Bash 中两个变量相减
我有下面的脚本来减去两个目录之间的文件计数,但 COUNT=
表达式不起作用。正确的语法是什么?
#!/usr/bin/env bash
FIRSTV=`ls -1 | wc -l`
cd ..
SECONDV=`ls -1 | wc -l`
COUNT=expr $FIRSTV-$SECONDV ## -> gives 'command not found' error
echo $COUNT
I have the script below to subtract the counts of files between two directories but the COUNT=
expression does not work. What is the correct syntax?
#!/usr/bin/env bash
FIRSTV=`ls -1 | wc -l`
cd ..
SECONDV=`ls -1 | wc -l`
COUNT=expr $FIRSTV-$SECONDV ## -> gives 'command not found' error
echo $COUNT
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
尝试使用此 Bash 语法,而不是尝试使用外部程序
expr
:顺便说一句,使用
expr
的正确语法是:但请记住使用
expr
> 将比我上面提供的内部 Bash 语法慢。Try this Bash syntax instead of trying to use an external program
expr
:BTW, the correct syntax of using
expr
is:But keep in mind using
expr
is going to be slower than the internal Bash syntax I provided above.您只需要在减号和反引号周围添加一些额外的空格:
请注意退出状态:
如果 EXPRESSION 既不为 null 也不为 0,则退出状态为 0;如果 EXPRESSION 为 null 或 0,则退出状态为 1。
在 bash 脚本中与 set -e 结合使用表达式时,请记住这一点,如果命令以非零状态退出,它将立即退出。
You just need a little extra whitespace around the minus sign, and backticks:
Be aware of the exit status:
The exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null or 0.
Keep this in mind when using the expression in a bash script in combination with set -e which will exit immediately if a command exits with a non-zero status.
您可以使用:
来避免调用单独的进程,如以下记录所示:
You can use:
to avoid invoking a separate process, as per the following transcript:
这就是我在 Bash 中做数学的方式:
This is how I always do maths in Bash:
空格很重要,
expr
希望其操作数和运算符作为单独的参数。您还必须捕获输出。像这样:但更常见的是使用内置算术扩展:
White space is important,
expr
expects its operands and operators as separate arguments. You also have to capture the output. Like this:but it's more common to use the builtin arithmetic expansion:
对于简单的整数运算,您还可以使用内置的 let 命令。
有关
let
的更多信息,请查看此处 。For simple integer arithmetic, you can also use the builtin let command.
For more info on
let
, look here.除了建议的 3 种方法之外,您还可以尝试
let
对变量执行算术运算,如下所示:let COUNT=$FIRSTV-$SECONDV
或
let COUNT=FIRSTV-SECONDV
Alternatively to the suggested 3 methods you can try
let
which carries out arithmetic operations on variables as follows:let COUNT=$FIRSTV-$SECONDV
or
let COUNT=FIRSTV-SECONDV
区分实数正数
用法
Diff Real Positive Numbers
Usage
使用 BASH:
输出
Use BASH:
Output