Calling one Bash script from another Script passing it arguments with quotes and spaces

前端 未结 3 1702
渐次进展
渐次进展 2020-12-23 13:17

I made two test bash scripts on Linux to make the problem clear.

TestScript1 looks like:
    echo \"TestScript1 Arguments:\"
    echo \"$1\"
             


        
相关标签:
3条回答
  • 2020-12-23 13:59

    Quote your args in Testscript 1:

    echo "TestScript1 Arguments:"
    echo "$1"
    echo "$2"
    echo "$#"
    ./testscript2 "$1" "$2"
    
    0 讨论(0)
  • 2020-12-23 14:08

    You need to use : "$@" (WITH the quotes) or "${@}" (same, but also telling the shell where the variable name starts and ends).

    (and do NOT use : $@, or "$*", or $*).

    ex:

    #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
    

    I'm not sure I understood your other requirement ( you want to invoke './testscript2' in single quotes?) so here are 2 wild guesses (changing the last line above) :

    './testscript2' "$@"  #only makes sense if "/path/to/testscript2" containes spaces?
    
    ./testscript2 '"some thing" "another"' "$var" "$var2"  #3 args to testscript2
    

    Please give me the exact thing you are trying to do

    edit: after his comment saying he attempts tesscript1 "$1" "$2" "$3" "$4" "$5" "$6" to run : salt 'remote host' cmd.run './testscript2 $1 $2 $3 $4 $5 $6'

    You have many levels of intermediate: testscript1 on host 1, needs to run "salt", and give it a string launching "testscrit2" with arguments in quotes...

    You could maybe "simplify" by having:

    #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}"
    

    if THAt doesn't work, then instead of running "testscript2 ${theargs}", replace THE LAST LINE above by

    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
    
    0 讨论(0)
  • 2020-12-23 14:12

    I found following program works for me

    test1.sh 
    a=xxx
    test2.sh $a
    

    in test2.sh you use $1 to refer variable a in test1.sh

    echo $1

    The output would be xxx

    0 讨论(0)
提交回复
热议问题