Bash – Use .sh or .bash Extension for Bash Scripts?

bashshebangshell

(See Use #!/bin/sh or #!/bin/bash for Ubuntu-OSX compatibility and ease of use & POSIX)

If I want my scripts to use the bash shell, does using the .bash extension actually invoke bash or does it depend on system config / 1st shebang line. If both were in effect but different, which would have precedence?

I'm not sure whether to end my scripts with .sh to just indicate "shell script" and then have the first line select the bash shell (e.g. #!/usr/bin/env bash) or whether to just end them with .bash (as well as the line 1 setting). I want bash to be invoked.

Best Answer

does using the .bash extension actually invoke bash or does it depend on system config / 1st shebang line.

If you do not use an interpreter explicitly, then the interpreter being invoked is determined by the shebang used in the script. If you use an interpreter specifically then the interpreter doesn't care what extension you give for your script. However, the extension exists to make it very obvious for others what kind of script it is.

[sreeraj@server ~]$ cat ./ext.py
#!/bin/bash
echo "Hi. I am a bash script"

See, .py extension to the bash script does not make it a python script.

[sreeraj@server ~]$ python ./ext.py
  File "./ext.py", line 2
    echo "Hi. I am a bash script"
                                ^
SyntaxError: invalid syntax

Its always a bash script.

[sreeraj@server ~]$ ./ext.py
Hi. I am a bash script
Related Question