Вопрос

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?

Это было полезно?

Решение

You can't do it using an intermediate variable. If you quote it will always pass 1 argument, if you don't you will lose the quotes.

However, you can pass the arguments directly if you don't use the variable like this:

./second "$@"

 

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

Alternately, you can use an array to store the arguments like this:

#!/bin/bash
# first script
ARGS=("$@")
./second "${ARGS[@]}"

Другие советы

IFS is your friend .

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

IFS stands for Internal Field Separator ...

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top