为什么 xargs 不能正确解析我的输入?

为什么 xargs 不能正确解析我的输入?

我一直在尝试编写一个 shell 脚本,该脚本将与 cmus 交互,然后使用通知发送通知我曲目信息。现在它不起作用,主要是因为 xargs 似乎没有向 notification-send 传递 2 个参数。它只发送一个,我不明白为什么。我已经用 sed 做了我能想到的一切来获得正确的输出,但它不起作用。另外,如果我使用带有两个参数的notify-send,它就可以工作,所以我不认为这是notify-send的问题。

cmus-remote -Q 的输出是:

status paused
file /home/dennis/music/Coheed And Cambria/GOODAP~1/05 Crossing the Frame.mp3
duration 207
position 120
tag artist Coheed & Cambria
tag album Good Apollo I'm Burning Star IV Volume One: From Fear Through the Eyes of Madness
tag title Crossing the Frame
tag date 2005
tag genre Rock
tag tracknumber 5
tag albumartist Coheed & Cambria
set aaa_mode all
set continue true
set play_library true
set play_sorted false
set replaygain disabled
set replaygain_limit true
set replaygain_preamp 6.000000
set repeat false
set repeat_current false
set shuffle true
set softvol false
set vol_left 100
set vol_right 100

我的代码很糟糕。我刚刚开始学习 shell 脚本,对此感到抱歉。

#!/bin/sh
#
# notify of song playing

info="$(cmus-remote -Q)"

title="`echo "$info" | grep 'tag title' | sed "s/'//g" | sed 's/tag title \(.*\)/'\''\1'\''/g'`"

artist="`echo "$info" | grep 'tag artist' | sed "s/'//g" | sed 's/tag artist \(.*\)/ '\''\1/g'`"
album="`echo "$info" | grep 'tag album ' | sed "s/'//g" | sed 's/tag album \(.*\)/ \1'\''/g'`"

stupid="${title}${artist}$album"
echo "$stupid" | xargs notify-send

答案1

xargs正在按预期工作;每行都作为参数。如果需要多个参数,请用换行符分隔它们。

{echo "$title"; echo "$artist"; echo "$album"} | xargs notify-send

也就是说,您为一些非常简单的事情做了太多的工作:

title="$(echo "$info" | sed -n 's/^tag title //p')"
artist="$(echo "$info" | sed -n 's/^tag artist //p')"
album="$(echo "$info" | sed -n 's/^tag album //p')"
notify-send "$title" "$artist" "$album"

(另请注意另一个问题: notify-osd发送通过 Pango 传递的消息,因此您需要转义任何可能被误认为 Pango 标记的内容。这意味着<, >,&在实践中,就像 HTML 和 XML 一样。上面的内容不尝试来处理这个问题。)

相关内容