如何调用shell脚本并从另一个shell脚本传递参数 [英] How to call a shell script and pass argument from another shell script

查看:161
本文介绍了如何调用shell脚本并从另一个shell脚本传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从另一个 shell 脚本调用一个 shell 脚本,被调用的脚本需要一些输入(命令行)参数.
我有下面提到的代码,但这不起作用.我不知道为什么参数值没有传递给被调用的脚本.

I'm calling a shell script from another shell script and the called script requires some input (command line) parameters.
I'm have below mentioned code, but thats not working. I don't know why the argument values are not passed to the called script.

script1.sh
=======================================
#!/bin/bash
ARG1="val1"
ARG2="val2"
ARG3="val3"
. /home/admin/script2.sh "$ARG1" "$ARG2" "$ARG3"


script2.sh
=======================================
#!/bin/bash
echo "arg1 value is: $1 ....."
echo "arg2 value is: $2 ....."
echo "arg3 value is: $3 ....."

但是当我执行 script1.sh 时,我得到以下结果:

But when I execute script1.sh I get following result:

arg1 value is:  .....
arg2 value is:  .....
arg3 value is:  .....

我错过了什么?

推荐答案

通过使用 获取第二个脚本./home/admin/script2.sh,您实际上是将它包含在第一个脚本中,因此您可以在 $@ 中获得原始脚本的命令行参数.如果你真的想用参数调用另一个脚本,那么做

By sourcing the second script with . /home/admin/script2.sh, you're effectively including it in the first script, so you get the command line arguments to the original script in $@. If you really want to call the other script with arguments, then do

/home/admin/script2.sh "$ARG1" "$ARG2" "$ARG3"

(确保它是可执行的).

(make sure it's executable).

这篇关于如何调用shell脚本并从另一个shell脚本传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆