我有下面的脚本减去两个目录之间的文件计数,但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
我有下面的脚本减去两个目录之间的文件计数,但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
当前回答
除了建议的3种方法,你可以尝试let,它对变量进行如下算术运算:
让数= FIRSTV - SECONDV美元
or
允许数= FIRSTV-SECONDV
其他回答
对于简单的整数运算,也可以使用内置的let命令。
ONE=1
TWO=2
let "THREE = $ONE + $TWO"
echo $THREE
3
更多关于let的信息,请看这里。
这是我在Bash中做数学的方法:
count=$(echo "$FIRSTV - $SECONDV"|bc)
echo $count
Diff实数
diff_real () {
echo "df=($1 - $2); if (df < 0) { df=df* -1}; print df" | bc -l;
}
使用
var_a=10
var_b=4
output=$(diff_real $var_a $var_b)
# 6
#########
var_a=4
var_b=10
output=$(diff_real $var_a $var_b)
# 6
使用BASH:
#!/bin/bash
# home/victoria/test.sh
START=$(date +"%s") ## seconds since Epoch
for i in $(seq 1 10)
do
sleep 1.5
END=$(date +"%s") ## integer
TIME=$((END - START)) ## integer
AVG_TIME=$(python -c "print(float($TIME/$i))") ## int to float
printf 'i: %i | elapsed time: %0.1f sec | avg. time: %0.3f\n' $i $TIME $AVG_TIME
((i++)) ## increment $i
done
输出
$ ./test.sh
i: 1 | elapsed time: 1.0 sec | avg. time: 1.000
i: 2 | elapsed time: 3.0 sec | avg. time: 1.500
i: 3 | elapsed time: 5.0 sec | avg. time: 1.667
i: 4 | elapsed time: 6.0 sec | avg. time: 1.500
i: 5 | elapsed time: 8.0 sec | avg. time: 1.600
i: 6 | elapsed time: 9.0 sec | avg. time: 1.500
i: 7 | elapsed time: 11.0 sec | avg. time: 1.571
i: 8 | elapsed time: 12.0 sec | avg. time: 1.500
i: 9 | elapsed time: 14.0 sec | avg. time: 1.556
i: 10 | elapsed time: 15.0 sec | avg. time: 1.500
$
获取当前时间,以秒为单位,自纪元的Linux, Bash
空格很重要,expr期望它的操作数和操作符作为单独的参数。您还必须捕获输出。是这样的:
COUNT=$(expr $FIRSTV - $SECONDV)
但更常见的是使用内置算术展开:
COUNT=$((FIRSTV - SECONDV))