执行命令并在 if 语句中进行比较 [英] Execute command and compare it in a if statement
问题描述
我正在使用 bash 脚本来检查两个特定目录是否包含特定数量的文件.让我们假设 20.是否可以在 if 语句中的一行中检查它?
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
推荐答案
语法错误:
if [[ $(ls /path/to/dir1 | wc -l) != 20 || $(ls /path/to/dir2 | wc -l) != 50 ]]
then
echo "do this!"
else
echo "do that!"
fi
(为了便于阅读,我移动了 then
的位置)
(I move the position of the then
for readability)
使用两个方括号 [[
可以使用 ||
表示或"而不是 -o
,这更接近于传统语言.严格来说,[[
进行模式匹配,所以虽然上面的代码可以工作,但算术测试应该真正使用 ((
:
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
$()
运行一个子shell 并捕获输出.
The $( )
runs a subshell and captures the output.
这篇关于执行命令并在 if 语句中进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!