检测默认交互 shell 不适用于 shell 脚本

detect default interactive shell doesn't work on shell script

我默认使用 zsh shell,我 运行 echo [=13=] 并在终端上得到 -zsh,但以下代码无法检测到默认交互 shell

#!/usr/bin/env bash

if [ -n "$ZSH_VERSION" ]; then
  echo "zsh"
elif [ -n "$BASH_VERSION" ]; then
  echo "bash"
else
  echo "others"
fi

检测结果总是bash,为什么?谢谢。

您的代码可用于检测 current shell。但是脚本 运行 在它们自己的 shell 中,独立于交互 shell。由于其 shebang,您的脚本文件总是 运行s 在 bash 中。没有 shebang,调用 shell 决定如何 运行 脚本(如果有的话)。

正在检测 parent shell

要检测调用脚本的 shell,请尝试

#!/usr/bin/env bash
ps -p $PPID -o comm=

当您 运行 交互式 zsh 并执行此文件时,您应该得到 zsh 作为输出。

正在检测默认值shell

你的问题的标题是关于检测默认交互 shell。为此,您无法检查任何进程,因为即使您的默认 shell 是 X,您也始终可以使用 Y。相反,请查看存储默认值的文件:

grep "^$USER:" /etc/passwd | cut -d: -f7

执行此操作的标准方法是使用 SHELL 环境变量:

echo "Your default shell is $SHELL"

这是在POSIX标准中定义的,section 8.3, "Other Environment Variables":

SHELL
This variable shall represent a pathname of the user's preferred command language interpreter. If this interpreter does not conform to the Shell Command Language in XCU Shell Command Language, utilities may behave differently from those described in POSIX.1-2017.