I'm just wondering about test Linux command.
Is there an output from test -f FILE that I could grab using a variable?
How do I know whether this test perform successfully or not?
I'm just wondering about test Linux command.
Is there an output from test -f FILE that I could grab using a variable?
How do I know whether this test perform successfully or not?
The test command sets its exit code. You can examine the value in $? but usually you don't have to. Instead, you use a control flow construct such as while or if which does this behind the scenes for you.
while test -e "$myfile"; do
if grep -q 'fnord' "$myfile"; then
echo "Success! Play again."
dd if=/dev/urandom count=1 | base64 >"$myfile"
else
break
fi
done
Observe how while examines the exit code from test and if examines the exit code from grep. Each of these programs -- and generally any useful Unix utility -- is written so that it returns a zero exit code on success, otherwise a non-zero value.
test is perhaps somewhat odd in that that's all it does. Historically, it was a bit of a kitchen sink to avoid having to burden the shell's syntax with a lot of string and file property tests (which may in retrospect have been a slightly unhappy design decision -- this trips up beginners still today).
You also see a lot of beginners who have not picked up this idiom, and write pretzel code like
test -e "$myfile"
while [ $? -eq 0 ]; do
....
Yo dawg, I hear you like running test so I run test to test the output from the first test.