Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if PATH has a specific directory entry in it

Tags:

bash

shell

path

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   echo "Your path is missing ~/bin, you might want to add it." else   echo "Your path is correctly set" fi 
like image 319
epochwolf Avatar asked Sep 08 '09 20:09

epochwolf


People also ask

How do you check for directories that are in that path?

How can you tell in which directory you're currently working? The answer is the pwd command, which stands for print working directory. The word print in print working directory means “print to the screen,” not “send to printer.” The pwd command displays the full, absolute path of the current, or working, directory.

What is echo in path?

You can use echo $PATH to find which directories your shell is set to check for executable files. To do so: Type echo $PATH at the command prompt and press ↵ Enter . This output is a list of directories where executable files are stored.

How do I get the current directory in bash?

By default, bash shows just your current directory, not the entire path. To determine the exact location of your current directory within the file system, go to a shell prompt and type the command pwd. This tells you that you are in the user sam's directory, which is in the /home directory.


1 Answers

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.

like image 173
Gordon Davisson Avatar answered Sep 24 '22 23:09

Gordon Davisson