Reputation: 3278
I want to print the largest number passed in on the command line but I am not sure how to assign a variable correctly.
What is the correct way to solve this issue?
#!/bin/sh
x=0
for var in "$@";
do
if [ $var -gt $x ]; then
$x=$var #this does not work
fi
done
echo "Largest number: $x"
Upvotes: 1
Views: 2268
Reputation: 85765
Your mistake is $x=$var
. It should be x=$var
. You can think of it as $x
is the value contained the in variable x
so you don't want to assign to value of x
but to x
itself.
#!/bin/sh
x=0
for var in "$@"; do
if [ "$var" -gt "$x" ]; then
x="$var"
fi
done
echo "Largest number: $x"
Here is an alternative script using some core-utils that will work with negative numbers:
#!/bin/bash
echo "Largest: $(printf '%i\n' $@ | sort -n | tail -n 1)"
Upvotes: 3