Bash 从路径中删除底部标高
我正在编写一个脚本,我想检查相对于脚本工作目录的文件夹是否在shell路径中 例如,如果项目结构为:Bash 从路径中删除底部标高,bash,Bash,我正在编写一个脚本,我想检查相对于脚本工作目录的文件夹是否在shell路径中 例如,如果项目结构为: top/ bin/ tests/ test1/ foo.sh test2/ foo.sh 我想从foo.sh中检查top/bin是否在PATH中。我知道以下方法会奏效: cd ../../bin if echo $PATH|grep `pwd`; then echo "Success" else echo "Failure" fi 但是我必须跟踪我开始使用的目
top/
bin/
tests/
test1/
foo.sh
test2/
foo.sh
我想从foo.sh
中检查top/bin
是否在PATH
中。我知道以下方法会奏效:
cd ../../bin
if echo $PATH|grep `pwd`; then
echo "Success"
else
echo "Failure"
fi
但是我必须跟踪我开始使用的目录,这样我才能cd
回到那里。我可以做一些类似的事情,比如在pwd
之后切掉最后两个目录,然后在其后面附加bin
?有没有其他聪明的方法来处理这个问题?
作为奖励,我想让这个脚本对测试中的额外目录级别保持健壮,但如果它使事情复杂化,这并不是严格必要的
# Exits with code 0 if the first argument is on the user's path.
is_on_path() {
CANONICAL_NAME=$(readlink -f "$1")
while read -r -d: COMPONENT; do
if [[ "$CANONICAL_NAME" = "$COMPONENT" ]]; then
return 0
fi
done <<< "$PATH"
return 1
}
奖励:从这里可以非常轻松地将其递归应用于所有父目录:
find_matching_ancestor() {
current_dir=$(pwd)
while [[ "$current_dir" != "/" ]]; do
if is_on_path "$current_dir/bin"; then
echo "$current_dir"
return 0
fi
current_dir=$(dirname "$current_dir")
done
return 1
}
这似乎有效
echo $PATH | xargs -d: -n1 | grep ^$(readlink -f ../../bin)$ | wc -l
也许最可靠的解决方案是将一个可执行位设置为该目录的文件,并使用“which”
例如,/bin是否在我的路径上
which ls
/bin/ls
您可以使用子字符串操作和全局绑定来实现这一点。一种避免需要回cd的简便技术就是在子shell中运行。例如,只需将您的命令包装在parens中:(cd.././bin| | |退出1;echo$PATH | tr:\\n | grep-q$(pwd))&echo Success | | echo Failure
@williampersell很棒的提示,我不知道!有点像在Elisp中保存游览。您的奖金解决方案使用while循环和dirname
正是我所需要的。请注意,-d
是a,在BSDxargs
中不存在(如在Mac OS X中)。
which ls
/bin/ls