Foobar-naut
Foobar-naut

Reputation: 111

Execute command and compare it in a if statement

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

Upvotes: 0

Views: 2952

Answers (2)

cdarke
cdarke

Reputation: 44364

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.

Upvotes: 2

sahaquiel
sahaquiel

Reputation: 1838

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

Upvotes: 2

Related Questions