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

前端 未结 8 2249
天命终不由人
天命终不由人 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 08:04

    $PATH is a list of strings separated by : that describe a list of directories. A directory is a list of strings separated by /. Two different strings may point to the same directory (like $HOME and ~, or /usr/local/bin and /usr/local/bin/). So we must fix the rules of what we want to compare/check. I suggest to compare/check the whole strings, and not physical directories, but remove duplicate and trailing /.

    First remove duplicate and trailing / from $PATH:

    echo $PATH | tr -s / | sed 's/\/:/:/g;s/:/\n/g'
    

    Now suppose $d contains the directory you want to check. Then pipe the previous command to check $d in $PATH.

    echo $PATH | tr -s / | sed 's/\/:/:/g;s/:/\n/g' | grep -q "^$d$" || echo "missing $d"
    
    0 讨论(0)
  • 2020-11-28 08:06

    Here's how to do it without grep:

    if [[ $PATH == ?(*:)$HOME/bin?(:*) ]]
    

    The key here is to make the colons and wildcards optional using the ?() construct. There shouldn't be any problem with metacharacters in this form, but if you want to include quotes this is where they go:

    if [[ "$PATH" == ?(*:)"$HOME/bin"?(:*) ]]
    

    This is another way to do it using the match operator (=~) so the syntax is more like grep's:

    if [[ "$PATH" =~ (^|:)"${HOME}/bin"(:|$) ]]
    
    0 讨论(0)
提交回复
热议问题