Bash “for” loop breaks at spaces in file names

Say, you want to batch create a set of soft links to files.

The first example will not work, as directory and file names with spaces in them will be broken into separate words:

currdir=`pwd`; for i in `ls *.mpg` ; do ln -s $currdir/$i /tmp/destinationdir; done

This example will work just fine:

currdir=`pwd`; for i in *.mpg ; do ln -s "$currdir"/"$i" /tmp/destinationdir; done

Tips:

  • Do not use ls or find to get the file names, instead use the bash shell’s built-in functions!
  • Enclose the variable names in double quotes!
Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s