james
james

Reputation: 167

bash script if statement not displaying true

I am trying to get a quick script together to check a file system prior to running resize2fs.

#!/bin/bash
var2=$(dumpe2fs -h /dev/mapper/mylv | grep "Filesystem state:")
var1=test
echo $var1
echo $var2

if [ "$var2" = "Filesystem state: clean" ];
then
        echo "clean"
else
        echo "dirty"
fi

My results

Server1:~ # ./filesystest.sh
dumpe2fs 1.38 (30-Jun-2005)
test
Filesystem state: clean
dirty

It seems even though var2 is in fact "Filesystem state: clean" it still shows up false.

Upvotes: 3

Views: 188

Answers (3)

anubhava
anubhava

Reputation: 785146

Instead of this check:

if [ "$var2" = "Filesystem state: clean" ];

try this check:

if [[ "$var2" = *"Filesystem state: clean"* ]];

Upvotes: 0

konsolebox
konsolebox

Reputation: 75488

Seeing the varying output of dumpe2fs I think you should check it like this instead:

shopt -s extglob
if [[ $var2 == 'Filesystem state:'*([[:blank:]])'clean' ]]

Or with regex:

if [[ $var2 =~ 'Filesystem state:'[[:blank:]]*'clean' ]]

Also, you could apply the command directly with this:

if dumpe2fs -h /dev/mapper/mylv 2>&1 | grep -q "Filesystem state:[[:blank:]]*clean"
then

If you want to get the state of the filesystem, you can do this:

state=$(exec dumpe2fs -h /dev/mapper/mylv 2>&1 | sed -ne '/Filesystem state:/s/.*state:\s*//p')

Upvotes: 1

devnull
devnull

Reputation: 123508

You probably have extra characters (maybe spaces) in var2.

Instead of saying:

if [ "$var2" = "Filesystem state: clean" ];

say:

if [[ "$var2" =~ "Filesystem state: clean" ]];

EDIT: In fact, your entire script can be written as:

dumpe2fs -h /dev/mapper/mylv | grep -q "Filesystem state: clean" && echo "clean" || echo "dirty"

Upvotes: 2

Related Questions