修改〜/ .bashrc中的“alert”别名
系统:Lubuntu 14.04 LTS
我想知道是否可以以特定方式修改~/.bashrc
中提供的alert
别名。 这是原始alert
:
# Add an "alert" alias for long running commands. Use like so: # sleep 10; alert alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
使用默认别名“alert”解释它的作用。
以下是我运行ls; alert
时系统上的默认通知示例(使用xfce4-notify
) ls; alert
ls; alert
,当然,成功完成:
如果我运行一个荒谬的命令, asdfgh; alert
asdfgh; alert
,我看到了这个:
由于error
图标, terminal
图标已被替换为error
图标
-i "$([ $? = 0 ] && echo terminal || echo error)"
截至目前,通知只有两个项目:
– 取决于“上一个”命令成功的terminal
或error
图标
– 命令本身(第一种情况是ls
,第二种情况是asdfgh
)
我可以修改现有的别名,在命令上方包含一行文字,如下所示:
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "Task finished" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
然后,如果我运行ls; alert
ls; alert
和asdfgh; alert
asdfgh; alert
我收到如下所示的通知。
我的问题是:两个通知都显示“任务已完成”但是可以使用相同的逻辑来决定是否再次应用 terminal
图标或error
图标以确定在命令上方显示哪个文本字符串? 因此,如果显示terminal
图标,则文本将为“任务已完成”,但如果显示error
图标,则文本可能类似“出错了!”
文艺青年最爱的
用这个:
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && (echo terminal; exit 0) || (echo error; exit 1))" "$([ $? = 0 ] && echo Task finished || echo Something went wrong!)" "$(history | sed -n "\$s/^\s*[0-9]\+\s*\(.*\)[;&|]\s*alert\$/\1/p")"'
简单评估$?
再次不会起作用,因为到了时间$?
将在第二次包含第一个命令代码( $([ $? = 0 ] && echo terminal || echo error)
的退出状态时进行评估(总是0
因为两个echo
总是会成功)。 解决这个问题的一个技巧是使第一个命令替换退出再次具有等效的退出状态:
$([ $? = 0 ] && (echo terminal; exit 0) || (echo error; exit 1))
这样$?
可以第二次评估,以决定打印哪个字符串:
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && (echo terminal; exit 0) || (echo error; exit 1))" "$([ $? = 0 ] && echo Task finished || echo Something went wrong!)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]+\s*//;s/[;&|]\s*alert$//'\'')"'
另请注意您的history|tail -n1|sed -e '\''s/^\s*[0-9]+\s*//;s/[;&|]\s*alert$//'\''
有点过于曲解。 这将更具可读性:
history | sed -n "\$s/^\s*[0-9]\+\s*\(.*\)[;&|]\s*alert\$/\1/p"
所以,最后的命令:
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && (echo terminal; exit 0) || (echo error; exit 1))" "$([ $? = 0 ] && echo Task finished || echo Something went wrong!)" "$(history | sed -n "\$s/^\s*[0-9]\+\s*\(.*\)[;&|]\s*alert\$/\1/p")"'
你可以通过运行测试(exit 0); alert
(exit 0); alert
和(exit 1); alert
(exit 1); alert
。