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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With