在使用" shift"之后,将参数传递给另一个脚本。内置

时间:2015-11-10 23:28:53

标签: bash

考虑一个简单的脚本program.sh

$ cat program.sh
echo program: I have "$#" arguments, they are "$@"
$ ./program.sh 1 2 3
program: I have 3 arguments, they are 1 2 3
$ ./program.sh '1 1' 2 3
program: I have 3 arguments. they are 1 1 2 3

现在我想要一个包装脚本wrapper.sh,它以与调用它相同的方式调用program.sh

$ cat wrapper.sh
echo wrapper: I have "$#" arguments, they are "$@"
./program.sh "$@"
$ ./wrapper.sh 1 2 3
wrapper: I have 3 arguments, they are 1 2 3
program: I have 3 arguments, they are 1 2 3
$ ./wrapper.sh '1 1' 2 3
wrapper: I have 3 arguments. they are 1 1 2 3
program: I have 3 arguments. they are 1 1 2 3

这很有效,但我想在shift中使用内置wrapper.sh,这会产生问题,因为我在"$@"的调用中不再使用program.sh

$ cat wrapper.sh
echo wrapper: I have "$#" arguments, they are "$@"
shift
./program.sh "$@"
$ ./wrapper.sh 1 2 3
wrapper: I have 3 arguments, they are 1 2 3
program: I have 2 arguments, they are 2 3
$ ./wrapper.sh '1 1' 2 3
wrapper: I have 3 arguments. they are 1 1 2 3
program: I have 2 arguments. they are 2 3

我最初尝试将$@的值设置为临时变量,但我尝试的任何内容似乎都不适用于wrapper.sh完全按照最初调用的方式调用program.sh。处理这个问题的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

保存$@很容易。只需将其保存为数组:

$ cat wrapper.sh 
echo wrapper: I have "$#" arguments, they are "$@"
save=("$@")
shift
./program.sh "${save[@]}"

这会产生输出:

$ wrapper.sh '1 1' 2 3
wrapper: I have 3 arguments, they are 1 1 2 3
program: I have 3 arguments, they are 1 1 2 3

这里的关键是save是一个bash数组。尝试将$@存储为shell字符串不起作用。将其保存为数组确实有效。