Ubuntu: Failing with shell script



Question:

I am trying to run the following script in Ubuntu 10.04 but hitting with different issues for the intget i declaration. Could anyone please help me asap

integer i    i=1    while true      do      read response        if [ -z == $response ]       then       continue       fi        if [ $response == "q" ]      then       break      fi          if [ -f /var/tmp/UE1_${i}.txt ]      then        cat /var/tmp/UE1_${i}.txt        i=$i+1      fi          if [ $i -eq  100 ]       then       break      fi    done  


Solution:1

integer i  i=1  

Simple i=1 without spaces is enough.

if [ -z == $response ]       then          continue   fi  

continue means skip everything in the loop that comes after continue and goto next iteration of loop. I don't think that's what you intended to do.

if [ $response == "q" ]  

It's a best practice to enclose variable names in double quotes ("$response") when referencing.

i=$i+1  

This will assign 1+1 as a string to $i instead on 2. You can either use expr:

i=$(expr $i + 1)  

or simply use:

(( i++ ))  

Your final script will look somthing like this:

#!/bin/bash    i=1    while true  do      read response        if [ "$response" == "q" ]      then          break      fi        if [ -f /var/tmp/UE1_${i}.txt ]      then          cat /var/tmp/UE1_${i}.txt          i=$(expr $i + 1)      fi        if [ $i -eq  100 ]       then          break      fi    done  

For more info on bash scripting checkout this excellent tutorial: Advanced Bash-Scripting Guide.


Solution:2

In bash you dont have to declare types as in other languages such as in C family.

So the first line integer i causes erros in its form. You can just remove it.

There is a case where you can tell bash that the declared variable must be treated as of some type, this can be done if you edit the first line to: declare (option) variable=value in your case:
declare -r i=1 the -r option tells bash that the variable must be treated as an integer.

You can check the available options for variable declarations here.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »