HowTo: Use bash For Loop In One Line

How do I use bash for loop in one line under UNIX or Linux operating systems?

The syntax is as follows to run for loop from the command prompt.

ADVERTISEMENTS

Run Command 5 Times

for i in {1..5}; do COMMAND-HERE; done

OR

 for((i=1;i<=10;i+=2)); do echo "Welcome $i times"; done

Work On Files

for i in *; do echo $i; done

OR

for i in /etc/*.conf; do cp $i /backup; done
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
Network Utilitiesdig host ip nmap
Package Managerapk apt
Processes Managementbg chroot disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w

ADVERTISEMENTS
10 comments… add one
  • Kingpin Mar 21, 2013 @ 12:13

    OK, but how do I run two commands in the for loop? for () command1; command; done
    ???

    • Anne Aug 22, 2013 @ 17:00

      two commands:
      for i in (); do echo $i ; ls $i; done

      nested for:

      for i in {0..3}; do for j in {0..9}; do echo -n \($i, $j\); echo Is today the $i$j \?; done; done

  • roger Sep 25, 2013 @ 17:50

    I’d suggest you add an example of this to https://www.cyberciti.biz/faq/bash-for-loop/ also that would have helped me…maybe with a ToC at the top as well :)

  • w Feb 13, 2014 @ 10:49

    Thanks for this.

  • ronator Oct 14, 2014 @ 14:41

    For the very rare case yout got file names with a leading dash:

    for i in *; do echo $i; done [ will not show files with leading dash ]

    for i in “*”; do echo $i; done [ will show files with leading dash (but not one file per line) ]

  • Anne Feb 13, 2015 @ 23:08

    Love it! Thanks!

  • Jakob Jun 8, 2016 @ 10:10

    Work on Folders:

    for i in */; do (cd “$i” && git fetch) done

  • Jimy Jul 21, 2016 @ 4:35

    Thanks for this!
    It saved me hours of banging my head on the table

  • Mora Oct 1, 2016 @ 11:45

    thanks

  • Rakesh Oct 4, 2016 @ 19:15

    Hi, I’m new in bash, please help me somebody. ..
    I have one folder in linux server and in folder has some *.sql file, so I want to execute all the sql in my mysql sequencely one by one. We also want output on my display as well as in log file for every files execution error. Ex. /root/desktop/sql/1_ff_f_update. And 2_*, 3_* so on. Count of the file was change every time so we can not tell u of count of the files….

    If possible help me..
    Thanks in advance. .

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.