[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash: testing a variable



On 7/9/2021 9:54 PM, Charles Curley wrote:
I'd like to check two things:

* Whether a given path is not already in the $PATH variable

* Whether the given path already exists

If both are true, I'd like to add the given path to the $PATH variable.

I can add the given path, and test for the existence of the given path.
I can write expressions that work to detect the given path in $PATH.
What I don't seem able to do is combine all that in a script.

Here's what I have for the script:

#!/bin/bash

# A short script for testing some code.

# pelican seems to like local installations here.
SUBSTR="${HOME}"/\.local/bin/
echo Substr is "${SUBSTR}"
# if [[ ! ${PATH} =~ .*/home/charles/.local/bin.* ]] ; then

[[ $PATH =~ \/home\/charles\/... ]] && echo match || echo nomatch

That is, escaping the backslash.

if [[ $( echo "$PATH" | grep -E -v "${SUBSTR}" ) ]] ; then

Try the -q opt to grep or redirecting the output to the null device:

'if $(echo $PATH | grep -v $SUBSTR 2>&1); then'

I call the script with the . operator: ". test.sh"


Personally, I would invoke the script as './try.sh' and use sourcing
('source, '.') to include libraries...
I would also not use 'test' as a name for a script (could be confused
with the test command).

Why do I always end up adding the given path, even if it is already in
$PATH?


Because if there is a match, grep will print the value of the match (in
this case the content of $PATH).
So the condition will always be 0.

--
John Doe


Reply to: