0

I'm trying to write as simple a bash script as possible to append one argument to the $PATH environment variable if argument isn't already part of the $PATH. I know there are other simple ways to do it by not using a bash script; however, I want to use a bash script. I've experimented with export but I haven't had any luck. Right now my simple code looks like this:

#!/bin/bash
if [[ "$(echo $PATH)" != *"$1"* ]]
then
PATH=$PATH:$1
fi

But:

$ ./script /home/scripts
$ echo $PATH
(returns unaltered PATH)

1 Answer 1

2

try with src or .:

src ./script /home/scripts . ./script /home/scripts

It's because your script runs on its own interpreter and this interpreter instance (which is where the variable $PATH is getting set) dies when the script dies. You have to ask your current interpreter to run the script instead (that's what src or . are used for)

Sign up to request clarification or add additional context in comments.

4 Comments

I was looking at the if logic and completely overlooked this. For what it's worth, this if logic is probably better: if [ -d "$1" ] && ! echo $PATH | grep -E -q "(^|:)$1($|:)"
In case someone reading that finds the regular expression hard to parse, it is specifically looking for the $1 that is passed in with a : before and after it, or at the very start or the very end of the $PATH variable. So, for instance, if /bin/too is already in the path, you can still add /bin to the path, which you can't do if you don't require the delimeters.
Thanks Jonathon. That's a great point. Is there a way to do this task with actually calling the command and not sourcing it?
I use this: [[ -d "$HOME/.cargo/bin" && ":$PATH:" != *":$HOME/.cargo/bin:"* ]] && export PATH="$HOME/.cargo/bin:$PATH" (well, it's a prepend example, you can put the new location on the end to append) The logic is "if the directory exists, and it's not already in PATH, then add it to PATH." Makes re-source-ing the file safe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.