Why you shouldn’t parse the output of ls?

When people try to use ls to get a list of filenames (either all files, or files that match a glob, or files sorted in some way) things fail disastrously.

If you just want to iterate over all the files in the current directory, use a for loop and a glob:

# Bad
for f in `ls`
do 
...
done
# Good!
 for f in *; do
 [[ -e $f ]] || continue
 ...
 done

Consider also using “shopt -s nullglob” so that an empty directory won’t give you a literal ‘*’.

# Good! (Bash-only)
 shopt -s nullglob
 for f in *; do
 ...
 done

Source: http://mywiki.wooledge.org/ParsingLs

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