-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloop.sh
executable file
·52 lines (44 loc) · 920 Bytes
/
loop.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env bash
array=(9 8 7)
size=${#array[@]}
# While loop.
j=0
while [ $j -lt "${size}" ]; do
printf "%s " "${array[j]}" # Prints 9 8 7
((j++))
done
echo
# Until loop.
j=0
until [ $j -eq "${size}" ]; do
printf "%s " "${array[j]}" # Prints 9 8 7
((j++))
done
echo
# For loop.
for ((i = 0; i < size; i++)); do
printf "%s " "${array[i]}" # Prints 9 8 7
done
echo
# For loop with range.
# The values in the range must be literal. {0..$size-1} won't work.
for i in {0..2}; do
printf "%s " "${array[i]}" # Prints 9 8 7
done
echo
# For-in loop.
for n in "${array[@]}"; do
printf "%s " "${n}" # Prints 9 8 7
done
echo
# TIP: Assign an array to for-in.
# Don't use comma, just separate the values with a space.
for char in h e l l o; do
printf "%s " "${char}" # Prints h e l l o
done
echo
# TIP: Iterate over files in a directory.
j=1
for file in /var/log/*.log; do
echo "$((j++)): ${file}"
done