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