Linux which shell is running

How to determine the current interactive shell that I’m in (command-line)

How can I determine the current shell I am working on? Would the output of the ps command alone be sufficient? How can this be done in different flavors of Unix?

Testing for particular capabilities (e.g. does it do ! substitution?) is probably more portable than finding the name of the shell. Local custom might have you running something named /bin/sh which could actually be ash, dash, bash, etc.

It appears that there is no simple answer to this question. If we can’t query the shell, maybe the better approach is to always specify the shell. I’m not sure that this is always possible, but maybe it is more easily accomplished than people generally assume.

@Aniket, not so much help as you might think — that’s only interested in interactive shell processes.

29 Answers 29

  • There are three approaches to finding the name of the current shell’s executable: Please note that all three approaches can be fooled if the executable of the shell is /bin/sh , but it’s really a renamed bash , for example (which frequently happens). Thus your second question of whether ps output will do is answered with «not always«.
    1. echo $0 — will print the program name. which in the case of the shell is the actual shell.
    2. ps -ef | grep $$ | grep -v grep — this will look for the current process ID in the list of running processes. Since the current process is the shell, it will be included. This is not 100% reliable, as you might have other processes whose ps listing includes the same number as shell’s process ID, especially if that ID is a small number (for example, if the shell’s PID is «5», you may find processes called «java5» or «perl5» in the same grep output!). This is the second problem with the «ps» approach, on top of not being able to rely on the shell name.
    3. echo $SHELL — The path to the current shell is stored as the SHELL variable for any shell. The caveat for this one is that if you launch a shell explicitly as a subprocess (for example, it’s not your login shell), you will get your login shell’s value instead. If that’s a possibility, use the ps or $0 approach.
  • If, however, the executable doesn’t match your actual shell (e.g. /bin/sh is actually bash or ksh), you need heuristics. Here are some environmental variables specific to various shells:
    • $version is set on tcsh
    • $BASH is set on bash
    • $shell (lowercase) is set to actual shell name in csh or tcsh
    • $ZSH_NAME is set on zsh
    • ksh has $PS3 and $PS4 set, whereas the normal Bourne shell ( sh ) only has $PS1 and $PS2 set. This generally seems like the hardest to distinguish — the only difference in the entire set of environment variables between sh and ksh we have installed on Solaris boxen is $ERRNO , $FCEDIT , $LINENO , $PPID , $PS3 , $PS4 , $RANDOM , $SECONDS , and $TMOUT .

    @Dennish — my ksh right now doesn’t have KSH_VERSION set. and echo $ <.sh.version>returns «Bad Substitution». See my solution above

    “ ps -ef | grep … … This is not 100% reliable as …” Using a simple regular expression via egrep or grep -e can easily bring the reliability up to for-all-intents-and-purposes 100%: ps -ef | egrep «^\s*\d+\s+$$\s+» . The ^ makes sure we’re starting from the beginning of the line, the \d+ eats up the UID, the $$ matches the PID, and the \s* and \s+ account for & ensure whitespace between the other parts.

    should work anywhere that the solutions involving ps -ef and grep do (on any Unix variant which supports POSIX options for ps ) and will not suffer from the false positives introduced by grepping for a sequence of digits which may appear elsewhere.

    Some shells have their own builtin version of ps which may not understand -p so you may need to use /bin/ps -p $$ .

    All the shells I’m familiar with understand $$ except for fish with which you would have to use ps -p %self .

    Actually, you shouldn’t rely on a hard paths such as /bin/ps . ps could easily (actually it is quite normal nowadays) be installed in /usr/bin . $(which ps) -p $$ is a better way. Of course, this will not work in fish, and possibly some other shells. I think it is (which ps) -p %self in fish.

    In some minimal systems like a debian-slim docker container, ps might not be there. In that case this approachs still works: readlink /proc/$$/exe

    Thanks. I found this the best option to use in a script to guard bash specific commands test `ps -p $$ -ocomm=` == «bash» && do_something_that_only_works_in_bash . (The next line in my script has the equivalent for csh.)

    I’ve found that if you do this from within a subshell then it can lead to spurious extra lines by matching the parent’s PID as well as the actual shell process. For this, I use -q instead of -p : SHELL=$(ps -ocomm= -q $$)

    If you just want to ensure the user is invoking a script with Bash:

    if [ -z "$BASH" ]; then echo "Please run this script $0 with bash"; exit; fi 
    if [ -z "$BASH" ]; then exec bash $0 ; exit; fi 

    It shouldn’t be closer to top, because it doesn’t answer the question at all. If the question would be «How to check if script is running under bash», I vote for it.

    @DawidFerenczy — This question is the top result when you search for that phrase though. In the long run, I think it’s much more important that answers answer what people are looking for rather than answer what the original question was about.

    This is very useful, thank you. Just adapted it a bit, putting this as the second line after #!/bin/bash : if [ ! -n «$BASH» ] ;then exec bash $0; fi . With this line the script is run using bash even if started using ksh or sh. My use case doesn’t need command line arguments, but they could be added after $0 if necessary.

    $SHELL environment variable contains a shell, which is configured as default for a current user. It doesn’t reflect a shell, which is currently running. Also it’s better to use ps -p $$ than grepping $$ because of false positives.

    The $SHELL env. variable points to the ‘parent’ shell, as specified in the POSIX spec: SHELL This variable shall represent a pathname of the user’s preferred command language interpreter. Therefore the value of $SHELL may not be the current shell.

    $SHELL need not always show the current shell. It only reflects the default shell to be invoked.

    To test the above, say bash is the default shell, try echo $SHELL , and then in the same terminal, get into some other shell (KornShell (ksh) for example) and try $SHELL . You will see the result as bash in both cases.

    To get the name of the current shell, Use cat /proc/$$/cmdline . And the path to the shell executable by readlink /proc/$$/exe .

    There are many ways to find out the shell and its corresponding version. Here are few which worked for me.

    Straightforward

    1. $>echo $0 (Gives you the program name. In my case the output was -bash.)
    2. $>$SHELL (This takes you into the shell and in the prompt you get the shell name and version. In my case bash3.2$.)
    3. $>echo $SHELL (This will give you executable path. In my case /bin/bash.)
    4. $>$SHELL —version (This will give complete info about the shell software with license type)

    Hackish approach

    $> ******* (Type a set of random characters and in the output you will get the shell name. In my case -bash: chapter2-a-sample-isomorphic-app: command not found)

    I have a simple trick to find the current shell. Just type a random string (which is not a command). It will fail and return a «not found» error, but at start of the line it will say which shell it is:

    ksh: aaaaa: not found [No such file or directory] bash: aaaaa: command not found 

    No good in a script. echo ‘aaaa’ > script; chmod +x script; ./script gives ./script.sh: 1: aaaa: not found

    ps is the most reliable method. The SHELL environment variable is not guaranteed to be set and even if it is, it can be easily spoofed.

    +1 $SHELL is the default shell for programs that need to spawn one. It doesn’t necessarily reflect the shell that’s currently running.

    I have tried many different approaches and the best one for me is:

    It also works under Cygwin and cannot produce false positives as PID grepping. With some cleaning, it outputs just an executable name (under Cygwin with path):

    You can create a function so you don’t have to memorize it:

    # Print currently active shell shell () < ps -p $$ | tail -1 | awk '' > 

    . and then just execute shell .

    It was tested under Debian and Cygwin.

    As of my setup (Cygwin | Windows 7) your answer is the best one, and ps -p $$ | tail -1 | gawk » works even from cmd without $bash. Please note gawk instead of awk, as awk works only from bash.

    @WebComer Sorry, I’m not sure what you mean by «works even from cmd without $bash«. Even if you would have Windows ports of ps , tail and gawk , cmd doesn’t define $$ as it’s PID so it definitely cannot work under the plain cmd.

    Why not simply ps -p$$ -o comm= ? POSIX says that specifying all headers empty suppresses the header completely. We’re still failing (like all the ps answers) when we’re sourced by a directly executed script (e.g. #!/bin/sh ).

    The following will always give the actual shell used — it gets the name of the actual executable and not the shell name (i.e. ksh93 instead of ksh , etc.). For /bin/sh , it will show the actual shell used, i.e. dash .

    I know that there are many who say the ls output should never be processed, but what is the probability you’ll have a shell you are using that is named with special characters or placed in a directory named with special characters? If this is still the case, there are plenty of other examples of doing it differently.

    As pointed out by Toby Speight, this would be a more proper and cleaner way of achieving the same:

    basename $(readlink /proc/$$/exe) 

    This will give the name of the actual executable, not the actual shell. When the actual shell is linked as a busybox applet, say ash -> /bin/busybox , this will give /bin/busybox.

    My variant on printing the parent process:

    Don’t run unnecessary applications when AWK can do it for you.

    Provided that your /bin/sh supports the POSIX standard and your system has the lsof command installed — a possible alternative to lsof could in this case be pid2path — you can also use (or adapt) the following script that prints full paths:

    #!/bin/sh # cat /usr/local/bin/cursh set -eu pid="$$" set -- sh bash zsh ksh ash dash csh tcsh pdksh mksh fish psh rc scsh bournesh wish Wish login unset echo env sed ps lsof awk getconf # getconf _POSIX_VERSION # reliable test for availability of POSIX system? PATH="`PATH=/usr/bin:/bin:/usr/sbin:/sbin getconf PATH`" [ $? -ne 0 ] && < echo "'getconf PATH' failed"; exit 1; >export PATH cmd="lsof" env -i PATH="$" type "$cmd" 1>/dev/null 2>&1 || < echo "$cmd not found"; exit 1; >awkstr="`echo "$@" | sed 's/\([^ ]\\)/|\/\1/g; s/ /$/g' | sed 's/^|//; s/$/$/'`" ppid="`env -i PATH="$" ps -p $pid -o ppid=`" [ "$"X = ""X ] && < echo "no ppid found"; exit 1; >lsofstr="`lsof -p $ppid`" || < printf "%s\n" "lsof failed" "try: sudo lsof -p \`ps -p \$\$ -o ppid=\`"; exit 1; >printf "%s\n" "$" | LC_ALL=C awk -v var="$" '$NF ~ var ' 

    this works in fish! but for me, fails in bash, because of the -i (-> ignore environment) option to env in the line where you check for lsof being available. it fails with: env -i PATH=»$» type lsof -> env: ‘type’: No such file or directory

    ps -o command | grep -v -e "\" -e grep -e tail | tail -1 

    This should be portable across different platforms and shells. It uses ps like other solutions, but it doesn’t rely on sed or awk and filters out junk from piping and ps itself so that the shell should always be the last entry. This way we don’t need to rely on non-portable PID variables or picking out the right lines and columns.

    I’ve tested on Debian and macOS with Bash, Z shell ( zsh ), and fish (which doesn’t work with most of these solutions without changing the expression specifically for fish, because it uses a different PID variable).

    Please try this helpful command.

    If you just want to check that you are running (a particular version of) Bash, the best way to do so is to use the $BASH_VERSINFO array variable. As a (read-only) array variable it cannot be set in the environment, so you can be sure it is coming (if at all) from the current shell.

    However, since Bash has a different behavior when invoked as sh , you do also need to check the $BASH environment variable ends with /bash .

    In a script I wrote that uses function names with — (not underscore), and depends on associative arrays (added in Bash 4), I have the following sanity check (with helpful user error message):

    case `eval 'echo $BASH@$' 2>/dev/null` in */bash@[456789]) # Claims bash version 4+, check for func-names and associative arrays if ! eval "declare -A _ARRAY && func-name() < :; >" 2>/dev/null; then echo >&2 "bash $BASH_VERSION is not supported (not really bash?)" exit 1 fi ;; */bash@[123]) echo >&2 "bash $BASH_VERSION is not supported (version 4+ required)" exit 1 ;; *) echo >&2 "This script requires BASH (version 4+) - not regular sh" echo >&2 "Re-run as \"bash $CMD\" for proper operation" exit 1 ;; esac 

    You could omit the somewhat paranoid functional check for features in the first case, and just assume that future Bash versions would be compatible.

    Источник

    Читайте также:  Vipnet linux фильтр открытой сети
Оцените статью
Adblock
detector