You use e2fsck
so I assume we're talking about ext?
filesystem. The command
tune2fs -l /dev/sdXX
will tell you the apparent state of the filesystem (which can be mounted, it's safe). You will get (among other things) either
Filesystem state: clean
or something else than clean
. Because grep
returns false if the match is not found, your basic try can be like this:
tune2fs -l /dev/sdXX | grep "^Filesystem state:[ ]*clean$" || { commands; to; fix; the; filesystem; }
The above will work only if the filesystem detected its unclean state beforehand. Sometimes you want to check for problems anyway (that's why the desired behavior is to fsck
every Nth mount or when such-and-such number of days have passed). If I get you right you're trying to get to know if you should e2fsck -y /dev/sdXX
, by analyzing the output of e2fsck -n /dev/sdXX
.
I say don't analyze the output. Check the exit status. See man 8 e2fsck
to learn:
The exit code returned by e2fsck
is the sum of the following conditions:
0
- No errors
1
- File system errors corrected
2
- File system errors corrected, system should
be rebooted
4
- File system errors left uncorrected
8
- Operational error
16
- Usage or syntax error
32
- e2fsck
canceled by user request
128
- Shared library error
Note e2fsck -n /dev/sdXX
will do nothing useful (and it will return "no errors") if the filesystem seems clear; so this is another way to detect the current apparent state, like we did with tune2fs
. To check anyway you need -f
option. Then you want to know if the exit status includes 4
. In bash
this can be done with:
e2fsck -nf /dev/sdXX # this is safe even if the filesystem is mounted
status=$?
[ $(( $status & 4 )) -eq 4 ] && { commands; to; fix; the; filesystem; }
Quick explanation:
$?
is the exit status of the last command (e2fsck
in this case). I save it to a separate variable so I can do multiple tests with it. It's not necessary in this simple example where there is one test only, but a good practice in general. The underlying reason is: after these lines $status
still contains exit status of e2fsck
and can be reused, while (the new) $?
has nothing to do with e2fsck
.
$(( ... ))
does shell arithmetic
- where
&
is bitwise AND,
- then
[ ... -eq 4 ]
is in fact the test
command to check if the result is 4
.
- If the test succeeds then the
{ ... }
block will be executed.
There may be errors not within the filesystem itself but on deeper level, on the device. I think this is out of scope of this question but just to point you in the right direction in case you need it, these are useful commands (notice sdX
, not sdXX
):
smartctl -t long /dev/sdX
badblocks -n -b 512 /dev/sdX
Read their man pages before you use them.