Samstag, 28. Februar 2009

Quoten von Shell Variablen

Heute habe ich in der AppleScript Mailinglist einen interessanten Beitrag von Mark J. Reed gelesen, der nicht nur für AppleScript Nutzer interessant ist.

Oft gibt es ja das Problem, daß man in Shell Scripten Parameter "herumreichen" muß. Mark hat das Thema "Quoting" darin schön zusammengefaßt:
Since I see lots of shell code being tossed around here, whether in do shell script strings or Terminal do scripts or scripts that invoke osascript, allow me to pass on a general tip: the best rule of thumb is to ALWAYS quote parameter expansions. Somewhat like macros in C, they are expanded *before* the shell does its normal compilation of the command (word splitting). So this:

foo="1 2 3 4"
somecommand $foo


calls "somecommand" with four arguments, not one. This is sometimes what you want, but frequently not. When I see bare $foo, I instinctively reach for the keyboard to turn it into "$foo" instead. :)

If you do want to expand something into a variable number of words, you can use an array instead of a string, especially if you find yourself trying to do yucky stuff like including quotes in the string and eval'ing the result (see above re: code generation).

foo=(1 "2 3" 4)
somecommand "${foo[@]}" # somecommand is called with three arguments


Array variables are, sadly, not POSIX-compliant. If that's an issue for you, one fallback is to use the shell's own positional parameters:

set -- 1 "2 3" 4
somecommand "$@" # calls somecommand with three arguments


..but that only works if you don't have data you care about already in the positional params.

Keine Kommentare:

Kommentar veröffentlichen