LinuxCommandLine -- [脚本 - 循环]

while

  • continue
  • break

语法

while [ condition ]; do
    commands
done

例子

# timer.sh 倒计时
#-----------------
#!/bin/bash

read -p "Enter an integer: " num


while (( num >= 0 )); do
    clear
    echo "Counter: $num"
    num=$((num - 1))
    sleep 1
done

clear

until

语法

until [ condition ]; do
    commands
done

例子

#!/bin/bash

read -p "Enter an integer: " num

until (( num < 0 )); do
    clear
    echo "Timer: $num"
    num=$((num - 1))
    sleep 1
done

clear

循环和重定向

重定向 stdin

$ cat data.txt
0 0
2 6
1 5
5 1
4 9
2 5
2 9
3 8
6 3
6 1

$ ./multi.sh
0 x 0 = 0
2 x 6 = 12
1 x 5 = 5
5 x 1 = 5
4 x 9 = 36
2 x 5 = 10
2 x 9 = 18
3 x 8 = 24
6 x 3 = 18
6 x 1 = 6

#multi.sh
#-------------
#!/bin/bash

while read num1 num2; do
    printf "$num1 x $num2 = %s\n" $(($num1 * $num2))
done < data.txt

管道

$ ./file_size.sh
Path: .
total 1.8M

admin.txt                  4.0K
counter.sh                 4.0K
data.txt                   4.0K
django_projects.tar.gz     1.7M
file_size.sh               4.0K
multi.sh                   4.0K
nginx.tar.gz               8.0K
ta_1.txt                   4.0K
task_1.txt                 4.0K
task_2.txt                 4.0K
test                       0
until_counter.sh           4.0K

#!/bin/bash

read -p "Path: " path

ls -sh $path | while read size filename; do
    if [[ $size =~ total ]]; then
        printf "$size $filename\n\n"
        continue
    fi

    printf "%-26s %s\n" $filename $size
done

for

第一种格式

$ for i in $(seq 5); do echo $i; done
1
2
3
4
5

$ for i in {1..5}; do echo $i; done
1
2
3
4
5

第二种格式

$ for ((i=1; i <=5 ; i++)); do echo $i; done
1
2
3
4
5

如果没有文件匹配,会直接显示通配符

$ ls
file_a  file_b  file_c

$ for file in file_*; do echo $file; done
file_a
file_b
file_c

# 如果没有文件匹配,会直接显示通配符
$ for file in dir_*; do echo $file; done
dir_*

# 加一个 if 检查
for file in dir_*; do
  if [ -e "$file" ]; then
    echo $file
  fi
done

打印文件最长的行

$ cat  ./longest-line.sh
#!/bin/bash

read -e -p "File: " file

if [ -e "$file" ]; then
    longest_line=""
    size=0

    while read line; do
       line_size=$(echo "$line" | wc -c)
        if ((line_size > size)); then
            longest_line="$line"
            size="$line_size"
        fi
    done < $file


    printf "longest line: %s\n" "$longest_line"
    printf "size: %s charater(s)\n" "$size"
else
    echo "ERROR: No sush file - $file" >&2
    exit 1
fi

你可能感兴趣的:(LinuxCommandLine -- [脚本 - 循环])