[Nix-dev] slightly off topic: bash/sh quoting/arguments

Marc Weber marco-oweber at gmx.de
Mon Apr 2 23:42:10 CEST 2012


Yeah, that's OT.
on irc there is #bash which should be the source of knowledge to gather
some keywords. Nevertheless here is your solution

First get a test script (copy paste into your bash shell):

args1="one two"
args2="three four"
sh -c 'for x in "$@"; do echo arg: $x; done' -- $args1 $args2

it prints:
  arg: one
  arg: two
  arg: three
  arg: four

so you already have what you want. Now what if one is 'o n e'
(containing spaces?)

solution: use arrays:

args1=("o n e" "t w o")
args2=("t h r e e" "f o u r")
sh -c 'for x in "$@"; do echo arg: $x; done' -- "${args1[@]}" "${args2[@]}"

which yields:

    arg: o n e
    arg: t w o
    arg: t h r e e
    arg: f o u r

which is what you want. Add element to array:
  args1=("${args1[@]" "new arg")

zsh note: $foo corresponds to "$foo" of bash. ${=foo} corresponds to the
"treat spaces as arg separator" bash like behaviour (if you don't use
"") Thus its hard to write portable code.

In general use a scripting language (ruby/python/perl/tcl/..) for
everything more complicated. bash starts to be a bottle neck very soon
(example is top-git)

Marc Weber


More information about the nix-dev mailing list