[clug] Help with bash script

steve jenkin sjenkin at canb.auug.org.au
Sun Nov 2 04:21:34 GMT 2008


Hal Ashburner wrote on 1/11/08 9:09 PM:

> 
> Yep, but if you're me and you're a bit soft in the head you think bash* will
> be consistent:
> 
> for F in $(ls); do echo "$F"; done
> a
> b
> b
> c
> c
> c
> prompt $
> 
> But you forget that's what it's going to do so can't see the massive bug in
> the middle of a script where you want this stuff to work every time.

It is consistent.
 $(...) is the same as `...` and needs to be quoted as well if you want
to preserve whitespace-within-strings.

prompt $ for F in "$(ls)"; do echo "$F"; done
a
b b
c c c
prompt $


Another trick is to use `ls -1|grep xxx`, instead of 'ls'...
didn't improve things here :-(

The semantics for backticks are something like "replace the expression
with the output of the command".  'sh' and derivatives think of the
command line as "a series of words", words are separated by 'whitespace'
 - which includes 'newline'.

With the same dir as above, try:
         F="$(ls -1)";echo $F;echo "$F"
         echo "$F"|grep '[ab]'

If you have a not-too-large file that you want to search multiple times,
you can slurp it into a shell variable and use 'echo "$F"|grep ...'.
It's useful if the file contents might change, like something is /proc.

Hard ('...') and Soft ("...") quoting makes the contained string a
single word. Variable substitution is done within Soft quotes, not Hard.
That includes backticks and \xxx.

It's easy with Soft quotes to create a string containing *all*
permissible characters - including `, ', ", $.

With Hard quotes, it's trivial to create *almost* any string - barring '
- the termination char.

Anyone got a nice way to do this??? [real question, not rhetorical]


HTH
sj
-- 
Steve Jenkin, Info Tech, Systems and Design Specialist.
0412 786 915 (+61 412 786 915)
PO Box 48, Kippax ACT 2615, AUSTRALIA

sjenkin at canb.auug.org.au http://members.tip.net.au/~sjenkin


More information about the linux mailing list