20.5 shell腳本中的邏輯判斷 20.6 文件目錄屬性判斷 20.7 if特殊用法 20.8/

20.5 shell腳本中的邏輯判斷
當腳本中使用某個字符串較頻繁而且字符串長度很長時就應該使用變量代替
使用條件語句時,常使用變量    if [ $a -gt 1 ]; then ... ; fi
引用某個命令的結果時,用變量替代   n=wc -l 1.txt
寫和用戶交互的腳本時,變量也是必不可少的  read -p "Input a number: " n; echo $n   若是沒寫這個n,能夠直接使用$REPLY
內置變量 $0, $1, $2…    $0表示腳本自己,$1 第一個參數,$2 第二個 ....       $#表示參數個數
數學運算a=1;b=2; c=$(($a+$b))或者$[$a+$b]
20.5 shell腳本中的邏輯判斷 20.6 文件目錄屬性判斷 20.7 if特殊用法 20.8/
格式1:if 條件 ; then 語句; fi
格式2:if 條件; then 語句; else 語句; fi
格式3:if …; then … ;elif …; then …; else …; fi
邏輯判斷表達式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等 -gt (>); -lt(<); -ge(>=); -le(<=);-eq(==); -ne(!=) 注意處處都是空格
可使用 && || 結合多個條件
if [ $a -gt 5 ] && [ $a -lt 10 ]; then
if [ $b -gt 5 ] || [ $b -lt 3 ]; thenshell

20.6 文件目錄屬性判斷vim

20.5 shell腳本中的邏輯判斷 20.6 文件目錄屬性判斷 20.7 if特殊用法 20.8/

[ -f file ]判斷是不是普通文件,且存在
[ -d file ] 判斷是不是目錄,且存在
[ -e file ] 判斷文件或目錄是否存在
[ -r file ] 判斷文件是否可讀
[ -w file ] 判斷文件是否可寫
[ -x file ] 判斷文件是否可執行bash

20.7 if特殊用法
20.5 shell腳本中的邏輯判斷 20.6 文件目錄屬性判斷 20.7 if特殊用法 20.8/
if [ -z "$a" ]  這個表示當變量a的值爲空時會怎麼樣
if [ -n "$a" ] 表示當變量a的值不爲空
if grep -q '123' 1.txt; then  表示若是1.txt中含有'123'的行時會怎麼樣
if [ ! -e file ]; then 表示文件不存在時會怎麼樣
if (($a<1)); then …等同於 if [ $a -lt 1 ]; then…
[ ] 中不能使用<,>,==,!=,>=,<=這樣的符號ide

20.8/20.9 case判斷 測試

vim test.sh 腳本以下:
#!/bin/bash
read -p "Please input a number :" n
if [ -z $n ]
then
echo "please input a number:"
exit 1
fi
m=echo $n|sed 's/[0-9]//g'
if [ ! -z $m ]
then
echo "Please input a number:"
exit 1
#elif [ $n -lt 0 ] || [ $n -gt 100 ]
#thencode

echo "The number ranger is 0-100."

#exit 1
fi
if [ $n -lt 60 ] && [ $n -ge 0 ]
then
tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
then
tag=2
elif [ $n -ge 80 ] && [ $n -lt 90 ]
then
tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
then
tag=4
else
tag=0
fi
case $tag in
1)
echo "not ok"
;;
2)
echo "ok"
;;
3)
echo "good"
;;
4)
echo "very good"
;;
*)
echo "The numbet range 0-100."
;;blog

測試以下:
20.5 shell腳本中的邏輯判斷 20.6 文件目錄屬性判斷 20.7 if特殊用法 20.8/
20.5 shell腳本中的邏輯判斷 20.6 文件目錄屬性判斷 20.7 if特殊用法 20.8/字符串

20.5 shell腳本中的邏輯判斷 20.6 文件目錄屬性判斷 20.7 if特殊用法 20.8/

相關文章
相關標籤/搜索