2

I am wanting to check that a certain directories always appear after other directories in an environment variable.

List items are separated by a colon, as with the PATH variable.

This is not simply for bash, but for a few different shells.

The problem is, I'm not sure how to check the order of items in a list using standard unix utilities.

What would be a starting point?

edit:

An example would be

$LIST=/test:/bin/test:/etc/test:/nan/:/var

I would want to test for example that any directory path that had the word test in it was prior in the list to a directory that did not.

What I want to do is small enough that I can hardcode the directories, so a dynamic solution is not necessary.

4
  • take look at man hier Oct 11, 2013 at 10:07
  • @RahulPatil I don't see what man hier has to do with this.
    – Chris Down
    Oct 11, 2013 at 10:09
  • question is still not clear for me, I just suggest him man. @Sonny Ordell , could you please input example, this help us understand your issue. Oct 11, 2013 at 10:11
  • @Rahul, I am adding an example to my question. Oct 11, 2013 at 10:15

1 Answer 1

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

For your specific example:

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"
2
  • With your Awk example, would it be possible to pass it input form stdin instead of taking from the environment? Oct 11, 2013 at 10:55
  • 1
    @SonnyOrdell Use getline to get a line from stdin. Like getline a; getline b and replace ARGV[1] with a and ARGV[2] with b. Oct 11, 2013 at 12:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .