0

Situation: Writing a shell script to do some stuff across multiple shells

Problem: While Bourne-compatible shell scripts (bash, ksh, ash, zsh, etc) are easy to be made portable (just make sure the scripts are sh compatible and it should run across other Bourne-compatible shells), there are syntax differences compared to those that are not POSIX compatible such as csh and fish. The script will fail immediately when running on these shells due to syntax errors (expected).

Question: Is there any way to write a script in such a way that it can be executed across all shells regardless of POSIX-compatibility of the individual shells? I cannot think of a way to do so without triggering a syntax error leading to the script exiting itself.

8
  • 1
    A Bourne Shell compatible shell does not exit if you put the syntax error into parenthesis (subshell), see test in the script whatshell: in-ulm.de/~mascheck/various/whatshell – schily Aug 7 '20 at 5:36
  • So I can use the parenthesised command to test if the shell it is running on, and then subsequently use that to run different scripts that are written for that shell? – Timothy Wong Aug 7 '20 at 7:19
  • 1
    Unless you write an extremely simple script, you cannot be syntax neutral. – schily Aug 7 '20 at 7:22
  • 1
    The question starts off with the faulty premise that this is "writing a Bash script". "Bash" is not a shorthand for shell programming. It is a specific shell. – JdeBP Aug 7 '20 at 8:05
  • 1
    updated. thanks for pointing that out – Timothy Wong Aug 7 '20 at 8:17
0

Simple: Write only for /bin/sh. That one is guaranteed (by POSIX, also by tradition) to exist. Other shells can be superficially similar, or outrageously different. Check e.g. pirl, a shell that is Perl under the (thin) hood, or the Scheme Shell, with very much LISPish syntax.

One of the nice aspects of Unix is that the shell is a bog-standard user level program. But that means every hacker out there can write their own, demented variant. Trying to write in some nebulous intersection between all shells is just doomed. Writing for all "common used shells" means to define somehow what "in common use" means... and that is sure to infuriate someone.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.