Detect if user's path has a specific directory in it

前端 未结 8 2271
天命终不由人
天命终不由人 2020-11-28 07:13

With /bin/bash, how would I detect if a user has a specific directory in their $PATH variable?

For example

if [ -p \"$HOME/bin\" ]; then         


        
8条回答
  •  被撕碎了的回忆
    2020-11-28 07:55

    Something really simple and naive:

    echo "$PATH"|grep -q whatever && echo "found it"
    

    Where whatever is what you are searching for. Instead of && you can put $? into a variable or use a proper if statement.

    Limitations include:

    • The above will match substrings of larger paths (try matching on "bin" and it will probably find it, despite the fact that "bin" isn't in your path, /bin and /usr/bin are)
    • The above won't automatically expand shortcuts like ~

    Or using a perl one-liner:

    perl -e 'exit(!(grep(m{^/usr/bin$},split(":", $ENV{PATH}))) > 0)' && echo "found it"
    

    That still has the limitation that it won't do any shell expansions, but it doesn't fail if a substring matches. (The above matches "/usr/bin", in case that wasn't clear).

提交回复
热议问题