本文介绍了HOWTO:检测从shell脚本的bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该方案是要求用户源的脚本文件:

The scenario is that users are asked to source a script file:

$ source envsetup.sh

该脚本文件可以使用bash唯一功能,因此我们有检测运行shell是bash或没有。

This script file may use bash only feature so we have detect the running shell is bash or not.

对于共享使用bash通用语法等贝壳,例如,SH,zsh的,KSH,我想报告一个警告。

For other shells that share common syntax with bash, for example, sh, zsh, ksh, I'd like to report a warning.

什么是检测跨Linux,Cygwin的,OS X?

What is the most reliable way to detect the current shell across Linux, Cygwin, OS X?

我所知道的是$ BASH,但我想知道它可能会失败的机会。

What I know is $BASH, but I am wondering the chances it could fail.

推荐答案

有一堆的环境变量,你可以看看,但其中许多人,如果不同的外壳是由庆典催生不会检测。考虑以下几点:

There are a bunch of environment variables that you can look at but many of them will not detect if a different shell is spawned from bash. Consider the following:

bash$ echo "SHELL: $SHELL, shell: $shell, ARGV[0]: $0, PS1: $PS1, prompt: $prompt"
SHELL: /bin/bash, shell: , ARGV[0]: -bash, PS1: bash$ , prompt:

bash$ csh
[lorien:~] daveshawley% echo "SHELL: $SHELL, shell: $shell, \$0: $0, PS1: $PS1, prompt: $prompt"
SHELL: /bin/bash, shell: /bin/tcsh, ARGV[0]: csh, PS1: bash$ , prompt: [%m:%c3] %n%#

[lorien:~] daveshawley% bash -r
bash$ echo "SHELL: $SHELL, shell: $shell, ARGV[0]: $0, PS1: $PS1, prompt: $prompt"
SHELL: /bin/bash, shell: , ARGV[0]: sh, PS1: bash$ , prompt:

bash$ zsh
% echo "SHELL: $SHELL, shell: $shell, ARGV[0]: $0, PS1: $PS1, prompt: $prompt"
SHELL: /bin/bash, shell: , ARGV[0]: zsh, PS1: % , prompt: %

% ksh
$ echo "SHELL: $SHELL, shell: $shell, ARGV[0]: $0, PS1: $PS1, prompt: $prompt"
SHELL: /bin/bash, shell: , ARGV[0]: ksh, PS1: bash$ , prompt:

有特定于除了它们具有由子壳被继承这是这里的环境事确实破裂的习惯的各种弹多个变量。几乎工作的唯一事情是 PS -o命令-p $$ 。这在技术上给你的shell运行的命令名。在大多数情况下,这将工作...因为应用程序启动用 EXEC 系统调用的某些变体,它允许命令的名称和可执行不同,它有可能为这个失败为好。试想一下:

There are a number of variables specific to the various shells except that they have a habit of being inherited by sub-shells which is where the environment thing really breaks. The only thing that almost works is ps -o command -p $$. This technically gives you the command name that the shell is running as. In most cases this will work... since applications are started with some variant of the exec system call and it allows for the name of the command and the executable to differ, it is possible for this to fail as well. Consider:

bash$ exec -a "-csh" bash
bash$ echo "$0, $SHELL, $BASH"
-csh, /bin/bash, /bin/bash
bash$ ps -o command -p $$
COMMAND
-csh
bash$

另一个技巧是使用 lsof的-p $$ | awk的'(NR == 2){$打印1} 。这可能是接近你可以得到,如果你足够幸运,有 lsof的派上用场了。

Another trick is to use lsof -p $$ | awk '(NR==2) {print $1}'. This is probably as close as you can get if you are lucky enough to have lsof handy.

这篇关于HOWTO:检测从shell脚本的bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:08