1

I am testing following code that intends to get input from user and after checking some conditions store it to a new variable. However, this code is not giving me any output or error upon running in the shell terminal. I have given execution permission to the file by sudo chmod +x test.sh.

#!/bin/bash counter="0" iso_val="100" while [ "$counter" == "3" ] do echo -n "Enter ISO [ 100-800 ]: "; read iso if (( "$iso" < "100" )) || (( "$iso" > "800" )); then echo "Error!" elif [ "$iso" == "" ]; then echo "Error!" else iso_val=$iso break fi counter=$[$counter + 1] done 
3
  • 1
    You set counter to 0 and then started a while loop which only runs when it's 3. O.o Obviously the loop will never run.
    – muru
    CommentedDec 3, 2019 at 4:49
  • I changed it, still no output. counter="1" iso_val="100" while [ "$counter" = "3" ]CommentedDec 3, 2019 at 5:06
  • I am increment in counter also. I don't understand what I am doing wrong here. Can you please correct me where it is wrong.CommentedDec 3, 2019 at 5:07

1 Answer 1

2

Your script as written runs without error and would not produce output.

A quick note: you should temporarily add set -x at the beginning of your bash scripts for getting a good start on debugging.

The issue is the line:

while [ "$counter" == "3" ] 

The do block following that line would only be run if $counter was equal to 3, but $counter will not increment unless that do block is ran.

You would need something outside the block you wish to execute to increment your counter. i.e.

#!/bin/bash counter="0" iso_val="100" while [ "$counter" -lt 3 ] do echo -n "Enter ISO [ 100-800 ]: "; read iso if [ -z "$iso" ] || [ "$iso" -lt 100 ] || [ "$iso" -gt 800 ]; then echo "Error!" else iso_val=$iso break fi counter=$(($counter + 1)) done 

I set a limit to how many times while is ran, otherwise the script does not exit on error. I also changed your string comparisons to integer comparisons where I could.

Edit: New script with clarified requirement from comments, "ask up to three times on error"

2
  • Thank you so much for such a nice explanation. Actually, I want to give 3 tries to the user to enter a value, that is why I am using while loop and counter.CommentedDec 3, 2019 at 5:37
  • I made some changes to fit that requirementCommentedDec 3, 2019 at 7:33

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.