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?
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).
$() 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.
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:
sh your_script.sh
and see what happens - Bash is a superset of sh
syntax, so many simple Bash scripts are valid sh
scripts.sh -n your_script.sh
as rojomoke suggests, which will report syntax errors without actually executing the script (but may not catch all issues).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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With