从另一个脚本调用一个Bash脚本,用引号和空格传递它的参数

nma*_*hok 45 bash shell double-quotes salt-stack

我在Linux上制作了两个测试bash脚本,以解决问题.

TestScript1看起来像:
    echo "TestScript1 Arguments:"
    echo "$1"
    echo "$2"
    echo "$#"
    ./testscript2 $1 $2
Run Code Online (Sandbox Code Playgroud) TestScript2看起来像:
    echo "TestScript2 Arguments received from TestScript1:"
    echo "$1"
    echo "$2"
    echo "$#"
Run Code Online (Sandbox Code Playgroud) 当我以下列方式执行testscript1时:
    ./testscript1 "Firstname Lastname" testmail@domain.com  
Run Code Online (Sandbox Code Playgroud) 期望的输出应该是:
    TestScript1 Arguments:  
    Firstname Lastname  
    testmail@domain.com  
    2
    TestScript2 Arguments received from TestScript1:  
    Firstname Lastname  
    testmail@domain.com  
    2  
Run Code Online (Sandbox Code Playgroud) 但实际输出是:
    TestScript1 Arguments:  
    Firstname Lastname  
    testmail@domain.com  
    2
    TestScript2 Arguments received from TestScript1:  
    Firstname
    Lastname      
    3  
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?我想获得所需的输出而不是实际的输出.

Mar*_* K. 42

在Testscript 1中引用你的args:

echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是一个不同的问题.您应该使用实际脚本中的一段代码提出一个新问题.您可以简化发布的代码,但在这种情况下,您将其简化为非常简单,以至于它不会出现您遇到的相同问题. (4认同)

Oli*_*lac 27

您需要使用:( "$@"带引号)或"${@}"(相同,但也告诉shell变量名称的开始和结束位置).

(并且不要使用:$@,或"$*",或$*).

例如:

#testscript1:
echo "TestScript1 Arguments:"
for an_arg in "$@" ; do
   echo "${an_arg}"
done
echo "nb of args: $#"
./testscript2 "$@"   #invokes testscript2 with the same arguments we received
Run Code Online (Sandbox Code Playgroud)

我不确定我是否理解你的其他要求(你想用单引号调用'./testscript2')所以这里有两个疯狂的猜测(改变上面的最后一行):

'./testscript2' "$@"  #only makes sense if "/path/to/testscript2" containes spaces?

./testscript2 '"some thing" "another"' "$var" "$var2"  #3 args to testscript2
Run Code Online (Sandbox Code Playgroud)

请告诉我你要做的确切事情

编辑:在他的评​​论说他尝试tesscript1"$ 1""$ 2""$ 3""$ 4""$ 5""$ 6"运行:盐'远程主机'cmd.run'./testscript2 $ 1 $ 2 $ 3 $ 4 $ 5 $ 6'

你有多个级别的中间件:主机1上的testscript1,需要运行"salt",并给它一个字符串启动带有参数的"testscrit2"...

您可以通过以下方式"简化":

#testscript1

#we receive args, we generate a custom script simulating 'testscript2 "$@"'
theargs="'$1'"
shift
for i in "$@" ; do
   theargs="${theargs} '$i'"
done

salt 'remote host' cmd.run "./testscript2 ${theargs}"
Run Code Online (Sandbox Code Playgroud)

如果THAt不起作用,那么不要运行"testscript2 $ {theargs}",而是替换上面的最后一行

echo "./testscript2 ${theargs}" >/tmp/runtestscript2.$$  #generate custom script locally ($$ is current pid in bash/sh/...)
scp /tmp/runtestscript2.$$ user@remotehost:/tmp/runtestscript2.$$ #copy it to remotehost
salt 'remotehost' cmd.run "./runtestscript2.$$" #the args are inside the custom script!
ssh user@remotehost "rm /tmp/runtestscript2.$$" #delete the remote one
rm /tmp/runtestscript2.$$ #and the local one
Run Code Online (Sandbox Code Playgroud)