Most shells 'exec' the last command in -c scripts, e.g.:

$ bash -c 'printf "$$ "; sh -c "echo \$\$"'
66303 66303
$ dash -c 'printf "$$ "; sh -c "echo \$\$"'
66304 66304
$ ksh93 -c 'printf "$$ "; sh -c "echo \$\$"'
66305 66305
$ yash -c 'printf "$$ "; sh -c "echo \$\$"'
66309 66309
$ zsh -c 'printf "$$ "; sh -c "echo \$\$"'
66310 66310

However, no shell seems to do this for scripts loaded from a file:

$ echo 'printf "$$ "; sh -c "echo \$\$"' >/tmp/test.sh
$ chmod +x /tmp/test.sh
$ bash /tmp/test.sh
66325 66326
$ dash /tmp/test.sh
66327 66328
$ /bin/ksh /tmp/test.sh
66329 66330
$ yash /tmp/test.sh
66331 66332
$ zsh /tmp/test.sh
66333 66334

My question: why is this? I would have thought that a script is a script and that it should make no essential difference whether a script is taken from a -c argument or loaded from a file. What makes the optimisation appropriate for one but not the other?

ksh93 used to use this exec-the-last-command optimisation also for scripts loaded from a regular file, but disabled this (keeping it only for -c scripts) in version 2011-12-24. The corresponding changelog entry is characteristically uninformative, so doesn't help answer my question. Now that a couple of redirection-related bugs have been fixed with that optimisation, we've re-enabled it for regular scripts in ksh 93u+m ahead of releasing the first beta of this reboot (Very Soon Now(tm)), but if there is a good reason that shouldn't be done, we should revert this.

--
||      modernish -- harness the shell
||      https://github.com/modernish/modernish
||
||      KornShell lives!
||      https://github.com/ksh93/ksh

  • execve(2) optimisat... Martijn Dekker via austin-group-l at The Open Group

Reply via email to