Posts mit dem Label unix werden angezeigt. Alle Posts anzeigen
Posts mit dem Label unix werden angezeigt. Alle Posts anzeigen

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.

Mittwoch, 11. Februar 2009

PATH Variable setzen mit addpath

Manchmal möchte man als Unix User gerne seine PATH Variable um neue Eintraege erweitern. Ich hatte immer mal wieder das "Problem", daß Einträge dabei doppelt auftauchten, da sie schon im Standard enthalten waren.

Also habe ich mir vor einiger Zeit eine kleine Funktion gebastelt, die nur solche Werte aufnimmt, die nicht bereits enthalten sind:


addpath () {
left=''
P=$1
shift
while [ -n "$1" ]
do case $1 in
-l) left=1 ;;
-r) left='' ;;
*) case :$P: in
*:$1:*) ;;
*) if [ $left ] ; then P=$1:$P ; else P=$P:$1 ; fi ;;
esac ;;
esac
shift
done
echo $P
}


"addpath" wird einfach in die .profile oder .bashrc (je nach Vorliebe) einkopiert.


Der Aufruf erfolgt in dieser Form:

PATH=`addpath $PATH -l /usr/local/perl/perl-5.8.8/bin -r ~/bin`


Dies fügt "/usr/local/perl/perl-5.8.8/bin" vor dem aktuellen Pfad ein (links) und "~/bin" dahinter (rechts).

Ohne -l und -r wird nur rechts angefügt. -l und -r beziehen sich auf alle, dahinter stehenden Pfade.

addpath kann fuer alle Pfadvariablen verwendet werden, die wie PATH aufgebaut sind, also z.B. auch für MANPATH, PERL5LIB etc. pp.