Anuj Kaushal

How to use “for” loop in one liner bash command

February 21, 2021, by anuj, category Bash, Blog, Command

There is always a need to running a command in the loop and it can be very useful if you don’t have to write a separate bash script to run command in loop.
So here are some different ways to run loop in one liner command.

# simple for loop command in sequence
anuj@anujtuf2:/Work/practice/findcmd$ for var in {110..114}; do echo "$var" + `date`; done;
110 + Sunday 21 February 2021 11:45:11 AM IST
111 + Sunday 21 February 2021 11:45:11 AM IST
112 + Sunday 21 February 2021 11:45:11 AM IST
113 + Sunday 21 February 2021 11:45:11 AM IST
114 + Sunday 21 February 2021 11:45:11 AM IST
# take input from file to loop
anuj@anujtuf2:/Work/practice/findcmd$ cat input.txt 
apple
orange
papaya
kiwi
mango
anuj@anujtuf2:/Work/practice/findcmd$ for var in $(cat input.txt); do echo "$var" + `date`; done;
apple + Sunday 21 February 2021 11:47:24 AM IST
orange + Sunday 21 February 2021 11:47:24 AM IST
papaya + Sunday 21 February 2021 11:47:24 AM IST
kiwi + Sunday 21 February 2021 11:47:24 AM IST
mango + Sunday 21 February 2021 11:47:24 AM IST

Its very useful when you have to delete specific deployment or run a command based on the parameter available in the file.

Another thing, recently i was trying to run for loop in a alpine container and it required some tweaking.

for var in `seq 1 20`; 
do
  echo "Counter $var";
done;