简体   繁体   中英

How to get the name of the shell running using a script?

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.

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:~$    

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

You can use

stat -tc '%N' /proc/$$/exe | cut -d' ' -f3

to get the name of the shell running the script

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM