sh -x 显示脚本执行过程linux
[root@localhost ~]# cat 2.shshell
#!/bin/bashbash
echo "hello"ide
[root@localhost ~]# sh -x 2.shspa
+ echo hello命令行
hello字符串
数学运算input
[root@localhost ~]# cat 1.sh数学
#!/bin/bashit
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
用法2、判断目标权限
[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
用法3、判断用户输入是否为数字
[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
用法4、判断用户输入是否为数字
[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
用法5、判断指定字符串是否存在
[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.
用法6、多重判断
[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
用法7、多重判断
[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