【发布时间】:2020-11-01 15:36:42
【问题描述】:
我不确定我的 shell 脚本有什么问题,但我猜测它与环境变量有关。我的脚本在我的树莓派上运行 gridcoinresearchd。如果我的网格币余额增加,我希望它关闭 pi 灯,然后重新打开它们。我不确定我是否正确设置了变量。我不确定脚本、shell 和父 shell 是否都设置为执行我想要执行的操作。任何帮助,将不胜感激。到目前为止,这是我的脚本:
#This script turns off sleep mode, activates gridcoinresearchd and turns off the rasperry pi red and green lights. It then records the gridcoin balance and saves the balance as "PREVIOUSBALANCE". The script then checks every 15 minutes to see if the real Gridcoin balance "CURRENTBALANCE" has increased. If the balance has increased, the script turns the lights back on. This script must be run as sudo.
#Disable sleep mode
systemctl mask sleep.target suspend.target hibernate.target hybrid-sleep.target
#Activate gridcoinresearchd
gridcoinresearchd &
sleep 360
# Disable the red and green motherboard LEDs.
sh -c 'echo 0 > /sys/class/leds/led0/brightness'
sh -c 'echo 0 > /sys/class/leds/led1/brightness'
# Get and set "PREVIOUSBALANCE"
export PREVIOUSBALANCE=`gridcoinresearchd getinfo | grep "balance" /dev/stdin | tr '\n' ' ' | sed -e 's/[^0-9.]/ /g' -e 's/^ *//g' -e 's/ *$//g' | tr -s ' '`
# Get "CURRENTBALANCE"
export CURRENTBALANCE=`gridcoinresearchd getinfo | grep "balance" /dev/stdin | tr '\n' ' ' | sed -e 's/[^0-9.]/ /g' -e 's/^ *//g' -e 's/ *$//g' | tr -s ' '`
# If CURRENTBALANCE is greater than PREVIOUSBALANCE then turn on the lights.
if [ "CURRENTBALANCE" > "PREVIOUSBALANCE" ]; then
sh -c 'echo 14 > /sys/class/leds/led0/brightness'
sh -c 'echo 14 > /sys/class/leds/led1/brightness'
fi
【问题讨论】:
-
在
[ ]中使用>创建一个文件,该文件的名称与指向它的变量的名称相同,因为它被视为重定向而不是比较,有些人会转义@ 987654328@ 但大多数人使用新的[[ ]],或者如果使用 bash 使用(( ))这是一个算术运算符/评估器,在你的脚本上放一个 shebang 并尝试 shellcheck.net 来验证你的脚本。 -
使用
if [ "${CURRENTBALANCE}" > "${PREVIOUSBALANCE}" ]; then -
顺便说一句:
sh(Bourne-shell) 通常不是bash(Bourne-again shell)。 -
始终通过shellcheck 运行您的问题脚本。
-
不需要
export一个只被当前脚本使用的变量。export的目的是向 swbprocesses 公开一个变量。 (例如,PYTHONPATH需要export才能让 Python 子进程访问它。)
标签: bash shell scripting raspberry-pi environment-variables