Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash string has odd expansion in if statement

I am doing a simple substring check using vars in .bashrc. This check should prevent adding a new path entry to $PATH that already exists in $PATH. The lhs is fine but the rhs of the compare expands the $PATH to something like /\u\s\r/\l\o\c\a\l/\b\i\n: for example. (does that to the entire PATH variable). I have checked the variables and they are what you would expect (PATH exists and is normal) TCL_PATH="/home/user/tcltk/bin"

if [[ -z "${PATH}" ]]; then 
    echo "PATH is empty"; 
else
    #this is the case
    echo "PATH is NOT empty"
fi
#these are as expected
echo $PATH
echo $TCL_PATH
if [[ "${TCL_PATH}" == *"${PATH}"* ]]; then 
  echo "EXISTS"
else
  echo "NOT EXISTS
fi

Why is the expansion happening and how do I fix it? I have done this before without any issues. Here is the output (using set -x for debug):

++ set -x
++ TCL_PATH=/home/user/tcltk/bin
++ echo /home/user/tcltk/bin /home/user/tcltk/bin
++ [[ -z /home/user/tcltk/bin ]]
++ echo 'TCL_PATH is NOT empty' TCL_PATH is NOT empty
++ [[ -z /usr/local/bin:/usr/bin:/bin:/opt/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl ]]
++ echo 'PATH is NOT empty' PATH is NOT empty
++ echo /usr/local/bin:/usr/bin:/bin:/opt/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl /usr/local/bin:/usr/bin:/bin:/opt/bin:/c/Windows/System32:/c/Windows:/c/Windows/System32/Wbem:/c/Windows/System32/WindowsPowerShell/v1.0/:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl
++ [[ /home/user/tcltk/bin == *\/\u\s\r\/\l\o\c\a\l\/\b\i\n\:\/\u\s\r\/\b\i\n\:\/\b\i\n\:\/\o\p\t\/\b\i\n\:\/\c\/\W\i\n\d\o\w\s\/\S\y\s\t\e\m\3\2\:\/\c\/\W\i\n\d\o\w\s\:\/\c\/\W\i\n\d\o\w\s\/\S\y\s\t\e\m\3\2\/\W\b\e\m\:\/\c\/\W\i\n\d\o\w\s\/\S\y\s\t\e\m\3\2\/\W\i\n\d\o\w\s\P\o\w\e\r\S\h\e\l\l\/\v\1\.\0\/\:\/\u\s\r\/\b\i\n\/\s\i\t\e\_\p\e\r\l\:\/\u\s\r\/\b\i\n\/\v\e\n\d\o\r\_\p\e\r\l\:\/\u\s\r\/\b\i\n\/\c\o\r\e\_\p\e\r\l* ]]
++ echo 'NOT EXIST' NOT EXIST
like image 858
user1741276 Avatar asked Oct 16 '25 16:10

user1741276


1 Answers

The test as written checks whether $PATH is included in $TCL_PATH, but it's the other way round.

if [[ $PATH = *"$TCL_PATH"* ]]; then 
    echo EXISTS
else
    echo NOT EXISTS
fi

Note that the test can give useless answers sometimes, e.g. when

TCL_PATH=/home/user/tcltk/bin
PATH=/home/user/tcltk/bin/subdir

You could improve the test by something like

if [[ :$PATH: = *:"$TCL_PATH":* ]]; then 
    ...
like image 75
choroba Avatar answered Oct 18 '25 07:10

choroba