0

I have a below shell script which will get the latest folder from my current directory in machineB and machineC. So I came up with the below command which will find me the latest folder inside -

/bat/data/snapshot

And that latest folder will be in the form of YYYYMMDD. Below is my shell script -

#!/bin/bash

readonly FILERS_LOCATION=(machineB machineC)
readonly MAPPED_LOCATION=/bat/data/snapshot

dir1=$(ssh -o "StrictHostKeyChecking no" david@${FILERS_LOCATION[0]} ls -dt1 "$MAPPED_LOCATION"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | head -n1)
dir2=$(ssh -o "StrictHostKeyChecking no" david@${FILERS_LOCATION[1]} ls -dt1 "$MAPPED_LOCATION"/[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9] | head -n1)

echo $dir1
echo $dir2

length1=$(ssh -o "StrictHostKeyChecking no" david@${FILERS_LOCATION[0]} "ls '$dir1' | wc -l")
length2=$(ssh -o "StrictHostKeyChecking no" david@${FILERS_LOCATION[1]} "ls '$dir2' | wc -l")

echo $length1
echo $length2

if [ $dir1 eq $dir2 ] && [length1 > 0] && [length2 > 0]
then
    echo "Hello World"

Now I need to write conditional if statement. I need to check whether dir1 is equal to dir2 and length1 is greater than 0 and length2 is also greater than 0 then only print outs Hello World

But somehow my above if statement doesn't work. Any idea what wrong I am doing here? I am little bit rusty in bash scripting..

1 Answer 1

5

It should be

if [ "$dir1" = "$dir2" ] && [ "$length1" -gt 0 ] && [ "$length2" -gt 0 ]

Remember, variable names must be preceded by $s. String equality comparisons must be done using =, and numeric comparisons should be done using named arithmetic operators like -gt. See help test.

Note that (as a rule) the -o and -a test operators should be avoided as [ cannot parse its arguments reliably when they are involved and operands look like operators. Use the && and || shell operators instead.

1
  • 2
    If you have bash, there's no real reason to use [. As you have just demonstrated, the syntax is absolutely horrid. Use [[ instead, it has far nicer syntax.
    – Chris Down
    Commented Dec 24, 2013 at 8:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .