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:
Notice how the
$
is not used when reading the value. With$var
you get the value of the variablevar
, butread
needs to know the name of the variable to read into, not its value.or, with a while loop,
The
(( ... ))
inbash
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
,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 theIFS
variable happens to contain digits.Related questions: