【问题标题】:bash script retrieve dbus outputbash 脚本检索 dbus 输出
【发布时间】:2015-01-15 17:28:01
【问题描述】:

今天要取回dbus命令的结果。

dbus-send --session --print-reply --dest="com.ac.comp" /com/ac/comp/Time com.ac.comp.Time.GetTime

当我执行上述命令时,我得到以下输出:

method return sender=:1.0 -> dest=:1.34 reply_serial=2
   byte 0
   byte 0
   byte 0
   byte 0
   byte 0
   byte 0
   uint16 0

值按照以下顺序给出:

second
minute
hour
weekday
dateday
month
year

我的 bash 实现如下:

dbus-send --session --print-reply --dest="com.ac.comp" /com/ac/comp/Time com.ac.comp.Time.GetTime | grep -E byte | cut -c 9-11 > "$file" 
dbus-send --session --print-reply --dest="com.ac.comp" /com/ac/comp/Time com.ac.comp.Time.GetTime | grep -E uint16 | cut -c 11-13 >> "$file" 

second=$(sed -n '1p' < $file)
minute=$(sed -n '2p' < $file)
hour=$(sed -n '3p' < $file)
weekday=$(sed -n '4p' < $file)
dateday=$(sed -n '5p' < $file)
month=$(sed -n '6p' < $file)
year=$(sed -n '7p' < $file) 
echo -e "Time ==> Day : $weekday - Date : $dateday/$month/$year - Time : $hour:$minute:$second"  

作业已正确完成。但是,我确信我的脚本可以最大化并且 dbus 不必被调用两次,并且有一种方法可以用更少的行来完成所有的事情。

作为新的 bash 程序员,我需要有关此问题的建议并学习新方法。

【问题讨论】:

  • 您不需要使用额外的重定向,sed 能够从文件中读取输入。那就是sed -n '1p' $file 可以正常工作
  • 谢谢!我刚试过你的指令,结果相同,删除了七行 --'
  • 无需预先剪切文件。 sed 也可以做到这一点(并且以一种不易出错的方式)。 sed -e '1{s/^ \+(byte|uint16) //;p}' 或类似的东西。虽然这是否会或多或少有效率取决于在 N sed 实例中执行该工作是否比在一个剪切实例中执行 N 次更好。
  • 您的意思是您提供的 sed 命令可以生成相同的输出?我尝试了同一行并进行了修改,但我只获得了第一行。谢谢
  • 我很抱歉 Etan 但一小时后我无法应用您的示例,因此仅调用 dbus-send 一次并仅存储字节和 uint16 值。你能提供更多细节吗?

标签: bash shell dbus


【解决方案1】:
array=($(dbus-send --session --print-reply --dest="com.ac.comp" /com/ac/comp/Time com.ac.comp.Time.GetTime))

也许这里的某个地方是你所追求的:

echo "Seconds = ${array[7]}"
echo "Minutes = ${array[9]}"
.
.

【讨论】:

  • 谢谢 ajaaskel !这是一个很好的选择,我没有义务创建文件。但是,我必须问最后一个问题。为什么指定 ${array[7]} 来检索第一个字节值?在“method return sender=:1.0 -> dest=:1.34 reply_serial=2”这一行中只有五个术语?
  • 我刚刚从您的输出中计算出,您将首先获得那些不需要的额外字符串,并且第一个数据可能会转到索引 7,即该数组中的单元格编号 8,因为存在单词 "字节”之前的实际值。即 0:method 1:return 2:sender=:1.0 3:-> 4:..
猜你喜欢
  • 1970-01-01
  • 2017-11-21
  • 1970-01-01
  • 2010-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 2018-05-18
相关资源
最近更新 更多