Hi script-writers,
The day came when I had to write a BASH script that walks arbitrary directory trees and looks at arbitrary files and attempts to determine something regarding a comparison among them. I thought it would be a simple couple-of-hours_tops!_ process - Not So!
My hangup is that sometimes some idiot -ahem!- excuse me, _lovely_user_ chooses to put spaces in directory and file names. This causes my script to fail.
The perfect solution, aside from threatening the guillotine for those who insist on using spaces in such places (not to mention the guys who put this in operating systems' code!), might be a routine that "escapes" the file and directory names for us, kind of like how cygwin has routines to convert from unix to dos filename formats. Is there anything like this in a standard Unix / Linux distribution?
Note that the simple for file in *
construct doesn't work so well when one is trying to compare directory trees as it ONLY works on "the current directory" - and, in this case as in many others, constantly CDing to various directory locations brings with it its own problems. So, in doing my homework, I found this question http://stackoverflow.com/questions/1563856/handle-special-characters-in-bash-for-in-loop and the proposed solution there hangs up on spaces in directory names, but can simply be overcome like this:
dir="dirname with spaces"
ls -1 "$dir" | while read x; do
echo $x
done
PLEASE NOTE: The above code isn't particularly wonderful because the variables used inside the while loop are INACCESSIBLE outside that while loop. This is because there's an implied subshell created when the ls command's output is piped. This is a key motivating factor to my query!
...OK, the code above helps for many situations but "escaping" the characters would be pretty powerful too. For example, dir above might contain:
dir\ with\ spaces
Does this already exist and I've just been overlooking it?
If not, does anyone have an easy proposal to write one - maybe with sed or lex? (I'm far from competent with either.)