Heutzutage finden Sie normalerweise eine POSIX-Shell auf einem System, und dies bedeutet im Allgemeinen, dass Sie Skripte in der POSIX-Sprache ausführen können (modulo führt zu Compliance-Fehlern).
Das einzige Problem ist, dass /bin/shes manchmal keine POSIX-Shell gibt. Und Sie müssen die #!Zeile in Skripten fest codieren, die sich als nette ausführbare Dateien verhalten sollen. Sie können den Benutzer nicht einfach auffordern, das Problem zu untersuchen und dann Ihr Skript als aufzurufen /path/to/posix/shell myscript.
Der Trick besteht also darin, POSIX-Funktionen in Ihrem Skript zu verwenden, das Skript jedoch automatisch die POSIX-Shell finden zu lassen. Eine Möglichkeit ist wie folgt:
#!/bin/sh
# At this point, we may be running under some old shell
# we have to tread carefully.
# note how we use test rather than [ ] syntax and avoid
# depending on test with no argument producing a failure;
# i.e. "test $posix_shell".
if ! test x$posix_shell = x ; then
# the three possible shell paths are just an example;
# please extend as necessary.
for shell in /usr/xpg4/bin/sh /bin/bash /usr/bin/bash ; do
if test -x $shell ; then
posix_shell=$shell
fi
done
if test x$posix_shell = x ; then
echo "no POSIX shell found"
exit 1
# or we could avoid bailing here and just fall back on /bin/sh:
# echo "falling back on /bin/sh: cross your fingers that it works"
# posix_shell=/bin/sh
fi
export posix_shell
# plain "$@" is broken in ancient shells!
# I seem to recall ${@+"$@"}: not sure if that's the right trick.
exec $posix_shell $0 ${@+"$@"} # can we count on exec in legacy shells?
fi
# phew, at this point in the script we have been re-executed and are
# being interpreted by some reasonably modern shell. We can use $(...)
# command substitution, and other features.
Es gibt andere Ansätze, beispielsweise die Codegenerierung. Boostrapen Sie Ihre Skripte mit einem kleinen Skript, das eine Reihe von Skriptdateien ohne ein # enthält! Zeile und fügt eine hinzu.
Das Schlimmste, was Sie tun können, ist, ganze Skripte so zu schreiben, dass sie ab 1981 auf einer Bourne-Shell ausgeführt werden. Dies ist nur erforderlich, wenn Sie für ein System schreiben müssen, das wirklich keine andere Shell hat .