Search code examples
bashparameter-expansion

Prevent variable expansion in the parameter of a function


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"

Is it possible to prevent expansion of the variable ($i in this case) in the parameter itself?


Solution

  • Not sure if this what you want, but here it goes:

    #!/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'
    

    Output:

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