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

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

    Using grep is overkill, and can cause trouble if you're searching for anything that happens to include RE metacharacters. This problem can be solved perfectly well with bash's builtin [[ command:

    if [[ ":$PATH:" == *":$HOME/bin:"* ]]; then
      echo "Your path is correctly set"
    else
      echo "Your path is missing ~/bin, you might want to add it."
    fi
    

    Note that adding colons before both the expansion of $PATH and the path to search for solves the substring match issue; double-quoting the path avoids trouble with metacharacters.

提交回复
热议问题