Reputation: 23
I'd like to run a shell script that prints the name of the shell running it.
So far I've been using echo $SHELL
but that variable may not be set and does not give the name of the current shell running the script.
I've tried with ps -p $$
but this only works when using it directly in the terminal as in the script it gives me the name of the script file.
I have not found a good solution to this problem.
Current script:
#!/bin/bash
echo $SHELL
Thanks
EDIT: Just in case, I mean that I want to get the name of the command interpreter running the script by using a script.
Upvotes: 2
Views: 501
Reputation: 69198
You can use
stat -tc '%N' /proc/$$/exe | cut -d' ' -f3
to get the name of the shell running the script
Upvotes: 1
Reputation: 4841
After some tests, this seems to work on linux:
gawk 'BEGIN{RS="\0"}; NR==1{print; exit}' /proc/$$/cmdline
Requires a non-portable gawk feature.
Edit: An account of what happens here
The file /proc/PID/cmdline contains the complete command line from PID. $$
expands to the current shell's PID. This file contains a NULL-byte seperated list of the complete command line. gawk
is instructed to split the records ("lines") on the NULL-byte, and print the first one it encounters.
This would be a slightly shorter one:
gawk 'BEGIN{RS="\0"}; {print; exit}' /proc/$$/cmdline
Upvotes: 0
Reputation: 134
Does something along these lines do what you want?
me@server2:~$ cat test
#!/bin/sh
X=$(ps h -p $$ -o args='' | cut -f1 -d' ')
echo "Running --> $X"
me@server2:~$ ./test
Running --> /bin/sh
me@server2:~$ sh test
Running --> sh
me@server2:~$ bash test
Running --> bash
me@server2:~$
Upvotes: 2