检查 shell 环境变量中项目的顺序

Son*_*ell 2 utilities coreutils environment-variables

我想检查某个目录是否总是出现在环境变量中的其他目录之后。

列表项由冒号分隔,与 PATH 变量一样。

这不仅适用于 bash,还适用于一些不同的 shell。

问题是,我不确定如何使用标准的 unix 实用程序检查列表中项目的顺序。

什么是起点?

编辑:

一个例子是

$LIST=/test:/bin/test:/etc/test:/nan/:/var
Run Code Online (Sandbox Code Playgroud)

例如,我想测试任何包含 test 一词的目录路径在列表中优先于没有的目录。

我想要做的足够小,我可以对目录进行硬编码,因此不需要动态解决方案。

Sté*_*las 7

POSIXly:

$ awk 'BEGIN{
  n = split(ENVIRON["PATH"], p, ":")
  while (n) i[p[n]]=n--
  if (! (ARGV[1] in i))
    print ARGV[1], "is not in $PATH"
  else if (! (ARGV[2] in i))
    print ARGV[2], "is not in $PATH"
  else if (i[ARGV[1]] < i[ARGV[2]])
    print ARGV[1], "is before", ARGV[2]
  else
    print ARGV[1], "is after", ARGV[2]
  exit}' /bin /usr/bin
/bin is after /usr/bin
Run Code Online (Sandbox Code Playgroud)

对于您的具体示例:

check_order() (
  test_seen=false non_test_seen=false
  IFS=:; set -f
  for i in $1; do
    case $i in
      (*test*)
        if $non_test_seen; then
          echo "there are some non-tests before some tests"
          return
        fi
        test_seen=true;;
      (*)
        non_test_seen=true
    esac
  done
  if $test_seen; then
    echo "tests are all first"
  else
    echo "no tests in there"
  fi
)
check_order "$LIST"
Run Code Online (Sandbox Code Playgroud)