color option for /bin/ls breaks shell scripts

Charles Jones charles.jones at ciscolearning.org
Wed Jul 2 13:41:08 MST 2008


Just thought I would share something I found while helping a friend 
troubleshoot a simple shellscript this morning.  His problem and 
solution were very simple, yet it was very not obvious to him at first. 
He had a script that was basically doing something like:

for file in `ls *.doc`; do ls -l $file /somedir; done

Yes I know the command itself is the same as ls -l *.doc, but he was 
just testing out basic variable expansion and loops in shell scripts.
He was getting "No such file or directory" errors. I thought it was 
strange, because the syntax looked fine to me.  I tried it on my machine 
and the same command worked fine.

I made sure it wasn't an issue with having to escape the wildcard in a 
subshell, or that his IFS variable was mucked with.
He then tried this command:
for file in `ls *.doc`; do mv -v $file /somedir; done
This time not only did he get the "No such file or directory" error, but 
also something like "mv: cannot stat  '\033[00mfoo.doc'
I immediately recognized these as ANSI color codes and sure enough, he 
had an alias set for ls='ls --color'.

So, the color codes were being prefixed to the filenames and so it could 
not find them. The error message for ls stripped the codes, so it was 
not obvious, but the mv command included them in literal form.

So he learned some valuable lessons:
1. Always call binaries by their full path (use /bin/ls) so you don't 
get bitten by an alias or something in $PATH overriding
2. bash -x -c 'command(s)' is helpful for debugging command-line shell
3. In some cases it's better to use something like: find . -name \*doc 
-exec command \;

-Charles


More information about the PLUG-discuss mailing list