简体   繁体   English

在Bash脚本变量中使用命令

[英]Using commands in Bash Script Variables

I have a bash script which checks the current status of Dropbox 我有一个bash脚本,用于检查Dropbox的当前状态

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

This produces a output which can look like this. 这将产生一个看起来像这样的输出。

Dropbox Status: 
Up to date

However I would like it to look like this. 但是我希望它看起来像这样。 So it is all on one line 一切都在一条线上

Dropbox Status: Update

I have tried scripts such as 我尝试了诸如

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

However this just creates errors such as Dropbox Status.sh: status: not found 但是,这只会产生诸如Dropbox Status.sh: status: not found错误Dropbox Status.sh: status: not found

Is there a way to do what I am after? 有什么办法可以做我所追求的吗?

Also if it is blatantly obvious I apologize since I am new to Bash Script 另外,如果这很明显,我道歉,因为我是Bash Script新手

Thanks for any help. 谢谢你的帮助。

您需要将命令结果存储在状态var中

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

Use printf and command substitution : 使用printf命令替换

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

or with intermediate variable: 或带有中间变量:

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

Also remember to quote your variables or they will undergo word splitting 还请记住引用您的变量,否则它们会分词

Why doesn't STATUS=~/bin/dropbox.py status work? 为什么STATUS=~/bin/dropbox.py status不起作用? Whats happens is that the command status is called with the environment variable STATUS set to ~/bin/dropbox.py , sort of the same as running: 发生的情况是,使用环境变量STATUS设置为~/bin/dropbox.py调用命令status ,类似于运行:

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

But without all the temporary variables 但是没有所有的临时变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM