Shell 脚本报错:unary operator expected - 解决方法
#!/bin/sh
内存总量
total=$( free -m | grep Mem | awk '{print $2}')
已使用内存
used=$( free -m | grep Mem | awk '{print $3}')
空闲内存
free=$( free -m | grep Mem | awk '{print $4}')
内存使用率
rate=$((($total-$free)*100/$total))
time=$(date) echo '############$time###############'
#$1 is max Mem if [ $rate -gt '$1' ] then echo 'rate=$rate freeMemory start!' sync sudo sh -c 'echo 3 >> /proc/sys/vm/drop_caches' echo 'FreeMemory Success!' else echo 'rate=$rate Memory is normal' fi
解决“unary operator expected”错误:
该错误通常发生在使用变量进行比较或计算时,缺少双引号导致变量未被正确解析。例如,在上面的脚本中,第 16 行的 time=date 应该改为 time=$(date),第 23 行的 $1 应该用双引号包裹,即 '$1'。
正确使用双引号和赋值操作符:
- 双引号用来将变量的值作为字符串传递给命令或函数。
- 赋值操作符
=用来将一个值赋给一个变量。
修改后的脚本:
#!/bin/sh
# 内存总量
total=$( free -m | grep Mem | awk '{print $2}')
# 已使用内存
used=$( free -m | grep Mem | awk '{print $3}')
# 空闲内存
free=$( free -m | grep Mem | awk '{print $4}')
# 内存使用率
rate=$((($total-$free)*100/$total))
time=$(date)
echo '############$time###############'
#$1 is max Mem
if [ $rate -gt '$1' ]
then
echo 'rate=$rate freeMemory start!'
sync
sudo sh -c 'echo 3 >> /proc/sys/vm/drop_caches'
echo 'FreeMemory Success!'
else
echo 'rate=$rate Memory is normal'
fi
总结:
在编写 shell 脚本时,应注意变量的正确使用,特别是使用双引号和赋值操作符时,以避免出现 “unary operator expected” 等错误。
原文地址: https://www.cveoy.top/t/topic/n5ju 著作权归作者所有。请勿转载和采集!