LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Spaces in bash parameters (https://www.linuxquestions.org/questions/programming-9/spaces-in-bash-parameters-299701/)

rose_bud4201 03-09-2005 01:26 PM

Spaces in bash parameters
 
*bangs head on monitor*

There must be some way to do this, but I can't seem to find it. For purely educational reasons, I am trying to figure out how to pass multiple-word parameters, i.e. "This is me", to a bash script, and have it evaluate correctly.
Inside the script, echoing $1 prints out "This is me" correctly, but the variable is not valid in if statements.

$ cat ./testscript.sh
#!/bin/bash

echo $1
if [ $1 = "This is me" ]; then
echo "Yay"
else
echo "No..."
fi
$ ./testscript.sh "This is me"
This is me
./testscript.sh: line 4: [: too many arguments
No...

Escaping the spaces (./testscript.sh "This\ is\ me") doesn't seem to work, and I'm not sure what else to try :(

Thanks!

drisay 03-09-2005 01:37 PM

just add double quotes around your $1 in the if statement

Code:

#!/bin/bash

echo $1
if [ "$1" = "This is me" ]; then
echo "Yay"
else
echo "No..."
fi


deiussum 03-09-2005 01:38 PM

Try putting quotes around $1 in the if line. Like so:

Code:

#!/bin/bash

echo $1
if [ "$1" = "This is me" ]; then
echo "Yay"
else
echo "No..."
fi

Edit: Beaten to it...

rose_bud4201 03-10-2005 08:29 AM

Oh, how very cool :D I wasn't aware that one *could* put quotes around a variable!

Thanks very much, both of you!!

chrism01 03-11-2005 12:21 AM

Very useful trick when dealing with filenames with spaces in them ... usually when dealing with Windows partitions/users...
Be aware that a lot of Unix cmds don't behave well with filenames with spaces in them, so try to avoid/convert as needed...

bigearsbilly 03-11-2005 06:57 AM

when using 'test' it's advisable to always
quote, otherwise it will often bomb out with spaces or
null variables
e.g:
Code:

[ -f "$filename" ] && echo OK || echo doh


All times are GMT -5. The time now is 12:47 PM.