Yves
Yves

Reputation: 12431

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"

Upvotes: 0

Views: 155

Answers (1)

Eric Renouf
Eric Renouf

Reputation: 14520

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[@]}"

Upvotes: 3

Related Questions