Search code examples
bashif-statementsedconditional-statements

Bash conditional validating the contents of two file lines


I'm attempting to verify that a particular file (SQL output from ij) has particular values on two given lines before proceeding.

My intention is to ensure that line 5 contains ----------- and line 6 contains 1

At the moment I am attempting:

if sed -n '5p' $SQLFILE == "-----------" && sed -n '6p' $SQLFILE == "1";
then
print "Success\n\n"
else
printf "Failure\n\n"
exit 200
fi

The above fails with "syntax error near -n"

Update:

Running with changes suggested (with -x set)

++ sed -n 5p ./testsql.txt
+ '[' ----------- == ----------- ']'
++ sed -n 6p ./testsql.txt
+ '[' '1          ' == 1 ']'
+ printf 'Initial Datasource Not Found, Or Error Running SQL Script. Exiting\n\n'

For reference:

[rvp@linuxtest UtilitiesTests]# sed -n '5p' $SQLFILE
-----------
[rvp@linuxtest UtilitiesTests]# sed -n '6p' $SQLFILE
1

Solution

  • You have to use $(...) to get the output of the sed commands. Then use test or [ to perform the equality test in if.

    Use -eq to perform numeric comparison instead of string comparison. This will ignore the extra spaces on line 6.

    if [ "$(sed -n '5p' "$SQLFILE")" = "-----------" ] && [ "$(sed -n '6p' "$SQLFILE")" -eq "1" ]
    

    You should also remember to quote variables and command substitutions. And the portable equality operator is =, == is a bash extension.