Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 从路径中删除底部标高_Bash - Fatal编程技术网

Bash 从路径中删除底部标高

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 但是我必须跟踪我开始使用的目

我正在编写一个脚本,我想检查相对于脚本工作目录的文件夹是否在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
但是我必须跟踪我开始使用的目录,这样我才能
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,在BSD
xargs
中不存在(如在Mac OS X中)。
which ls
/bin/ls