简体   繁体   English

如何从另一个shell脚本调用一个shell脚本?

[英]How to call one shell script from another shell script?

I have two shell scripts, a.sh and b.sh .我有两个shell脚本a.shb.sh

How can I call b.sh from within the shell script a.sh ?我怎么能叫b.sh从shell脚本中a.sh

There are a couple of different ways you can do this:有几种不同的方法可以做到这一点:

  1. Make the other script executable, add the #!/bin/bash line at the top, and the path where the file is to the $PATH environment variable.使另一个脚本可执行,在顶部添加#!/bin/bash行,并将文件所在的路径添加到 $PATH 环境变量。 Then you can call it as a normal command;然后就可以作为普通命令调用了;

  2. Or call it with the source command (alias is . ) like this: source /path/to/script ;或者使用source命令(别名是. )调用它,如下所示: source /path/to/script ;

  3. Or use the bash command to execute it: /bin/bash /path/to/script ;或者使用bash命令执行: /bin/bash /path/to/script

The first and third methods execute the script as another process, so variables and functions in the other script will not be accessible.第一种和第三种方法将脚本作为另一个进程执行,因此其他脚本中的变量和函数将无法访问。
The second method executes the script in the first script's process, and pulls in variables and functions from the other script so they are usable from the calling script.第二种方法在第一个脚本的进程中执行脚本,并从另一个脚本中提取变量和函数,以便它们可以从调用脚本中使用。

In the second method, if you are using exit in second script, it will exit the first script as well.在第二种方法中,如果您在第二个脚本中使用exit ,它也会退出第一个脚本。 Which will not happen in first and third methods.这不会发生在第一种和第三种方法中。

Check this out.看一下这个。

#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."

There are a couple of ways you can do this.有几种方法可以做到这一点。 Terminal to execute the script:执行脚本的终端:

#!/bin/bash
SCRIPT_PATH="/path/to/script.sh"

# Here you execute your script
"$SCRIPT_PATH"

# or
. "$SCRIPT_PATH"

# or
source "$SCRIPT_PATH"

# or
bash "$SCRIPT_PATH"

# or
eval '"$SCRIPT_PATH"'

# or
OUTPUT=$("$SCRIPT_PATH")
echo $OUTPUT

# or
OUTPUT=`"$SCRIPT_PATH"`
echo $OUTPUT

# or
("$SCRIPT_PATH")

# or
(exec "$SCRIPT_PATH")

All this is correct for the path with spaces!!!所有这些对于带空格的路径都是正确的!!!

The answer which I was looking for:我正在寻找的答案:

( exec "path/to/script" )

As mentioned, exec replaces the shell without creating a new process.如前所述, exec替换 shell 而不创建新进程。 However , we can put it in a subshell, which is done using the parantheses.但是,我们可以将它放在子shell 中,这是使用括号完成的。

EDIT: Actually ( "path/to/script" ) is enough.编辑:实际上( "path/to/script" )就足够了。

If you have another file in same directory, you can either do:如果您在同一目录中有另一个文件,您可以执行以下操作:

bash another_script.sh

or要么

source another_script.sh

or要么

. another_script.sh

When you use bash instead of source , the script cannot alter environment of the parent script.当您使用bash而不是source ,脚本无法更改父脚本的环境。 The . . command is POSIX standard while source command is a more readable bash synonym for . command 是 POSIX 标准,而source command 是更易读的 bash 同义词. (I prefer source over . ). (我更喜欢source不是. )。 If your script resides elsewhere just provide path to that script.如果您的脚本驻留在别处,只需提供该脚本的路径。 Both relative as well as full path should work.相对路径和完整路径都应该有效。

Depends on.依赖于取决于。 Briefly... If you want load variables on current console and execute you may use source myshellfile.sh on your code.简而言之...如果您想在当前控制台上加载变量并执行,您可以在代码中使用source myshellfile.sh Example:例子:

!#/bin/bash
set -x
echo "This is an example of run another INTO this session."
source my_lib_of_variables_and_functions.sh
echo "The function internal_function() is defined into my lib."
returned_value=internal_function()
echo $this_is_an_internal_variable

set +x

If you just want to execute a file and the only thing intersting for you is the result, you can do:如果您只想执行一个文件,而唯一让您感兴趣的是结果,您可以执行以下操作:

!#/bin/bash
set -x
./executing_only.sh
sh i_can_execute_this_way_too.sh
bash or_this_way.sh
set +x

I hope helps you.我希望对你有帮助。 Thanks.谢谢。

You can use /bin/sh to call or execute another script (via your actual script):您可以使用/bin/sh调用或执行另一个脚本(通过您的实际脚本):

 # cat showdate.sh
 #!/bin/bash
 echo "Date is: `date`"

 # cat mainscript.sh
 #!/bin/bash
 echo "You are login as: `whoami`"
 echo "`/bin/sh ./showdate.sh`" # exact path for the script file

The output would be:输出将是:

 # ./mainscript.sh
 You are login as: root
 Date is: Thu Oct 17 02:56:36 EDT 2013

First you have to include the file you call:首先,您必须包含您调用的文件:

#!/bin/bash
. includes/included_file.sh

then you call your function like this:然后你像这样调用你的函数:

#!/bin/bash
my_called_function

Just add in a line whatever you would have typed in a terminal to execute the script!只需添加一行您在终端中键入的内容即可执行脚本!
eg:例如:

#!bin/bash
./myscript.sh &

if the script to be executed is not in same directory, just use the complete path of the script.如果要执行的脚本不在同一目录下,则使用脚本的完整路径即可。
eg:`/home/user/script-directory/./myscript.sh &例如:`/home/user/script-directory/./myscript.sh &

Simple source will help you.简单的来源会帮助你。 For Ex.对于前。

#!/bin/bash
echo "My shell_1"
source my_script1.sh
echo "Back in shell_1"

This was what worked for me, this is the content of the main sh script that executes the other one.这对我有用,这是执行另一个脚本的主 sh 脚本的内容。

#!/bin/bash 
source /path/to/other.sh

The top answer suggests adding #!/bin/bash line to the first line of the sub-script being called.最佳答案建议将#!/bin/bash行添加到被调用的子脚本的第一行。 But even if you add the shebang, it is much faster * to run a script in a sub-shell and capture the output:但是,即使您添加了shebang,在子shell 中运行脚本并捕获输出也会更快*

$(source SCRIPT_NAME)

This works when you want to keep running the same interpreter (eg from bash to another bash script) and ensures that the shebang line of the sub-script is not executed.当您想继续运行相同的解释器(例如从 bash 到另一个 bash 脚本)并确保不执行子脚本的 shebang 行时,这会起作用。

For example:例如:

#!/bin/bash
SUB_SCRIPT=$(mktemp)
echo "#!/bin/bash" > $SUB_SCRIPT
echo 'echo $1' >> $SUB_SCRIPT
chmod +x $SUB_SCRIPT
if [[ $1 == "--source" ]]; then
  for X in $(seq 100); do
    MODE=$(source $SUB_SCRIPT "source on")
  done
else
  for X in $(seq 100); do
    MODE=$($SUB_SCRIPT "source off")
  done
fi
echo $MODE
rm $SUB_SCRIPT

Output:输出:

~ ❯❯❯ time ./test.sh
source off
./test.sh  0.15s user 0.16s system 87% cpu 0.360 total

~ ❯❯❯ time ./test.sh --source
source on
./test.sh --source  0.05s user 0.06s system 95% cpu 0.114 total

* For example when virus or security tools are running on a device it might take an extra 100ms to exec a new process. *例如,当病毒或安全工具在设备上运行时,执行新进程可能需要额外的 100 毫秒。

 #!/bin/bash

 # Here you define the absolute path of your script

 scriptPath="/home/user/pathScript/"

 # Name of your script

 scriptName="myscript.sh"

 # Here you execute your script

 $scriptPath/$scriptName

 # Result of script execution

 result=$?
chmod a+x /path/to/file-to-be-executed

That was the only thing I needed.那是我唯一需要的东西。 Once the script to be executed is made executable like this, you (at least in my case) don't need any other extra operation like sh or ./ while you are calling the script.一旦要执行的脚本像这样可以执行,您(至少在我的情况下)在调用脚本时不需要任何其他额外的操作,例如sh./

Thanks to the comment of @Nathan Lilienthal感谢@Nathan Lilienthal 的评论

pathToShell="/home/praveen/"   
chmod a+x $pathToShell"myShell.sh"
sh $pathToShell"myShell.sh"

Assume the new file is "/home/satya/app/app_specific_env" and the file contents are as follows假设新建文件为“/home/satya/app/app_specific_env”,文件内容如下

#!bin/bash

export FAV_NUMBER="2211"

Append this file reference to ~/.bashrc file将此文件引用附加到 ~/.bashrc 文件

source /home/satya/app/app_specific_env

When ever you restart the machine or relogin, try echo $FAV_NUMBER in the terminal.当您重新启动机器或重新登录时, echo $FAV_NUMBER在终端中尝试echo $FAV_NUMBER It will output the value.它将输出值。

Just in case if you want to see the effect right away, source ~/.bashrc in the command line.以防万一,如果您想立即看到效果,请在命令行中输入source ~/.bashrc

There are some problems to import functions from other file.从其他文件导入函数存在一些问题。
First : You needn't to do this file executable.第一:您不需要执行此文件。 Better not to do so!最好不要这样做! just add只需添加

. file

to import all functions.导入所有函数。 And all of them will be as if they are defined in your file.所有这些都好像在您的文件中定义了一样。
Second : You may be define the function with the same name.第二:你可能定义了同名的函数。 It will be overwritten.它将被覆盖。 It's bad.这不好。 You may declare like that你可以这样声明

declare -f new_function_name=old_function_name 

and only after that do import.只有在那之后才能导入。 So you may call old function by new name.所以你可以用新名称调用旧函数。
Third : You may import only full list of functions defined in file.第三:您只能导入文件中定义的完整函数列表。 If some not needed you may unset them.如果有些不需要,您可以取消设置它们。 But if you rewrite your functions after unset they will be lost.但是如果你在 unset 之后重写你的函数,它们就会丢失。 But if you set reference to it as described above you may restore after unset with the same name.但是,如果您如上所述设置对它的引用,则可以在取消设置后使用相同的名称进行恢复。
Finally In common procedure of import is dangerous and not so simple.最后在普通的导入过程中是危险的,并不是那么简单。 Be careful!当心! You may write script to do this more easier and safe.您可以编写脚本来更轻松、更安全地执行此操作。 If you use only part of functions(not all) better split them in different files.如果您只使用部分功能(不是全部),最好将它们拆分到不同的文件中。 Unfortunately this technique not made well in bash.不幸的是,这种技术在 bash 中做得不好。 In python for example and some other script languages it's easy and safe.例如在 python 和其他一些脚本语言中,它既简单又安全。 Possible to make partial import only needed functions with its own names.可以只使用自己的名称部分导入需要的函数。 We all want that in next bush versions will be done the same functionality.我们都希望在下一个灌木版本中完成相同的功能。 But now We must write many additional cod so as to do what you want.但是现在我们必须编写许多额外的 cod 才能做你想做的事。

Use backticks.使用反引号。

$ ./script-that-consumes-argument.sh `sh script-that-produces-argument.sh`

Then fetch the output of the producer script as an argument on the consumer script.然后获取生产者脚本的输出作为消费者脚本的参数。

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

相关问题 如何从Unix中的shell脚本调用另一个shell脚本 - How to call another shell script from a shell script in Unix 如何根据第一个脚本的结果从另一个shell脚本调用shell脚本? - How to call a shell script from another shell script based on the first script's result? 如何将变量从一个Shell脚本返回到另一个脚本 - how to return a variable from one shell script to another script 如何从另一个用户的另一个Shell脚本中调用Shell脚本? - How to call shell script from another shell script from another user? 从另一个Shell脚本仅调用一个函数 - call only one function from another shell script Shell脚本:使用“ source / export”无法将变量从一个Shell脚本导出到另一个Shell脚本 - Shell script: exporting variables from one shell script to another shell script not working using “source/export” 如何从另一个Shell脚本运行Shell脚本 - How run a shell script from another shell script 如何从另一个 shell 脚本的数组变量替换一个 shell 脚本的数组变量? - How to replace an array variable of one shell script from another shell script's array variable? 如何从另一个 shell 脚本启动一个 shell 脚本作为进程 - How do I start one shell script as process from another shell script 如何将错误代码从一个Shell脚本捕获到另一个Shell脚本 - How to catch error code from one shell script into another shell script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM