Shell scripting: working with files that have spaces in their names

Shell scripts are very useful for manipulating files, among other things. However, problem arises when some of the files in your target directories have spaces in their names. The error you will get in such cases is:

1
./test.sh: line 8: [: too many arguments

This sounds somewhat cryptic, but it’s perfectly logical, bash is using spaces as separators, so each word in a file name is seen as another argument. The workaround is to change the value of the internal IFS variable (which stands for Internal Field Separator). Here is an example that works:

 

1
2
3
4
5
6
7
8
9
#!/bin/bash
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for file in /var/www/html
do
  #do something here
  ...
done
IFS=$SAVEIFS

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image