Similar to other programming languages, the shell supports A for loop.
The general format for A for loop is:
For variable in list do Command1 command2 ... Commandndone
A list is a sequence of values (numbers, strings, and so on), each separated by a space. Each time the loop is passed, the next value in the list is assigned to the variable.
The in list is optional, if it is not used, the For loop uses the command-line positional parameters.
For example, sequentially output the numbers in the current list:
- For Loop in 1 2 3 4 5
- Do
- Echo "The value is: $loop"
- Done
Operation Result:
The value is:1the value is:2the value is:3the value is:4the value is:5
Characters in the sequential output string:
- For str ' A string '
- Do
- echo $str
- Done
Operation Result:
This is a string
Show files starting with. Bash in the home directory:
- #!/bin/bash
- For FILE in $HOME/.bash*
- Do
- echo $FILE
- Done
Operation Result:
/root/.bash_history/root/.bash_logout/root/.bash_profile/root/.bashrc
Shell for Loop