Bash – While loop using a counter utilizing user’s input of an integer

bashshell-script

I am working on a script and I have a while in which I want to take the user input and use as an integer value with a counter like so:

read -p "How many bytes would you like you replace :> " $numOfBytes
echo "$numOfBytes bytes to replace"
while [ $counter -le $numOfBytes ]
do
    echo "testing counter value = $counter"
    let $counter++
done

To my understanding it doesn't currently work because it is taking the numOfBytes variable as a string.

Do I need to convert the string to an int some how? Is it possible to do something like that? Is there an alternative?

Best Answer

You want to read an integer and then do a loop from 1 to that integer, printing the number in each iteration:

#!/bin/bash

read -p 'number please: ' num

for (( i = 1; i <= num; ++i )); do
    printf 'counter is at %d\n' "$i"
done 

Notice how the $ is not used when reading the value. With $var you get the value of the variable var, but read needs to know the name of the variable to read into, not its value.

or, with a while loop,

#!/bin/bash

read -p 'number please: ' num

i=0
while (( ++i <= num )); do
    printf 'counter is at %d\n' "$i"
done

The (( ... )) in bash is an arithmetic context. In such a context, you don't need to put $ on your variables, and variables' values will be interpreted as integers.

or, with /bin/sh,

#!/bin/sh

printf 'number please: ' >&2
read num

i=1
while [ "$i" -le "$num" ]; do
    printf 'counter is at %d\n' "$i"
    i=$(( i + 1 ))
done

The -le ("less than or equal") test needs to act on two quoted variable expansions (in this code). If they were unquoted, as in [ $i -le $num ], then, if either variable contained a shell globbing character or a space, you might get unexpected results, or errors. Also, quoting protects the numbers in case the IFS variable happens to contain digits.

Related questions:

Related Question