Can anyone give me a clue why this code doesn't work as expected? The function count_collatz_step() take one parameter which a number that need to calculate collatz until it reaches 1. The func should return steps it takes.
#
# Count steps of collatz conjecture takes, until the number reach 1.
#
count_collatz_step() {
step=0
if [ $1 % 2 == 0 ]
then
$1=$(($1/2))
step=$((step + 1))
else
$1=$((3*$n+1))
step=$((step + 1))
fi
echo $step
}
echo "Input start point: "
read -n start
echo "Input end point: "
read -n end
count=0
while [ $start -lt $end ]
do
echo $start + ":" + count_collatz_step $start
if [ $count % 7 -eq 0 ]
then
echo "\n"
fi
start=$((start+1))
count=$((count+1))
done
Hi Bunching,
Please show us your working C code. I'm guessing that you have misunderstood how echo and read work in bash and that your function might want to return a value rather than print a value, but without a description of what you're trying to do (rather than just a statement that your shell script isn't working), it is hard to guess how it should be corrected. But, one clear thing is that there is nothing in your code that invokes your function. (You print the name of the function as one of the arguments to one of your echo statements, but you do not call the function.)
Wisecracker,
Note that in a bash function, $1 is the 1st command line argument passed to the function; not a command line argument passed to the script containing the function definition.
Assigning the parameter to a (local) variable in the function is the right thing to do.
But - you can't use return in bash like you do in e.g. C as it will return an exit status into the $? special parameter, not a value to be used by the caller. Print the value instead.
On the caller's side, you need to execute the function, by either running it on the command line or by using the command substitution mechanism, which also allows to intercept the stdout and use it for e.g. an assignment. Try echo $start + ":" + $(count_collatz_step $start)