If each line in the file is a complete command - no continuations over multiple lines - then you can use read
:
while read cmd
do
if [ -z "$cmd" ]
then : Empty
elif $cmd
then : OK
else : Oops
fi
done < cmds.txt
Or, if you prefer linear construction and don't need anything from the sub-shell that the while loop represents in what follows, you can use:
cat cmds.txt |
while read cmd
do
if [ -z "$cmd" ]
then : Empty
elif $cmd
then : OK
else : Oops
fi
done
Note the careful use of quotes around the tested string. I still prefer to use an explicit '-z
' operator; there are those who argue it is not 100% necessary. I still use single square brackets rather than double - mainly out of habit built up over 20+ years. Those who learned shell using bash
or ksh
often prefer the double square bracket operator instead.
Beware I/O redirections, of course.
Also, if you don't have anything to do in the various then and else clauses, you should simply feed cmds.txt to the shell:
sh cmds.txt
This is by far the most reliable way of dealing with multi-line commands.