Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
Thusitha Thilina Dayaratne Avatar asked Jul 24 '15 09:07

Thusitha Thilina Dayaratne


People also ask

Is bash compatible with sh?

Bash is largely compatible with sh and incorporates useful features from the Korn shell ksh and the C shell csh. It is intended to be a conformant implementation of the IEEE POSIX Shell and Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1).

What is $() in bash?

$() means: "first evaluate this, and then evaluate the rest of the line". Ex : echo $(pwd)/myFile.txt. will be interpreted as echo /my/path/myFile.txt. On the other hand ${} expands a variable.


1 Answers

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.

like image 187
dimo414 Avatar answered Sep 30 '22 06:09

dimo414