10 Bash for Loop In One Line Examples

Bash For loop is used to execute a series of commands until a particular condition becomes false. Bash for loop one line is very handy for Linux admins. Here are 10 examples of bash for loop in one line.


The syntax of bash for loop in one line is below:

for i in (list); do command1; command2; done

Bash for Loop In one Line with items

# for i in 1 2 3 4 5 ; do echo "$i" ; done
# for i in {1..5} ; do echo "$i" ; done
# for i in {1..5..1};do echo "$i" ; done
# for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus;   do  echo $planet; done


Bash for loop C style In One Line with items

# for ((i=1;i<=5;i++));do echo $i;done

Bash For Loop In one line with Command Output

# for i in `seq 1 5`;do echo $i ;done
# for i in `cat test`;do dig $i +short ;done
# for i in `awk '{print $1}' test` ;do ping -c 2 $i ;done

Bash For Loop In one Line with variables

# for i in $(cat test);do dig $i +short ;done
# a="a b c"
# for i in $a;do echo $i;done
a
b
c
# a=(a b c)
# for i in ${a[@]};do echo $i;done
a
b
c
# for i in $(seq 1 5);do echo $i ;done


Bash For Infinite Loop In one Line

# for (( ; ; )); do echo "Hello World!"; done
# while true; do echo "Hello World!"; done
# while :; do echo "Hello World!"; done

Bash For Loop In One Line with Files

# for i in *; do echo "Found the following file: $i"; done
# for i in `cat filelist.txt`; do echo ${i}; done;
if a line may include spaces better use a while loop:
# cat filelist.txt | while read LINE; do echo "${LINE}"; done

Related:

Bash For Loop Examples In Linux



123 views

Join our newsletter. Get a free Linux account on Cloud.

Get a Free Cloud Server! 

We can use this cloud server to practice Linux commands. Never miss a post!

Thanks for submitting!