10 Bash for Loop In One Line Examples

Table of Contents

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 in Linux

Bash is a default shell now. It is very convenient. For example, they remember commands that we have typed and let us reuse those commands.

It also let us edit those commands, so they don’t have to be the same each time. And bash let us define our own command abbreviations, shortcuts, and other features.

Bash is programmable. We can write a bash script to handle our daily work. Whenever we find ourselves doing a task repeatedly, we should try to automate it by writing a shell script.

There are more powerful scripting languages, like Perl, Python, and Ruby, but the Linux shell bash is a great place to start. After all, we already know how to type commands.

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;
  • # cat filelist.txt | while read LINE; do echo “${LINE}”; done

if a line may include spaces better use a while loop.

Related:

Bash For Loop Examples In Linux

Linux Troubleshooting Guide:

Linux Learning Guide:

Table of Contents

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

You might also like