In addition to missing a spaces in [ i%2 -eq 0 ]
and [ "$1" -lt 50 ]
, your arithmetic use is incorrect along with several variable assignment issues. You need to assign the result of the arithmetic to the value at hand. The form is var=value
, not value == var
.
You have 3 choices for how to do arithmetic in bash. The old newval=$(expr i / 2)
or let newval="$i"/2
or newval=$((i / 2))
:
Cleaning up your script, you could do something like:
if [ "$1" -gt 1 ] && [ "$1" -lt 50 ]
then
for i in $1; do
//if $i is even
if (( i % 2 == 0 ))
then
newvar=$((i / 2))
echo "$newvar,"
//if $i is odd
else
newvar=$((3 * i + 1))
echo "$newvar,"
fi
done
fi
Note, while you can multiply and reassign the loop increment i
, it is far better to assign the result to a new variable, e.g. some newvar
.
Note how:
newvar=$((i / 2))
and
newvar=$((i * 3 + 1))
It also looks like you intended:
if [ "${#1}" -gt 1 ] && [ "${#1}" -lt 50 ]
to check that the number of characters given is between 1
and 50
, otherwise, your for i in $1; do
does not make a lot of sense. If you are just testing the value and not the number of characters, get rid of the for
altogether:
if [ "$1" -gt 1 -a "$1" -lt 50 ]
then
val="$1" ## assign positinal parameter to variable
## if $val is even ## to avoid subtleties in syntax
if (( val % 2 == 0 ))
then
newvar=$((val / 2))
echo "$newvar,"
## if $val is odd
else
newvar=$((3 * val + 1))
echo "$newvar,"
fi
fi
Alternative
If I have figured out what you are trying to do, then you might consider doing it this way:
#!/bin/bash
declare -i val
if [ "$1" -gt 1 -a "$1" -lt 50 ]; then
val="$1" # assign val=$1
while ((val > 0)); do # loop for val > 0
if ((val > 1)); then # set output format
fmt="%d,"
else
fmt="%d"
fi
if ((val % 2 == 0)) # if $val is even
then
n=$((val / 2))
else # if $val is even
n=$((val * 3 + 1))
fi
printf "$fmt" "$n"
((val--)) # decrement val
done
else
printf "input value not between 1 and 50\n"
fi
printf "\n"
Example Use/Output
$ bash ql.sh 10
5,28,4,22,3,16,2,10,1,4
Or, rewritten in a more compact form using compound commands:
#!/bin/bash
declare -i val
if [ "$1" -gt 1 -a "$1" -lt 50 ]; then # validate input 1 - 50
for ((val = $1; val > 0; val--)); do # loop for val > 0
((val > 1)) && fmt="%d," || fmt="%d" # print format
((val % 2 == 0)) && n=$((val / 2)) || n=$((val * 3 + 1)) # even/odd
printf "$fmt" "$n"
done
else
printf "input value not between 1 and 50\n"
fi
printf "\n"