How to use for loop in a command
the basic usage for 'for' loops in bash is to use them in a script like
for i in 1 2 3 4 5 6...N
do
some deeds
...
done
But there is another thing you can do with it, which I think makes everything much easier to do in linux.
Lets assume you have something repetitive to do.
You have 19 git repositories to add the same, commit and push.
One way it can be done is with getting into each repo and do
cd dir_name
git add file_name
git commit -m "some commit message"
git push
If you have to do it 19 times (or more) its very much exahusting.
There is a solution for that, with one command only.
Create a directory and clone all 19 repos into it
mkdir reposdir and then
git clone $repos_name
Then there is only one command you can do (you can also use it in the clone process):
for d in $(ls); do cd $d; git add file_name; git commit -m "adding the file"; git push; cd ../;done
Now with one command you did everything!
for d in $(ls) - Like when you use it in scripts, you can use the $() operator to take the output of a command and go over it with for loop. In this case, You go over the content of the current directory, which is the directory where all the cloned repos are.
do cd $d - Get into the directory that the loop is currently on, in this case, one of the directories in the current durectories (=one of the projects)
git add add $file_names
git commit -m "$message" - add files to the working directory and commit them.
git push - push to the remote repository
cd ../ - Very important part! You have to go back one directory for the next iteration to go to the next directory - that's the only way this command can work. Otherwise you will stay in the directory and won't be able to find the next project.
done - This is how a loop ends.
Summary
You can use this method in a lot of placements where you need a little loop, or for any reptitive task, that you can print the variables of it to the screen. Just put it in the output of the command inside $() and do whatever you want with it.
Examples
Doing things on specific pods:
for s in $(kubectl get pods | awk '{print $1}' | egrep "pod1|pod2...");do echo $s:; kubectl logs $s;echo;done
Check if a file exists in an archive file:
for f in $(tar -tvf mytar.tar.gz | awk '{print $6}' | awk -F'/' '{print $NF}'); do echo $f:;if [ ! -z $(ls ../directory/ | grep $f) ];then echo exits;else echo DONT EXIST;fi;done')
Give variable to the for loop and do something with it. In this case, give a string of pods names that you want to do something on:
read -p "pods:" pods;pods=$(echo ${pods} | sed 's/ /|/g') && read -p "command:" command && for s in $(kubectl get pods | awk -v awkvar="$pods" '$1 ~ awkvar {print $1}');do kubectl $command pod $s;echo;done