0

my script contain :

#### #!/usr/bin/sh
FILE="/home/steven/.bash_profile"
STRING="export PATH="$PATH:/opt/mssql-tools/bin""

if [ -z $(grep "$STRING" "$FILE") ]; then

        echo 'the string is exist' >&2
else

        echo 'the string doesnt exist' >&2
fi

and my file contain :

#### # .bash_profile

 # Get the aliases and functions

if [ -f ~/.bashrc ]; then

        . ~/.bashrc
fi

#### # User specific environment and startup programs

PATH=$PATH:$HOME/.local/bin:$HOME/bin

export PATH

why it always returns the is exist?

  • -z checks if the string is empty. Did you mean to use -n? Or just use grep directly: if grep -q "$STRING" "$FILE"; then ... – muru Jul 17 at 4:44
  • @muru i try grep directly but failed. – Steven Audy Jul 17 at 4:54
2

We should escape the $ and " in the STRING variable. Otherwise, it will expand the $PATH

Declare it as:

 STRING="export PATH=\"\$PATH:/opt/mssql-tools/bin\""

As commented by @muru, try as

if  grep -q "$STRING" "$FILE" ; then
         echo 'the string exists' ; 
else
         echo 'the string does not exist' ; 
fi

Since export is missing on line number 12 of file bashrc, it will always report that it doesn't exist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.