How to make code include in Shell Script files

Asked

Viewed 1,773 times

3

How can I perform the following process:

Add the arquivoa.sh and arquivob.sh in the arquivoc.sh, and then perform the defined functions within each file

archivoa.sh

#!/bin/bash

echo "Arquivo A"
function funcaoA(){
  echo "Executando a funcao A"
}

arquivob.sh

#!/bin/bash

echo "Arquivo B"
function funcaoB(){
  echo "Executando a funcao B"
}

arquivoc.sh

#!/bin/bash

echo "Arquivo C"
funcaoA()
funcaoB()

the doubt is, how to perform the include of the other files within the file.sh?

I’m performing the tests on Ubuntu 16.

grateful

2 answers

7


To add a script within another and be able to make use of the functions it is necessary to add the following line at the beginning of the file

source <arquivo_alvo>

and to perform the function is not necessary ()

the code at the end will be as below

archivoa.sh

#!/bin/bash

echo "Arquivo A"
function funcaoA(){
  echo "Executando a funcao A"
}

arquivob.sh

#!/bin/bash

echo "Arquivo B"
function funcaoB(){
  echo "Executando a funcao B"
}

arquivoc.sh

#!/bin/bash
source ./arquivoa.sh # ./ para indicar que o arquivo esta na mesma pasta
source ./arquivob.sh

echo "Arquivo C"
funcaoA
funcaoB

while executing

bash arquivoc.sh

we will have the following exit

Arquivo A
Arquivo B
Arquivo C
Executando a funcao A
Executando a funcao B

realize that the echo of each file was executed. Then take care that your inserted file does not disrupt the flow of the main application.

4

Hello. Complementing the excellent answer given, it is worth remembering that, in addition to

source arquivo.sh

you can also use

. arquivo.sh

If there is no bar in the.sh file name, Shell will attempt to locate the referred file name in the system PATH. Still, as the file will be included, .sh file does not need to be executable.

According to the Bash manual page, if it is not in POSIX mode, the file will be searched in the local directory if it is not found in the PATH.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.