web-dev-qa-db-fra.com

Comment inclure un fichier dans un script bash

Existe-t-il un moyen d'inclure un autre script Shell dans un script Shell pour pouvoir accéder à ses fonctions?

Comme dans PHP, vous pouvez utiliser la directive include avec d'autres fichiers PHP afin d'exécuter les fonctions contenues dans ce fichier en appelant simplement le nom de la fonction.

80
Mechaflash

Il suffit de mettre dans votre script:

source FILE

Ou

. FILE

c'est la même chose.

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current Shell.

Read and execute commands from FILENAME in the current Shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
148
Gilles Quenot

Oui, utilisez source ou la forme abrégée qui est simplement .:

. other_script.sh
29
Paulpro

Les réponses ci-dessus sont correctes, mais si vous exécutez le script dans un autre dossier, il y aura un problème.

Par exemple, a.sh et b.sh sont dans le même dossier, A include b, avec . ./b.sh à inclure.

Lorsque vous exécutez un script hors du dossier, par exemple avec xx/xx/xx/a.sh, le fichier b.sh ne sera pas trouvé: ./b.sh: No such file or directory

J'utilise 

. $(dirname "$0")/b.sh
21
Fancyoung