数字的绝对值 [英] Absolute value of a number
问题描述
我想通过bash中的以下代码获取数字的绝对值:
#!/bin/bashecho输入第一个文件名:"首先阅读echo输入第二个文件名:"阅读第二s1 = $(stat --format =%s"$ first")s2 = $(stat -c'%s'"$ second")res = expr $ s2-$ s1如果["$ res" -lt 0]然后res = $ res \ * -1科幻回声$ res
现在我面临的问题是if语句,无论我进行什么更改,它总是出现在if中,我尝试将 [[]]
放在语句周围,但是什么也没有.>
这是错误:
./p6.sh:第13行:[::预期为整数表达式
$ s2 = 5 s1 = 4$ echo $ s2 $ s15 4$ res = expr $ s2-$ s11个$ echo $ res
第四行实际发生的事情是,将 res
设置为空并为 expr
命令导出.因此,当您运行 ["$ res" -lt 0]
res
扩展为空时,您会看到错误.
您可以只使用算术表达式:
$((res = s2-s1))$ echo $ res1个
算术上下文保证结果将为整数,因此即使未定义所有术语,您也将获得整数结果(即零).
$((res = whoknows-whocares));回声$ res0
或者,您可以这样声明外壳,从而告诉外壳 res
是整数:
$声明-i res$ res = s2-s1
这里有趣的是,赋值的右侧在算术上下文中处理,因此您不需要 $
进行扩展.
I want to take the absolute of a number by the following code in bash:
#!/bin/bash
echo "Enter the first file name: "
read first
echo "Enter the second file name: "
read second
s1=$(stat --format=%s "$first")
s2=$(stat -c '%s' "$second")
res= expr $s2 - $s1
if [ "$res" -lt 0 ]
then
res=$res \* -1
fi
echo $res
Now the problem I am facing is in the if statement, no matter what I changes it always goes in the if, I tried to put [[ ]]
around the statement but nothing.
Here is the error:
./p6.sh: line 13: [: : integer expression expected
$ s2=5 s1=4
$ echo $s2 $s1
5 4
$ res= expr $s2 - $s1
1
$ echo $res
What's actually happening on the fourth line is that res
is being set to nothing and exported for the expr
command. Thus, when you run [ "$res" -lt 0 ]
res
is expanding to nothing and you see the error.
You could just use an arithmetic expression:
$ (( res=s2-s1 ))
$ echo $res
1
Arithmetic context guarantees the result will be an integer, so even if all your terms are undefined to begin with, you will get an integer result (namely zero).
$ (( res = whoknows - whocares )); echo $res
0
Alternatively, you can tell the shell that res
is an integer by declaring it as such:
$ declare -i res
$ res=s2-s1
The interesting thing here is that the right hand side of an assignment is treated in arithmetic context, so you don't need the $
for the expansions.
这篇关于数字的绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!