问题原文
原帖链接 · cherouvim · CC BY-SA 3.0
I usually work with Ubuntu LTS servers which from what I understand symlink /bin/sh to /bin/dash. A lot of other distros though symlink /bin/sh to /bin/bash.
From that I understand that if a script uses #!/bin/sh on top it may not run the same way on all servers?
Is there a suggested practice on which shell to use for scripts when one wants maximum portability of those scripts between servers?
社区高分解答
原帖链接 · Kaz · CC BY-SA 3.0
In the ./configure script which prepares the TXR language for building, I wrote the following prologue for better portability. The script will bootstrap itself even if #!/bin/sh is a non-POSIX-conforming old Bourne Shell.
(I build every release on a Solaris 10 VM).
#!/bin/sh
# use your own variable name instead of txr_shell;
# adjust to taste: search for your favorite shells
if test x$txr_shell = x ; then
for shell in /bin/bash /usr/bin/bash /usr/xpg4/bin/sh ; do
if test -x $shell ; then
txr_shell=$shell
break
fi
done
if test x$txr_shell = x ; then
echo "No known POSIX shell found: falling back on /bin/sh, which may not work"
txr_shell=/bin/sh
fi
export txr_shell
exec $txr_shell $0 ${@+"$@"}
fi
# rest of the script here, executing in upgraded shell
The idea here is that we find a better shell than the one we are running under, and re-execute the script using that shell. The txr_shell environment variable is set, so that the re-executed script knows it is the re-executed recursive instance.
(In my script, the txr_shell variable is also subsequently used, for exactly two purposes: firstly it is printed as part of an informative message in the output of the script. Secondly, it is installed as the SHELL variable in the Makefile, so that make will use this shell too for executing recipes.)
On a system where /bin/sh is dash, you can see that the above logic will find /bin/bash and re-execute the script with that.
On a Solaris 10 box, the /usr/xpg4/bin/sh will kick in if no Bash is found.
The prologue is written in a conservative shell dialect, using test for file existence tests, and the ${@+"$@"} trick for expanding arguments catering to some broken old shells (which would simply be "$@" if we were in a POSIX conforming shell).
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
