Reputation: 3789
I am trying to run the below logic
if [-f $file] && [$variable -lt 1] ; then
some logic
else
print "This is wrong"
fi
It fails with the following error
MyScipt.ksh[10]: [-f: not found
Where 10th line is the if condition , I have put in .
I have also tried
if [-f $file && $variable -lt 1] ; then
which gives the same error.
I know this is a syntax mistake somehwere , but I am not sure , what is the correct syntax when I am using multiple conditions with &&
in a if block
Upvotes: 1
Views: 2516
Reputation: 5995
The [
syntax is secretly a program!
$ type [
[ is a shell builtin
$ ls -l $(which [)
-rwxr-xr-x 1 root root 35264 Nov 19 16:25 /usr/bin/[
Because of the way the shell parses (technically "lexes") your command line, it sees this:
if
- keyword[-f
- the program [-f
$file]
- A string argument to the [-f
program, made by the value of $file
and ]
. If $file
was "asdf", then this would be asdf]
And so forth, down your command. What you need to do is include spaces, which the shell uses to separate the different parts (tokens) of your command:
if [ -f "$file" ]; then
Now [
stands on its own, and can be recognized as a command/program. Also, ]
stands on its own as an argument to [
, otherwise [
will complain. A couple more notes about this:
;
, because that is a special separator that the shell recognizes.Using &&
in an if-test like that isn't the usual way to do it. [
(also known as test
) understands -a
to mean "and," so this does what you intended:
if [ -f "$file" -a "$variable" -lt 1 ]; then
Upvotes: 2
Reputation: 224864
[
is not an operator, it's the name of a program (or a builtin, sometimes). Use type [
to check. Regardless, you need to put a space after it so that the command line parser knows what to do:
if [ -f $file ]
The &&
operator might not do what you want in this case, either. You should probably read the bash(1)
documentation. In this specific case, it seems like what you want is:
if [ -f $file -a $variable -lt 1 ]
Or in more modern bash syntax:
if [[ -f $file && $variable -lt 1 ]]
Upvotes: 3
Reputation: 17258
Use -a in an if
block to represent AND.
Note the space preceding the -f option.
if [ -f $file -a $variable -lt 1] ; then
some logic
else
print "This is wrong"
fi
Upvotes: 1