sh -x 显示脚本执行过程

[root@localhost ~]# cat 2.sh

#!/bin/bash

echo "hello"

[root@localhost ~]# sh -x 2.sh

+ echo hello

hello


数学运算

[root@localhost ~]# cat 1.sh

#!/bin/bash

a=1

b=2

c=$[$a+$b]

echo $c

[root@localhost ~]# sh 1.sh

3


逻辑判断if

[root@localhost ~]# cat 3.sh

#!/bin/bash

# 用户输入一个数字

read -t 5 -p "Please input a number:" number

# 判断用户输入是否大于5

if [ $number -gt 5 ]

then

# 如果判断为真,输出

echo "number > 5"

fi

# 逻辑判断符号

# 数学表示  shell表示

#  > -gt

#  < -lt

#  == -eq

#  != -ne

#  >= -ge

#  <= -le


逻辑判断if...else...

[root@localhost ~]# cat 3.sh

#!/bin/bash

read -t 5 -p "Please input a number:" number

if [ $number -gt 5 ]

then

echo "number > 5"

else

echo "number < 5"

fi


逻辑判断if...elif...else...

[root@localhost ~]# cat 3.sh

#!/bin/bash

read -t 5 -p "Please input a number:" number

if [ $number -gt 5 ]

then

echo "number > 5"

elif [ $number -lt 5 ]

then

echo "number < 5"

else

echo "number = 5"

fi


if判断的几种用法

用法一:判断/tmp/目录是否存在,如果存在,屏幕输出OK,-d是目标类型,也可以是其他类型,如-f,-s等,详见linux文件类型。第一个是以脚本的形式执行,第二个是以命令行的形式执行

[root@localhost ~]# cat 1.sh

#!/bin/bash

if [ -d /tmp/ ]

then

echo OK;

fi

[root@localhost ~]# bash 1.sh

OK

[root@localhost ~]# if [ -d /tmp/ ]; then echo OK; fi

OK

用法二、判断目标权限

[root@localhost test]# ll

总用量 4

-rw-r--r-- 1 root root 45 12月  9 19:32 1.sh

[root@localhost test]# if [ -r 1.sh ]; then echo OK; fi

OK

用法三、判断用户输入是否为数字

[root@localhost test]# cat 2.sh

#!/bin/bash

read -t 5 -p "Please input a number: " n

m=`echo $n | sed 's/[0-9]//g'`

if [ -n "$m" ]

then

echo "The character you input is not a number, Please retry."

else

echo $n

fi

用法四、判断用户输入是否为数字

[root@localhost test]# cat 2.sh

#!/bin/bash

read -t 5 -p "Please input a number: " n

m=`echo $n | sed 's/[0-9]//g'`

if [ -z "$m" ]

then

echo $n

else

echo "The character you input is not a number, Please retry."

fi

用法五、判断指定字符串是否存在

[root@localhost test]# cat 3.sh

#!/bin/bash

if grep -q '^root:' /etc/passwd

then

echo "root exist."

else

echo "root not exist."

fi

[root@localhost test]# sh 3.sh

root exist.

用法六、多重判断

[root@localhost test]# ll

总用量 16

-rw-r--r-- 1 root root  45 12月  9 19:32 1.sh

-rw-r--r-- 1 root root 182 12月  9 19:45 2.sh

-rw-r--r-- 1 root root  99 12月  9 19:56 3.sh

-rw-r--r-- 1 root root  79 12月  9 19:59 4.sh

[root@localhost test]# cat 4.sh

#!/bin/bash

# && 逻辑与  ||  逻辑或

if [ -d /tmp/ ] && [ -f 1.txt ]

then

echo OK

else

echo "not OK"

fi

[root@localhost test]# bash 4.sh

not OK

用法七、多重判断

[root@localhost test]# ll

总用量 16

-rw-r--r-- 1 root root  45 12月  9 19:32 1.sh

-rw-r--r-- 1 root root 182 12月  9 19:45 2.sh

-rw-r--r-- 1 root root  99 12月  9 19:56 3.sh

-rw-r--r-- 1 root root  79 12月  9 19:59 4.sh

[root@localhost test]# cat 4.sh

#!/bin/bash

# -a 逻辑与  -o  逻辑或

if [ -d /tmp/ -o -f 1.txt ]then

echo OK

else

echo "not OK"

fi

[root@localhost test]# bash 4.sh

not OK