Shell for Loop
The general format for A for loop is:
For variable in list
Do
Command1
Command2
...
CommandN
Done
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.
1. 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:1
The value Is:2
The value Is:3
The value Is:4
The value Is:5
2. The characters in the sequential output string:
For str ' A string '
Do
Echo $str
Done
Operation Result:
This is a string
3. display 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
4. Show all directories under/usr directory
#!/bin/bash
dir=$ (ls-l/usr/|awk '/^d/{print $NF} ')
For I in $dir
Do
Echo $i
Done
Run results
Bin
etc
Games
Include
Lib
Lib64
Libexec
Local
Sbin
Share
Src
Shell for Loop