Similar to other programming languages, Shell supports for loops.
The general format of a for loop is:
The in list is optional, and without it, the for loop uses the command-line positional arguments.
For example, to sequentially output the numbers in the current list:
The general format of a for loop is:
for variable in list do command1 command2 ... commandN doneA list is a sequence of values (numbers, strings, etc.), each value separated by a space. Each time through the loop, assign the next value in the list to the variable.
The in list is optional, and without it, the for loop uses the command-line positional arguments.
For example, to sequentially output the numbers in the current list:
for loop in 1 2 3 4 5 do echo "The value is: $loop" doneoperation result:
The value is: 1 The value is: 2 The value is: 3 The value is: 4 The value is: 5Sequentially output characters in a string:
for str in 'This is a string' do echo $str doneoperation result:
This is a stringDisplay files in the home directory starting with .bash:
#!/bin/bash for FILE in $HOME/.bash* do echo $FILE doneoperation result:
/root/.bash_history /root/.bash_logout /root/.bash_profile /root/.bashrc