简体   繁体   中英

bash: How to pass arguments containing spaces

I have two bash scripts as below:

#main.sh
#!/bin/bash

files="file1 \"abc $1\" \"def $1\""

./upload.sh $files


#upload.sh
#!/bin/bash
for param in "$@"; do
    echo "${param}"
done

I'm trying to pass an argument containing a space to main.sh with the command as below:

edeMacBook-Pro:doc Yves$ ./main.sh "Sri Lanka"

I think $files will be like this: file1 "abc Sri Lanka" "def Sri Lanka" . So when I do ./upload.sh $files , three arguments should be passed to upload.sh .

However, when I execute the command, I get:

file1
"abc
Sri
Lanka"
"def
Sri
Lanka"

Rather than trying to build a single string that "looks like" a string with all the arguments (which you could then try to eval if you really want to go that route) try using an array:

files=("file1" "abc $1" "def $1")
upload.sh "${files[@]}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM