Aashik
Aashik

Reputation: 1

Can I use multiple AND (&&) operators for the conditions in BASH

if ssh server [ -d /path/to/dir1 && -d /path/to/dir2 && -d /path/to/dir3 && -d /path/to/dir1 ]

Please can anyone help me as i am new to bash.

Upvotes: 0

Views: 343

Answers (1)

Shane Bishop
Shane Bishop

Reputation: 4760

The [ ] is syntactic sugar for calling the POSIX test shell built-in. It does not allow && within it.

The [[ ]] is the bash extension, which does allow && to produce compound logical expressions.

So there is two ways to do what you want.

The POSIX way:

if [ -d /path/to/dir1 ] && [ -d /path/to/dir2 ] && [ -d /path/to/dir3 ] && [ -d /path/to/dir1 ]
then
    # Your code here
fi

Using the bash [[ ]] extension:

if [[ -d /path/to/dir1 && -d /path/to/dir2 && -d /path/to/dir3 && -d /path/to/dir1 ]]
then
    # Your code here
fi

In your case it looks like you are sshing to a server and then trying to see if all the conditions are true. In that case, in POSIX shell you can do

if ssh server sh -c '[ -d /path/to/dir1 ] && [ -d /path/to/dir2 ] && [ -d /path/to/dir3 ] && [ -d /path/to/dir1 ]'
then
    # Your code here
fi

(The sh -c is not strictly necessary if you know the user's login shell on the remote host is a POSIX shell.)

With the bash extension, you can do

if ssh server bash -c '[[ -d /path/to/dir1 && -d /path/to/dir2 && -d /path/to/dir3 && -d /path/to/dir1 ]]'
then
    # Your code here
fi

In both of the last two examples, the quoting is necessary.

Upvotes: 1

Related Questions