在 Bash 脚本变量中使用命令

Using commands in Bash Script Variables

我有一个 bash 脚本可以检查 Dropbox 的当前状态

#!/bin/bash
while true
do
    echo Dropbox Status: 
    ~/bin/dropbox.py status
    sleep 1
    clear
done

这会产生如下所示的输出。

Dropbox Status: 
Up to date

不过我希望它看起来像这样。所以这一切都在一条线上

Dropbox Status: Update

我试过

等脚本
#!/bin/bash
while true
do
    STATUS=~/bin/dropbox.py status
    echo Dropbox Status: $STATUS
    sleep 1
    clear
done

然而,这只会产生错误,例如 Dropbox Status.sh: status: not found

有什么办法可以实现我的目标吗?

此外,如果这很明显,我深表歉意,因为我是 Bash Script

的新手

感谢您的帮助。

您需要将命令结果存储在您的状态变量中

  STATUS=$(~/bin/dropbox.py status)

使用printfcommand substitution:

printf "Dropbox Status: %s\n" "$(~/bin/dropbox.py status)"

或中间变量:

status=$(~/bin/dropbox.py status)
printf "Dropbox Status: %s\n" "$status"

还要记得引用你的变量,否则它们将经历 word splitting

为什么 STATUS=~/bin/dropbox.py status 不起作用?发生的事情是命令 status 被调用,环境变量 STATUS 设置为 ~/bin/dropbox.py,有点像 运行:

_status=$STATUS
export STATUS=~/bin/dropbox.py
status
export STATUS=_status

但没有所有的临时变量