I have the following bash script
i=1
while SH= read -r LINE
do
if echo $LINE | grep 'Network connection down!'
then
echo "shutdown"
exit
elif echo $LINE | grep 'Network connection available'
then
echo $LINE
((i++))
fi
done < <(tac /var/log/messages)
This script works so far. I am not an expert at shell scripting. I am trying to add an and operator to the first conditional statement, something like this
if echo $LINE | grep 'Network connection down!' && $i<4
Can anyone help show me how to make this work in shell script, every variation I have tried so far ends with various errors like
conditional binary operator expected
and various other ones that I can describe. Many thanks to everyone in advance :)
Shell programming requires a special command to perform comparisons, as the if
statement itself does not work with expressions, only commands. In bash
, the command to use is the conditional command, [[ ... ]]
.
if echo "$line" | grep 'Network connection down!' && [[ $i -lt 4 ]]; then
You can use an arithmetic command (( ... ))
as well, which allows a more familiar looking expression:
if echo "$line" | grep 'Network connection down!' && (( i < 4 )); then
You can also replace your call to grep
with the =~
operator:
if [[ $line =~ Network\ connection\ down! && $i -lt 4 ]]; then
( or [[ $line =~ Network \connection \down! ]] && (( i < 4))
, but you probably get the point).