2

I am trying to pass arguments from a bash script to an executable and one of them contains spaces. I have been searching how to solve this, but I cannot find the right way to do it. Minimal example with a script called first and a script called second.

first script:

#!/bin/bash
# first script
ARGS="$@"
./second $ARGS

second script:

#!/bin/bash
# second script
echo "got $# arguments"

Now if I run it like this, I get the following results:

$ ./first abc def
got 2 args
$ ./first "abc def"
got 2 args
$ ./first 'abc def'
got 2 args

How can I make it so, that the second script also only receives one argument?

4

2 回答 2

4

你不能使用中间变量来做到这一点。如果您引用它将始终传递 1 个参数,否则您将丢失引号。

但是,如果您不使用这样的变量,则可以直接传递参数:

./second "$@"

 

$ ./first abc def
got 2 arguments
$ ./first "abc def"
got 1 arguments

或者,您可以使用数组来存储参数,如下所示:

#!/bin/bash
# first script
ARGS=("$@")
./second "${ARGS[@]}"
于 2013-08-09T14:09:29.797 回答
0

IFS 是您的朋友。

#!/bin/bash
# first script
ARGS="$@"
IFS=$(echo -en "\n\b")
./second $ARGS

IFS 代表内部场分离器...

于 2013-08-09T14:21:24.483 回答