misguided
misguided

Reputation: 3789

multiple if condition in unix

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

Answers (3)

bonsaiviking
bonsaiviking

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:

  • You don't need to put a space before or after ;, because that is a special separator that the shell recognizes.
  • You should always "double quote" $variables because they get expanded before the shell does the lexing. This means that if an unquoted variable contains a space, the shell will see the value as separate tokens, instead of one string.

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

Carl Norum
Carl Norum

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

suspectus
suspectus

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

Related Questions