I am running Ubuntu 22 ( "22.04.4 LTS (Jammy Jellyfish)")
I understand that in any linux shell script the symbol $$ denotes the pid of the process running that script
I have a shell script that needs to ensure it runs under bourne so it determines which shell it is being run under.That determination of shell is needed because script has lot of non portable bourne shell specific code.
So in order to ensure that this script runs under bourne, in addition to a shebang I decided to add some more saftey check to determine which shell is running the script. That is because some users tend to specify a shell explicitly thus overriding shebang
Review following code snippet from my shell script that makes a determination of the shell under which script is being run. This uses $$ and finds the name of process that has PID=$$ ; this runs fine if there is NO shebang at begining of script
runshell=`ps -p $$ |grep -v PID| awk '{print $4}'`
if [ $runshell != "sh" ]
then
echo " shell is $runshell"; exit 99;
echo "You must run this in bourne shell. Exiting"
exit 99;
fi
echo "Running in bourne shell. "
# rest of code that needs to run in bourne shell
As far as there is no shebang, above script runs perfectly fine ( the variable "runshell" has the value of shell that runs the script) .
However if I introduce shebang as follows, then the name of process having pid $$ turns out to be the script name typed at command line . So in the below snippet the vaiable 'runshell' gets value = .
#!/bin/sh
runshell=`ps -p $$ |grep -v PID| awk '{print $4}'`
if [ $runshell != "sh" ]
then
echo " shell is $runshell"; exit 99;
echo "You must run this in bourne shell. Exiting ";
exit 99;
fi
# rest of code that needs to run in bourne shell
when I run this script as "./script.sh " then the described problem happens
However if I run it specifying a shell as "sh script.sh" then it detects the shell correctly
so questions
- Why should a shebang influence value of $$ (and hence the name of proces with PID $$) ?
- And if I need to retain the shebang how do I make determination of shell under which the script is running ?
Thanks for your help