【问题标题】:Better Method to Store Aliases?存储别名的更好方法?
【发布时间】:2019-12-17 12:47:25
【问题描述】:

我在~/.bash_profile 中添加了一个别名列表

现在加载一个新的终端窗口需要大约 10 秒的时间。

有没有更好的方式或位置来存储日常使用的别名?

以下是我常用的一些示例:

alias sshcol="kubectl exec -ti $(kubectl get pod --selector=app=collector --field-selector=status.phase=Running -n etl -o jsonpath={.items[0].metadata.name}) -n etl -c collector /bin/bash"

alias logscol="kubectl logs --tail=50 $(kubectl get pod --selector=app=collector --field-selector=status.phase=Running -n etl -o jsonpath={.items[0].metadata.name}) -n etl -c collector"

【问题讨论】:

  • $(kubectl get pod - 因为你每次都运行这个命令。
  • 由于您在定义别名时运行kubectl get pod,而不是在使用时运行它,因此您可能可以运行一次并重新- 使用每个定义中的值。
  • 如果这实际上是一个错误并且您确实需要在每次使用别名时运行kubctl get pod,您需要转义$ 或使用单引号。无论哪种方式,别名定义都会加快。

标签: bash macos terminal alias


【解决方案1】:

$(kubectl get pod - 这是因为每次获取 bash_profile 时,您都会在 $(...) 中运行命令。你可以使用一个函数。

sshcol() {
    kubectl exec -ti "$(kubectl get pod --selector=app=collector --field-selector=status.phase=Running -n etl -o jsonpath="{.items[0].metadata.name}")" -n etl -c collector /bin/bash
}

【讨论】:

    【解决方案2】:

    您似乎在不必要地重新运行kubectl get pod。例如,

    # Run this once and save the result
    pod=$(kubectl get pod --selector=app=collector --field-selector=status.phase=Running -n etl -o jsonpath={.items[0].metadata.name})
    
    alias sshcol="kubectl exec -ti \"$pod\" -n etl -c collector /bin/bash"
    alias logscol="kubectl logs --tail=50 \"$pod\" -n etl -c collector"
    

    您可能希望使用函数来代替别名。

    但是,如果 kubectl get pod 在定义时运行是一个错误,并且在您使用别名时确实需要运行,您应该明确定义一个函数,如 Kamil Cuk's answer .

    【讨论】:

    • 你不能单引号整个事情,它只在使用别名时才被评估?
    • 你可以,但是 1) 我已经怀疑重复调用是不必要的,并且 2) 在那一点上,我更喜欢函数定义。我在对问题的原始评论中提到了单引号。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2012-01-30
    • 1970-01-01
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多