How to include code in Shell Script files

3

How can I perform the following process:

Add arquivoa.sh and arquivob.sh into arquivoc.sh , and then execute the functions defined within each file

filea.sh

#!/bin/bash

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

archivob.sh

#!/bin/bash

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

archivoc.sh

#!/bin/bash

echo "Arquivo C"
funcaoA()
funcaoB()

The question is, how to perform the include of the other files inside the archivoc.sh?

I'm running tests on Ubuntu 16.

grateful

    
asked by anonymous 24.03.2017 / 16:20

2 answers

7

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

source <arquivo_alvo>

and to execute the function you do not need ()

The code in the end will look like below

filea.sh

#!/bin/bash

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

archivob.sh

#!/bin/bash

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

archivoc.sh

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

echo "Arquivo C"
funcaoA
funcaoB

when running

bash arquivoc.sh

We will have the following output

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

Notice that echo of each file has been executed. So be careful that your inserted file does not disturb the flow of the main application.

    
24.03.2017 / 16:20
4

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

source arquivo.sh

you can also use

. arquivo.sh

If there is no slash in the .sh file name, the Shell will try to find the file name in the system PATH. Still, since the file will be included, .sh file does not have 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.

    
24.03.2017 / 18:06