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

查看:32
本文介绍了在 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 既不为空也不为 0,则退出状态为 0,如果 EXPRESSION 为空或 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天全站免登陆