Is there a way to get a shell script to run under bash instead of sh?

I tried to find it, but could not find anything. I am sure the answer is simple.

I write shell scripts for various purposes that can be run by different people, and some of them can invoke a script using "sh" instead of "bash".

the script contains tools that do not work in a normal shell environment, and bash is required - is there a way to get the script to run under bash, even if it was called with "sh"

+6
source share
2 answers

As Richard Pennington says , the right way to do this is

#!/bin/bash 

as the first line of the script.

But this will not help if users invoke it with sh explicitly. For example, if I type

 sh your-script-name 

line #! will be ignored.

You cannot stop people from doing this, but you can dissuade him by adding something like this at the top of the script:

 #!/bin/bash if [ ! "$BASH_VERSION" ] ; then echo "Please do not use sh to run this script ($0), just execute it directly" 1>&2 exit 1 fi 

Or you could do something like:

 #!/bin/bash if [ ! "$BASH_VERSION" ] ; then exec /bin/bash "$0" " $@ " fi 

but this can be very wrong; for example, it is probably not guaranteed that $0 , which is usually the name of the script, is actually a name that you can use to call it. I can imagine that this happens in an endless loop if you are wrong, or your system is a little misconfigured.

I recommend the error reporting approach.

(Note: I just edited this answer, so the error message contains a script name that may be useful to users.)

+24
source
 #! /bin/bash # The rest of your script. 
+2
source

Source: https://habr.com/ru/post/949847/


All Articles