Defining common variables across multiple scripts?

前端 未结 2 1670
逝去的感伤
逝去的感伤 2021-01-13 15:32

I have a number of Bash and Perl scripts which are unrelated in functionality, but are related in that they work within the same project. The fact that they work in the same

2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 16:36

    When you run a shell script, it's done in a sub-shell so it cannot affect the parent shell's environment. So when you declare a variable as key=value its scope is limited to the sub-shell context. You want to source the script by doing:

    . ./myscript.sh
    

    This executes it in the context of the current shell, not as a sub shell.

    From the bash man page:

    . filename [arguments]
    source filename [arguments]
    
    Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename.
    
    If filename does not contain a slash, file names in PATH are used to find the directory containing filename. 
    

    Also you can use the export command to create a global environment variable. export governs which variables will be available to new processes, so if you say

    FOO=1
    export BAR=2
    ./myscript2.sh
    

    then $BAR will be available in the environment of myscript2.sh, but $FOO will not.

提交回复
热议问题