Use .sh or .bash extension for Bash scripts?

(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 or the first 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 setting in the first line).

I want Bash to be invoked.

Asked By: Michael Durrant

||

The naming of the script has nothing to do with how it’s run.

The shebang line defines what interpreter is used to run the script.

I personally don’t care if a script is sh, bash, perl, whatever so I just name it for what it does; I find adding an extension redundant. I’ll do file scriptname to find out what the file is if I want to know that.

So if you want your script to be run with bash, use #!/bin/bash as the first line.

Answered By: wurtel

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 (the #!-line, which must be the first line of the script file).

On the other hand, if you use an interpreter explicitly, then the interpreter doesn’t care what extension you gave 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, the .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

It’s always a Bash script.

[sreeraj@server ~]$ ./ext.py
Hi. I am a Bash script
Answered By: Sreeraj
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.