[CentOS] bash - safely pass untrusted strings?

Tue Feb 26 23:24:47 UTC 2008
Stephen Harris <lists at spuddy.org>

On Tue, Feb 26, 2008 at 05:30:12PM -0500, Jacques B. wrote:

> If I understand you correctly, you are referring to the problem caused
> by spaces in filenames?  Steve mentioned the environment variable IFS
> ("individual field separator" if memory serves me correctly).  By
> default it's space, tab, or newline.  You can change that in your
> script to be newline only in order to process file names with spaces
> in it, and then change it back afterwards (so save the value of $IFS
> at the beginning of the script to something like Default_IFS and then
> just prior to exiting the script reassign that value back to IFS to
> return it to its original state).  If that's what you are looking at

You don't need to do any of that in a script, because scripts are run as
a sub-process and don't impact the current environment.  You only need to
save/restore IFS if you're doing this as part of a larger script (or as a
function called in the current shell).

However, spaces AREN'T an issue with proper quoting.

  $ touch "a file with spaces in"
  $ touch "another file"
  $ ls
  a file with spaces in  another file
  $ for a in *
  > do
  > echo "File: $a"
  > done
  File: a file with spaces in
  File: another file

Indeed, carriage returns aren't an issue either!

  $ a=$(echo "a\nb")
  $ touch "$a"
  $ touch c
  $ ls
  a?b  c
[ Note the ? in the ls output; that's "ls" saying there's a funny character! ]
  $ for a in *
  > do
  > echo "File: $a"
  > done
  File: a
  b
  File: c

All works nicely.

You only need to use find if you're doing things deep down in a directory
tree.

-- 

rgds
Stephen