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

Mathijs Kwik mathijs at bluescreen303.nl
Tue Apr 3 00:19:51 CEST 2012


On Mon, Apr 2, 2012 at 11:42 PM, Marc Weber <marco-oweber at gmx.de> wrote:
> 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.

Ah, that's it then. it seems ${=foo} doesn't do the trick in zsh
either though, but I don't care. It's not the target, I just tried it
there.

>
> 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)

Many tools (openvpn, dhcpcd, wicd) allow you to hook into certain
events just by placing a small shell script somewhere. Of course you
can invoke whatever you like from there, but loading ruby isn't
exactly cheap :)
So I wanted to stick to sh here.

But I fully agree on your general point. Any useful utility you want
to start should probably not be in bash. Problem always is that things
start out in 4 lines of bash. But a week later it's 40 :)

I recently toyed around a bit with shelly [1], which is haskell's take
on scripting. I must say it's pretty fun. If you compile to static
binaries, there's an advantage over python/ruby/perl because it
doesn't need a runtime env installed.

Anyway, thanks for your extended answer.

[1] http://hackage.haskell.org/package/shelly-0.3.1

>
> Marc Weber
> _______________________________________________
> nix-dev mailing list
> nix-dev at lists.science.uu.nl
> http://lists.science.uu.nl/mailman/listinfo/nix-dev


More information about the nix-dev mailing list