How to include file in a bash shell script

后端 未结 5 807
不知归路
不知归路 2021-01-29 23:53

Is there a way to include another shell script in a shell script to be able to access its functions?

Like how in PHP you can use the include directive with

相关标签:
5条回答
  • 2021-01-30 00:27

    Simply put inside your script :

    source FILE
    

    Or

    . FILE # POSIX compliant
    

    $ 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.
    
    0 讨论(0)
  • 2021-01-30 00:29

    Syntax is source <file-name>

    ex. source config.sh

    script - config.sh

    USERNAME="satish"
    EMAIL="satish@linuxconcept.com"
    

    calling script -

    #!/bin/bash
    source config.sh
    echo Welcome ${USERNAME}!
    echo Your email is ${EMAIL}.
    

    You can learn to include a bash script in another bash script here.

    0 讨论(0)
  • 2021-01-30 00:30

    Yes, use source or the short form which is just .:

    . other_script.sh
    
    0 讨论(0)
  • 2021-01-30 00:35

    In my situation, in order to include color.sh from the same directory in init.sh, I had to do something as follows.

    . ./color.sh
    

    Not sure why the ./ and not color.sh directly. The content of color.sh is as follows.

    RED=`tput setaf 1`
    GREEN=`tput setaf 2`
    BLUE=`tput setaf 4`
    BOLD=`tput bold`
    RESET=`tput sgr0`
    

    Making use of File color.sh does not error but, the color do not display. I have tested this in Ubuntu 18.04 and the Bash version is:

    GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

    0 讨论(0)
  • 2021-01-30 00:39

    Above answers are correct, but if run script in other folder, there will be some problem.

    For example, the a.sh and b.sh are in same folder, a include b with . ./b.sh to include.

    When run script out of the folder, for example with xx/xx/xx/a.sh, file b.sh will not found: ./b.sh: No such file or directory.

    I use

    . $(dirname "$0")/b.sh
    
    0 讨论(0)
提交回复
热议问题