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! |
just add double quotes around your $1 in the if statement
Code:
#!/bin/bash |
Try putting quotes around $1 in the if line. Like so:
Code:
#!/bin/bash |
Oh, how very cool :D I wasn't aware that one *could* put quotes around a variable!
Thanks very much, both of you!! |
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... |
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. |