【问题标题】:How do I use environment variables in shell scripts? [duplicate]如何在 shell 脚本中使用环境变量? [复制]
【发布时间】: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


【解决方案1】:

您的错误出现在 if 语句中,在“sh”中,您无法使用“”符号比较算术值。因此,您可以使用 'eq, gt, ge, lt, le'。您还忘记了变量中的“$”符号。这是修复:

....
    
if [ "$CURRENTBALANCE" -gt "$PREVIOUSBALANCE" ]; then
        sh -c 'echo 14 > /sys/class/leds/led0/brightness'
        sh -c 'echo 14 > /sys/class/leds/led1/brightness'
fi
....

【讨论】:

  • 他们也不需要将命令包装在sh -c 中。如果您需要将它们包装在 sudo 中,这将是模糊的,但这不是这里的 chse。只需将 echo 14 >device 作为当前脚本的一部分。
  • 是的,当然没有意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-02
  • 2010-10-04
  • 2020-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多