【问题标题】:Prevent variable expansion in the parameter of a function防止函数参数中的变量扩展
【发布时间】:2021-06-26 05:19:00
【问题描述】:
function kubeall { 
    for i in `seq 0 2`; do 
        echo pod-$i
        kubectl exec -it pod-$i -- bash -c "$@"
    done 
}
kubeall "cat ~/logs/pod-$i/log.out"

是否可以防止参数本身中的变量(在这种情况下为$i)的扩展?

【问题讨论】:

    标签: bash parameter-expansion


    【解决方案1】:

    按原样将$i 传递给kubeall 无济于事。您应该将 $i 作为位置参数传递给 bash。

    function kubeall {
      for i in {0..2}; do
        echo "pod-$i"
        kubectl exec -it "pod-$i" -- bash -c "$1" bash "$i"
      done
    }
    
    kubeall 'cat ~/"logs/pod-$1/log.out"'
    

    【讨论】:

    • 完美运行。对使用 kubectl 的未来观众的小评论,在 kubectl exec -it "pod-$i" -- bash -c "$1" bash "$i" 中使用 --,否则 -c 将被 kubectl 视为标志。虽然我个人更喜欢@Darkman 的解决方案,因为它更灵活。谢谢你。
    【解决方案2】:

    不确定这是不是你想要的,但它就是这样:

    #!/bin/bash
    function kubeall {
        echo '$@: '"$@"
        for i in $(seq 0 0); do
            echo pod-$i
            #Note :: Include $i to the new shell.
            bash -c "i=$i; $@"
        done
    }
    
    #Note :: Using single quotes here to send the arguments as it is.
    kubeall 'echo ~/pod-$i/log.out'
    

    输出:

    $@: echo ~/pod-$i/log.out
    pod-0
    /home/username/pod-0/log.out
    

    【讨论】:

      猜你喜欢
      • 2019-07-07
      • 2020-09-13
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多