在Bash中减去两个变量 [英] Subtract two variables in Bash

查看:69
本文介绍了在Bash中减去两个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的脚本来减去两个目录之间的文件数,但是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

推荐答案

您只需要在减号和反引号周围加上一些空白:

You just need a little extra whitespace around the minus sign, and backticks:

COUNT=`expr $FIRSTV - $SECONDV`

请注意退出状态:

如果EXPRESSION既不为null也不为0,则退出状态为0;如果EXPRESSION为null或0,则退出状态为1 .

The exit status is 0 if EXPRESSION is neither null nor 0, 1 if EXPRESSION is null or 0.

在bash脚本中将表达式与 set -e 结合使用时,请记住这一点,如果命令以非零状态退出,则表达式将立即退出.

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.

这篇关于在Bash中减去两个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆