Check if Bash script is compatible with sh

I have a script where it is defined #!/bin/bash, and I want to check if this script is compatible with #!/bin/sh.

Is there a way to do so?

Upvotes: 9

Views: 4238

Answers (2)

dimo414
dimo414

Reputation: 48874

Being sh-compatible isn't, in itself, a goal. What issue(s) are you running into that requires your script work with sh? Depending on your reasoning different options may or may not be sufficient. If you simply need your script to run on most modern environments then using bash should be perfectly fine, and may actually be better than using sh, since sh maps to different shells on different platforms. On most modern environments it isn't actually its own binary but is just bash in POSIX-compliant mode, or another shell like dash.

If you really just need to make an existing Bash script work with the shebang #!/bin/sh you have several options:

  1. Just run it as sh your_script.sh and see what happens - Bash is a superset of sh syntax, so many simple Bash scripts are valid sh scripts.
  2. Run sh -n your_script.sh as rojomoke suggests, which will report syntax errors without actually executing the script (but may not catch all issues).
  3. Manually audit your script for invalid syntax (John B's Bashisms reference isn't a bad start), this obviously isn't a great solution but in practice it's the only way to be sure. If that seems daunting, well, it is :)

If you want/need to support sh the best option is simply to specify your script's shebang as #!/bin/sh - if it behaves as desired in the environments you need it to then it's (by definition) sh-compatible.

Note that you can write a sh-compatible script that still isn't POSIX-compliant, since many standard utilities like grep have their own POSIX-compliant feature sets you'd need to respect too. Again though, being POSIX-compliant isn't an end in itself, and I'd encourage you to confirm you really need to support POSIX before trying to be compliant with the standard.

I asked a related question you might find helpful too.

Upvotes: 7

rojomoke
rojomoke

Reputation: 4025

Running the script with the -n option will parse and read the commands, and report syntax errors, but will not execute the code.

sh -n <scriptname>

Upvotes: 5

Related Questions