传递给另一个脚本时,Linux shell脚本参数扩展

时间:2014-10-13 08:48:32

标签: shell

我有2个shell脚本,请说a.sh和b.sh. a.sh如下。

    #!/bin/sh

    arg1="$1"   //contains path of b.sh
    arg2="$2"  //contains "-ab  'val1 val2'"
    arg3="$3"  //contains "val3"

    arg2=$(echo $arg2 | tr "'" '"')  // replace single quote with double quote 

    # call second shell script
   "b.sh" $arg2 $arg3

在b.sh。

    #!/bin/sh

    arg_b1="$1" //coming as "-ab"    - ok
    arg_b2="$2" //coming as "val1    - not ok  expecting "val1 val2"
    arg_b3="$3" //coming as val2"    - not ok expecting "val3"

我希望得到arg_b2为" val1 val2"因为他们在通过时双引号内。但事实并非如此。 请帮忙解决这个问题?

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

a.sh:

#!/bin/sh
arg1="$1"   # contains path of b.sh
arg2="$2"   # contains "-ab  'val1 val2'"
arg3="$3"   # contains "val3"

arg2=$( echo "$arg2" | tr "'" '"' )  # replace single quote with double quote

    # call second shell script
sh -c "\"$arg1\" $arg2 $arg3"

b.sh:

#!/bin/bash

echo "{$1}"
echo "{$2}"
echo "{$3}"

我认为这会产生符合您意图的结果。