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

前端 未结 8 2259
天命终不由人
天命终不由人 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"
    

提交回复
热议问题