简体   繁体   English

在另一个脚本中运行bash脚本时,父脚本中定义的所有变量是否都继承给孩子?

[英]When running a bash script within another script, are all variables defined in the parent script inherited to the child?

For example, say I have script1.sh and I need to call script2.sh. 例如,假设我有script1.sh,我需要调用script2.sh。 Will script2.sh be able to use any variables defined script1.sh? script2.sh能够使用定义为script1.sh的任何变量吗? If yes, if I went a step deeper and called script3.sh within script2.sh, would that have access to script1.sh variables? 如果是,那么如果我更进一步,在script2.sh中调用script3.sh,那可以访问script1.sh变量吗?

If not, what would have to be done to achieve that? 如果没有,那么必须要做些什么呢?

Only the exported variables are accessible in the called script: 在调用的脚本中只能访问导出的变量:

1.sh 1.sh

#! /bin/bash
export exported=1
not_exported=2
2.sh

2.sh 2.sh

#! /bin/bash
echo $exported
echo $not_exported

Running 1.sh only outputs 1 . 运行1.sh仅输出1

You can export a variable only for a dingle call by assigning to it before the call: 您可以通过在调用之前为其分配变量来仅导出该调用的变量:

not_exported=3 2.sh

There are three ways a variable may be made available for use by a script launched by another script : 可以使用三种方式使变量由另一个脚本启动的脚本使用:

  • Marking the variable for export (such as with the export keyword used at the time of declaration or afterwards, or by using the - x option of declare , local or typeset ) ; 将变量标记为导出(例如,在声明时或声明之后使用export关键字,或通过使用declarelocaltypeset x选项);

  • Putting an assignment for the variable as a prefix to the command being executed (eg varname=1 command and args ), separated by spaces only ; 将变量的赋值作为要执行的命令的前缀(例如varname=1 command and args ),仅以空格分隔;

  • Calling the child script with source or . 使用source或调用子脚本. , which causes the script to be read and interpreted by the current shell instead of being launched as a separate process, and therefore makes all variables of the current context (including local variables) available to the child script. ,这导致脚本由当前外壳程序读取和解释,而不是作为单独的进程启动,因此使当前上下文的所有变量(包括局部变量)可供子脚本使用。

Note that marking a variable for export will cause this variable to be copied to the memory space of the child process, and this copy then becomes independent from the variable of the parent shell : modifying it in the child will not change the value in the parent. 请注意,将变量标记为导出将导致该变量被复制到子进程的内存空间中,然后此副本变得独立于父shell的变量:在子进程中对其进行修改不会更改父进程中的值。

Using source or . 使用source. is the only way you can cause a child script to modify variables in the parent script, as a child process never has access to the memory space of its parent. 这是导致子脚本修改父脚本中变量的唯一方法,因为子进程永远无法访问其父级的内存空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM