Search code examples
shellunixconditional-statementsls

Nested if in shell scripting


I want to write a script that take 1 command line argument( a directory) and then prompt for 2 number, it will then print out any file(each in a different line) that has the size between that 2 number, this is my script

echo -n "Enter the first number: "
read a
echo -n "Enter the second, bigger number: "
read b
    if
 [ $b -lt $a ]
then
 echo 'The first number must be smaller'
else
 echo The files in $1 that are between $a and $b bytes are the following
 echo
 for var in 'ls $1'
 do
  if
   [ -f $var ]
  then
    size='ls -l $var | '{ print $5 }''
     if
      [ $size -le $b && $size -ge $a ]
     then
      echo $var is $size bytes
     fi
  fi
 done
fi

The problem is after I enter the numbers, it will print out "The files..." and then nothing else. Also, I use Vi to edit it,but the color of last three lines is not quite right(the color should match the first "fi" but it not). Can anyone show me what was wrong? Thank you.


Solution

  • Your immediate problem is that you used single quotes where you wanted command substitution. However, this is the wrong way to iterate over files. You should use pattern matching instead. Your for loop should read

    for var in $1/*
    do
      if [ -f "$var" ]
      then
        # Check 'man stat' for the correct format string on your system
        size=$(stat +%s "$var")
        if [ $size -le $b ] &&  [ $size -ge $a ]
        then
          echo $var is $size bytes
        fi
      fi
    done