简体   繁体   中英

Shell script variable & loop

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"

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)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM