gpt4 book ai didi

Bash:如何结合 watch 使用别名命令

转载 作者:行者123 更新时间:2023-11-29 09:38:58 25 4
gpt4 key购买 nike

我想在 bash 中结合 watch 命令使用别名命令。 watch命令是多个链式命令。

一个非常简单的例子,我认为它会如何工作(但它没有):

alias foo=some_command          # a more complicated command
watch -n 1 "$(foo) | grep bar" # foo is not interpreted as the alias :(

最佳答案

watch -n 1 "$(foo) | grep sh" 错误有两个原因。

  1. watch "$(cmdA) | cmdB" 被 shell 执行时,$(cmdA) gets expanded 运行watch之前。然后 watch 将执行 cmdAoutput 作为命令(在大多数情况下应该会失败)并将其输出通过管道传递给 cmdB。你的意思可能是 watch 'cmdA | cmdB'.

  2. 别名 foo 仅在当前 shell 中定义。 watch 不是内置命令,因此必须在不知道别名 foo 的另一个 shell 中执行它的命令。 this answer中介绍了一个小技巧,但是我们必须进行一些调整以使其与管道和选项一起使用

alias foo=some_command
alias watch='watch -n 1 ' # trailing space treats next word as an alias
watch foo '| grep sh'

请注意,watch 的选项必须在 watch 别名中指定。尾随空格导致仅下一个单词被视为别名。使用 watch -n 1 foo bash 会尝试将 -n 扩展为别名,而不是 foo

关于Bash:如何结合 watch 使用别名命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54814543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com