Bash '+' 操作数错误 // 引号误用
Bash error with '+' operand // Quotes misuse
☿[~]$ alias hdd='echo Σ= $(($(df -BMB /dev/sdb1 --output=used | tail -1 | grep -o '[0-9]*')+$(df -BMB /dev/sdc1 --output=used | tail -1 | grep -o '[0-9]*'))) Mb'
这个别名突然停止工作:
☿[~]$ hdd
bash: +: syntax error: operand expected (error token is "+")
但命令仍然有效:
☿[~]$ echo Σ= $(($(df -BMB /dev/sdb1 --output=used | tail -1 | grep -o '[0-9]*')+$(df -BMB /dev/sdc1 --output=used | tail -1 | grep -o '[0-9]*'))) Mb
Σ= 3782845 Mb
不要使用别名;改为定义一些函数。
get_space_used () {
df -BMB "" --output=used | tail -1 | grep -o '[0-9]*'
}
hdd () {
sdb1=$(get_space_used /dev/sdb1)
sdc1=$(get_space_used /dev/sdc1)
echo "$(( sdb1 + sdc1 ))"
}
这使得引用更容易,重构重复代码,并且更容易在出现错误时查明问题所在。在你的例子中,第二个 df
管道有问题,因为 bash
试图执行类似 echo $(( foo + ))
.
的东西
☿[~]$ alias hdd='echo Σ= $(($(df -BMB /dev/sdb1 --output=used | tail -1 | grep -o '[0-9]*')+$(df -BMB /dev/sdc1 --output=used | tail -1 | grep -o '[0-9]*'))) Mb'
这个别名突然停止工作:
☿[~]$ hdd
bash: +: syntax error: operand expected (error token is "+")
但命令仍然有效:
☿[~]$ echo Σ= $(($(df -BMB /dev/sdb1 --output=used | tail -1 | grep -o '[0-9]*')+$(df -BMB /dev/sdc1 --output=used | tail -1 | grep -o '[0-9]*'))) Mb
Σ= 3782845 Mb
不要使用别名;改为定义一些函数。
get_space_used () {
df -BMB "" --output=used | tail -1 | grep -o '[0-9]*'
}
hdd () {
sdb1=$(get_space_used /dev/sdb1)
sdc1=$(get_space_used /dev/sdc1)
echo "$(( sdb1 + sdc1 ))"
}
这使得引用更容易,重构重复代码,并且更容易在出现错误时查明问题所在。在你的例子中,第二个 df
管道有问题,因为 bash
试图执行类似 echo $(( foo + ))
.