Iterate similar command over multiple items

11/12/2021

If I'm trying to do a command like kubectl apply -f dir1/subdir1/deployment.yml, and I have subdir1, subdir2, etc, how can I run that command for all of them at once?

I tried kubectl apply -f dir1/*/deployment.yml and that passes all the deployment.yml to the single -f flag, making it invalid as that flag accepts a single argument.

I've also tried kubectl apply -f dir1/{subdir1,subdir2}/deployment.yml with no luck.

PS: I'm using zsh for my shell with oh-my-zsh+p10k if that matters.

-- cclloyd
kubectl
kubernetes
shell

2 Answers

11/12/2021

A command-agnostic solution in zsh:

for d (dir1/*/deployment.yml) kubectl apply -f "$d"

This uses a zsh-specific alternate form of the for loop, more commonly written as

for d in dir1/*/deployment.yml; do kubectl apply -f "$d"; done

(Though this is admittedly different from running kubectl precisely once and letting it iterate over the configurations itself.)

-- chepner
Source: StackOverflow

11/14/2021

To include subdirectories use the parameter -R, like

kubectl apply -R -f /path/to/dir

Where -R is the parameter used for Processing the directory used in -f recursively

Refer this documentation for more information on kubectl apply command.

-- Goli Nikitha
Source: StackOverflow