[英]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
. 你的错误是
$x=$var
。 It should be x=$var
. 它应该是
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. 您可以将其视为
$x
是变量x
包含的值,因此您不希望分配给x
值而是分配给x
本身。
#!/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: 这是一个使用一些core-utils的替代脚本,它将使用负数:
#!/bin/bash
echo "Largest: $(printf '%i\n' $@ | sort -n | tail -n 1)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.