To address the specific question:
Do I need to convert the string to an int some how?
The answer is no. Shell variables are all strings, but depending on the context in which they're used they can be treated as integers or strings. In case of -le
operator for [
command (aka test
command), variables will be treated as integers.
# integer comparison
$ var=25; test "$var" -le "$HOME"
bash: test: /home/username: integer expression expected
$ test "$var" -le 30 && echo Lower
Lower
# string comparison
$ test $var = 24 && echo 'same string' || echo 'different string'
different string
$ test $var = 25 && echo 'same string' || echo 'different string'
same string
Your script needs to initialize counter
variable, drop $
from numOfBytes
in read
, and remove $
from let
.
#!/bin/bash
read -p "How many bytes would you like you replace :> " numOfBytes
echo "$numOfBytes bytes to replace"
counter=0
while [ "$counter" -le "$numOfBytes" ]
do
echo "testing counter value = $counter"
let counter++
done
This works as so:
$ ./counter.sh
How many bytes would you like you replace :> 5
5 bytes to replace
testing counter value = 0
testing counter value = 1
testing counter value = 2
testing counter value = 3
testing counter value = 4
testing counter value = 5
Note that due to let
being bash
/ksh
keyword, this makes the script less portable. It'd be advisable to make use of arithmetic expansion counter=$((counter+1))
, which is part of POSIX's Shell Language standard (section 2.6.4).
See also: https://askubuntu.com/a/939299/295286
As Storm Dragon pointed out, the fact that shell variables are treated depending on their context also implies that user's input needs to be sanitized. One possible way is to take numOfBytes
into portable case
steatement as in this answer, which takes care of determining whether the input is actually a digit.
$
on$numOfBytes
in theread
command, and usecounter=$(( counter + 1 ))
for the increment. Also double quote you variable expansions.