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

前端 未结 8 2274
天命终不由人
天命终不由人 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: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"(:|$) ]]
    

提交回复
热议问题