Way to often I get it wrong, so I decided to right this down…
When processing the list of arguments in your bash script, remember that often arguments such as file names contain spaces. The wrong way to go about this is:
#!/bin/bash for FILE in $* do echo "$FILE" done
The right way to do it is:
#!/bin/bash for FILE in "$@" do echo "$FILE" done
Advanced Bash-Scripting Guide explains the difference in “Internal Variables” chapter.
3 thoughts on “Handling arguments with spaces in bash”
I think this approach is incorrect. When filename is correctly passed to a program (e.g., space is escaped with \ ), it would appear as one single argument in your script, even if it has spaces.
Oops, I missed the point of your post. You’re right.
Its just that my usual approach to this problem is as follows:
while [ -n “$1” ] ; do echo $1 ; shift ; done