【shell语法 | 01】基础练习

利用判断符号[ ]

  • [ str ] : str 字符串存在为真
 1 [root@localhost ~]# if [  ]; then echo 'true';else echo 'false';fi  
 2 false
 3 [root@localhost ~]# 
 4 [root@localhost ~]# if [ 123 ]; then echo 'true';else echo 'false';fi
 5 true
 6 [root@localhost ~]# if [  ]; then echo 'true';else echo 'false';fi 
 7 false
 8 [root@localhost ~]# 
 9 [root@localhost ~]# if [ '123' ]; then echo 'true';else echo 'false';fi 
10 true
11 [root@localhost ~]# 
12 [root@localhost ~]# if [[ '123' ]]; then echo 'true';else echo 'false';fi 
13 true
14 [root@localhost ~]# 
15 [root@localhost ~]# if [[ '' ]]; then echo 'true';else echo 'false';fi 
16 false
  • -n : nozero 字符串长度不为0时为真
  • -z: zero 字符串长度为0时为真
 1 [root@localhost ~]# a=123
 2 [root@localhost ~]# 
 3 [root@localhost ~]# if [[ -n $a ]]; then echo 'true';else echo 'false';fi 
 4 true
 5 [root@localhost ~]# 
 6 [root@localhost ~]# if [ -n $a ]; then echo 'true';else echo 'false';fi 
 7 true
 8 [root@localhost ~]# 
 9 [root@localhost ~]# if [ -z $a ]; then echo 'true';else echo 'false';fi 
10 false
11 [root@localhost ~]# a=
12 [root@localhost ~]# 
13 [root@localhost ~]# if [ -z $a ]; then echo 'true';else echo 'false';fi 
14 true
15 [root@localhost ~]# if [ -n $a ]; then echo 'true';else echo 'false';fi 
16 true
17 [root@localhost ~]# 
18 [root@localhost ~]# if [ -n "$a" ]; then echo 'true';else echo 'false';fi 
19 false

循环体

1. for...do...done(固定循环)

for var in list
do 
  commands
done

1. 示例1

#!/bin/bash
for animal in dog cat elephant
do
    echo "There are ${animal}s.."
done
1 #!/bin/bash
2 for animal in dog cat elephant
3 do
4     echo "There are ${animal}s.."
5 done
1 #!/bin/bash
2 for((i = 0; i < 5; ++i))
3 do
4     echo "this is test!"
5 done

产生十个随机数字

方法1:

#!/bin/bash

for i in $(seq 10);
do
    echo "$i: $RANDOM";
done
View Code

方法2:

 1 #!/bin/bash
  2 for((i = 0; i < 5; ++i))
  3 do
  4     echo "this is test!"
  5 done     
原文地址:https://www.cnblogs.com/sunbines/p/14587095.html