Rules with using double parentheses in Bash

Hi.could you explain me what are the rules when we are using double parentesis in if statement,if I put [ $# > 0 ],the code is working ,with (( is not

 
#!/bin/bash
if (($# > 0))
then
 if ((! -d "$1"))  
then
 echo "Directory $1 not found"
fi
else
 echo Problem
fi
 
 
 

This is probably what you're looking for:

Test Constructs

That doesn't do what you think it does. (I made the same mistake when I first started shell scripting.)

The greater-than symbol, >, is a redirection operator, not a comparison operator (unless it is escaped, in which case it is string comparison, not numerical). What you need is:

[ $# -gt 0 ]

(I never use the non-standard (( ... )) syntax.)

1 Like

Some ideas:

#!/bin/bash
# scriptname : A script to do something with a directory
#
# Parameter validation
if [ ! $# -eq 1 ]
then
       echo "Usage: scriptname directory"
       exit 1
fi
# Save supplied parameter
mydir="$1"
# Does the directory exist?
if [ ! -d "${mydir}" ]
then
        echo "Directory $1 not found"
        exit 1
fi
# Processing continues here
if [ $# -ne 1 ]
mydir=$1
if [ ! -d "$mydir" ]

@cfajohnson
I only agree with the simplification of the "not" condition in the first command you post. The rest is pedantic and naive and reduces the resiliance of the script to duff parameters and similar environment variable names.

If I thought that there were lots of parameters I would have posted:

mydir="${1}"

When you get into 5,000 line Shell scripts you take all precautions.

If you write your scripts correctly, you don't need that "protection".

That is the same as:

mydir=$1

The braces and quotes are unnecessary in any circumstances.

If you don't know what is required and what is not, how do you know what difference extra "precautions" will make?

@cfajohnson
Please tell me how you would deal with the 10th 11th and 12th parameter to the Shell script?
Is $1 unambiguous in every context in a Shell script? This is a rhetorical question because I know that you know the answer.
${1} is totally unambiguous.
Whether or not it it is strictly necessary in the context of that particular statement.

Btw. this sort of interchange between professionals is fun and I enjoy it.

The specification does not matter. If you write paranoid scripts which assume that the parameters and data may not conform to specification they will be much more robust when the bad data comes.

In the standard manner:

p10=${10}
p11=${11}
p12=${11}

Yes.

As is:

var=$1

...which is not unnecessarily verbose.