我正在学习bash,但现在让这个脚本工作起来有很多问题:
#!/bin/bash
A="0"
B="0"
C="0"
D="0"
E="0"
F="0"
G="0"
while true; do
sleep 1
BATTERY='cat battery.txt'
if [["$BATTERY" -le 100] && ["$BATTERY" -gt 85] && [$A -eq 0]]; then
A="1"
commands...
elif [["$BATTERY" -le 85] && ["$BATTERY" -gt 70] && [$B -eq 0]]; then
B="1"
commands...
elif [["$BATTERY" -le 70] && ["$BATTERY" -gt 55] && [$C -eq 0]]; then
C="1"
commands...
elif [["$BATTERY" -le 55] && ["$BATTERY" -gt 40] && [$D -eq 0]]; then
D="1"
commands...
elif [["$BATTERY" -le 40] && ["$BATTERY" -gt 25] && [$E -eq 0]]; then
E="1"
commands...
elif [["$BATTERY" -le 25] && ["$BATTERY" -gt 10] && [$F -eq 0]]; then
F="1"
commands...
elif [["$BATTERY" -le 10] && ["$BATTERY" -gt 0] && [$G -eq 0]]; then
G="1"
commands...
fi
done当我执行这个脚本时,我得到的错误是:
./changewill.sh: line 17: [[cat battery.txt: command not found
./changewill.sh: line 27: [[cat battery.txt: command not found
./changewill.sh: line 36: [[cat battery.txt: command not found
./changewill.sh: line 45: [[cat battery.txt: command not found
./changewill.sh: line 54: [[cat battery.txt: command not found
./changewill.sh: line 63: [[cat battery.txt: command not found
./changewill.sh: line 72: [[cat battery.txt: command not found我一直在阅读和查看,我认为cat的输出是正确的分配给电池。我尝试了一些不同的东西,比如{ [ ¨,但都不起作用。是的,该文件存在,并且与脚本位于同一文件夹中。
有什么建议吗?
发布于 2012-09-28 16:19:45
BATTERY='cat battery.txt'它不会执行cat battery.txt,它只是将"cat battery.txt“作为字符串保存到变量中。
您应该:
BATTERY=$(cat battery.txt)或
BATTERY=`cat battery.txt`(首选第一种形式。)
你的测试也有语法错误。例如,使用:
elif [[ $BATTERY -le 10 && $BATTERY -gt 0 && $G -eq 0 ]]; then ...[和[[实际上是完全不同的东西。
[是test程序(查看ls /usr/bin/[和man test),[[ expr ]]是shell复合命令(conditional expression)。
发布于 2012-09-28 16:19:43
要获得命令的输出,需要用反引号将命令括起来,而不是用引号:
BATTERY=`cat battery.txt`
^ ^发布于 2012-09-28 16:20:54
条件的正确语法是
[[ $BATTERY -le 55 && $BATTERY -gt 40 && $D -eq 0 ]]即没有单个方括号。对于数字比较,您也可以使用双括号:
if (( BATTERY==55 && BATTERY > 40 && D == 0 )) ; then ...https://stackoverflow.com/questions/12636170
复制相似问题