Home > Software engineering >  Shell script to to check if a line exist in a file
Shell script to to check if a line exist in a file

Time:04-22

I have tried all the solutions available on stack overflow, but when I use if condition with with it always results true. I need to find a line in the file and see if it doesn't exit then insert the line in that file, but it always results that the line already exists. Here is my script

isInFile=$(grep -q '^export' /etc/bashrc)
if [[ $isInFile == 0 ]];
then
    echo "line is not present";
    echo "export PROMPT_COMMAND='RETRN_VAL=\$?;logger -p local6.debug \"\$(whoami) [\$\$]: \$(history 1 | sed \"s/^[ ]*[0-9]\ [ ]*//\" )\"'" >> /etc/bashrc;
    source /etc/bashrc;
else
    echo "line is in the file";
fi

It always says that

line is in the file

CodePudding user response:

The if statement branches based on the exit status of the command it's given. [[ is just one command you can use, it's not mandatory syntax. At an interactive prompt, enter help if

Do this:

if grep -q '^export' /etc/bashrc
then
    # exit status of grep is zero: the pattern DOES MATCH the file
    echo "line is in the file";
else
    # exit status of grep is non-zero: the pattern DOES NOT MATCH the file
    echo "line is not present";
    echo "export PROMPT_COMMAND='RETRN_VAL=\$?;logger -p local6.debug \"\$(whoami) [\$\$]: \$(history 1 | sed \"s/^[ ]*[0-9]\ [ ]*//\" )\"'" >> /etc/bashrc;
    source /etc/bashrc;
fi

CodePudding user response:

I see 2 issues in your code:

  1. if [[ $isInFile == 0 ]]; --If condition should not terminate with ;. Remove that.
  2. The expression you are checking is always an empty string. Try echo $isInFile. What you are checking is output of the command, not its return value. Instead, you should remove -q from your grep expression and check if the output is empty or not.

Following code should work:

isInFile=$(grep '^export' /etc/bashrc)
if [ -z "$isInFile" ]
then
    echo "line is not present";
    echo "export PROMPT_COMMAND='RETRN_VAL=\$?;logger -p local6.debug \"\$(whoami) [\$\$]: \$(history 1 | sed \"s/^[ ]*[0-9]\ [ ]*//\" )\"'" >> /etc/bashrc;
    source /etc/bashrc;
else
    echo "line is in the file";
fi

-z check for emptiness of variable.

  • Related