1

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"
1
  • 2
    To assign a value to a variable you do var=$something. Change $x=$var to x=$var. Commented Oct 16, 2013 at 10:24

1 Answer 1

3

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)"
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, thought I was close @sudo_O

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.