Execute command and compare it in a if statement

你说的曾经没有我的故事 提交于 2021-02-08 10:35:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!