问题
I am using bash scripting to check whether two specific directories are containing some specific number of files. lets assume 20. Is it possible to check it in a line inside a if statement?
#!/bin/bash
if [ [ls /path/to/dir1 | wc -l ] != 20 || [ ls /path/to/dir2 | wc -l ] != 50 ]; then
echo "do this!"
elif
echo "do that!"
fi
回答1:
The syntax is incorrect:
if [[ $(ls /path/to/dir1 | wc -l) != 20 || $(ls /path/to/dir2 | wc -l) != 50 ]]
then
echo "do this!"
else
echo "do that!"
fi
(I move the position of the then for readability)
With two square brackets [[ you can use || for "or" instead of -o, which is closer to conventional languages. Strictly speaking the [[ does pattern matching, so although the code above will work, an arithmetic test should really use ((:
if (( $(ls /path/to/dir1 | wc -l) != 20 || $(ls /path/to/dir2 | wc -l) != 50 ))
then
echo "do this!"
else
echo "do that!"
fi
The $( ) runs a subshell and captures the output.
回答2:
Correct if syntax:
if [ $(ls /path/to/dir1 | wc -l) -ne 20 -o $(ls /path/to/dir2 | wc -l) -ne 50 ]
But in your example you shouldn't use just elif. Use either else, or specify condition for elif, exmpl:
if [ $(ls /path/to/dir1 | wc -l) -ne 20 -o $(ls /path/to/dir2 | wc -l) -ne 50 ]
then
echo "Do smth"
elif [ $(ls /path/to/dir3 | wc -l) -ne 100 ]
then
echo "Do anything else"
fi
来源:https://stackoverflow.com/questions/47928305/execute-command-and-compare-it-in-a-if-statement