如何检查目录是否在 Bash 的路径上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9660608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:45:51  来源:igfitidea点击:

How can I check if a directory is on the path in Bash?

bash

提问by Kevin Burke

Possible Duplicate:
Bash: Detect if user's path has a specific directory in it

可能的重复:
Bash:检测用户路径中是否包含特定目录

Given a directory, how can I determine whether it's on the unix PATH? Looking for a shell script.

给定一个目录,如何确定它是否在 unix PATH 上?寻找一个shell脚本。

Thanks, Kevin

谢谢,凯文

回答by ruakh

You can write:

你可以写:

if [[ :$PATH: == *:"$directory_you_want_to_check":* ]] ; then
    # O.K., the directory is on the path
else
    # oops, the directory is not on the path
fi

Note that this won't follow symbolic links, or anything like that; it's just a string comparison, checking if colon-$PATH-colon contains colon-directory-colon.

请注意,这不会遵循符号链接或类似的东西;这只是一个字符串比较,检查冒号-$PATH-冒号是否包含冒号-目录-冒号。

回答by tripleee

I usually prefer case-- posting this in order to make the set complete (-:

我通常更喜欢case- 发布此内容以使设置完整(-:

case :$PATH: in
  *:/home/you/bin:*)  ;;  # do nothing
  *) PATH=/home/you/bin:$PATH ;;
esac

Notice the leading and trailing colons on the case expression in order to simplify the pattern. With case $PATHyou would have to compare to four different patterns, depending on whether the beginning and end of the match was at the beginning or end of the variable.

请注意 case 表达式上的前导和尾随冒号,以简化模式。随着case $PATH你将不得不比较四种不同的模式,这取决于比赛的开始和结束是否是在变量的开头或结尾。

回答by paxdiablo

Quick and dirty: you can echo the (slightly modified) path through grepand check the return value:

快速而肮脏:您可以通过回显(稍微修改)路径grep并检查返回值:

pax> echo ":$PATH:" | grep :/usr/sbin:
:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:

pax> echo $?
0

pax> echo ":$PATH:" | grep :/usr/xbin:

pax> echo $?
1

By putting :at either end of both the path and the directory you're looking for, you simply the grepexpression and ensure only complete paths are found. Otherwise, looking for /usr/binmay turn up /usr/bin/xyzzyfor example.

通过放置:在路径和您要查找的目录的任一端,您只需简单地grep表达并确保只找到完整的路径。否则,例如,寻找/usr/bin可能会出现/usr/bin/xyzzy

回答by Jasonw

I will probably have something like that, that is to echo the existing $PATH and grep for the pattern.

我可能会有类似的东西,即回显现有的 $PATH 和 grep 模式。

#!/bin/sh

if [ $# -ne 1 ]; then
 echo "
#!/bin/bash

DIR="/usr/xbin"
[ `echo ":$PATH:" | grep :$DIR:` ] && echo true || echo false
<dir>" exit 1 fi dir=${1%/}; if [ `echo :$PATH: | grep -F :$dir:` ]; then echo "$dir is in the UNIX path" else echo "$dir is not in the UNIX path" fi

回答by Umae

Maybe it can helps:

也许它可以帮助:

##代码##