實際案例
1.判斷接收參數個數大於1
[ $# -lt 1 ] && echo "至少需要一個參數" && { echo "我要退出了.... "; exit; } || echo "搞到參數"
2.統計文件夾 和 文件數
let etcd=`ls -l /etc| grep "^d"|wc -l`
let etcf=`ls -l /etc| grep "^-"|wc -l`
let sum=$[$etcd+$etcf]
3.取某列的最大值
number=`df | grep '^/dev' | tr -s " " " "|cut -d" " -f5|tr -s "%" " "|sort -n|tail -n1`
4.短路條件判斷
[ $# -ne 2 ] && echo "need two args" && exit
5.統計文件的空白行
let b=`grep '^$' $2|wc -l`
6.ping通遠程主機
ping -c2 $1 &> /dev/null
[ $? -eq 0 ] && echo "$1 可以被ping通" || echo "$1 不可以被ping通"
7.一次性刪除大批量文件
ls |xargs rm -rf 當刪除的文件數量過多,超過了所支持的參數數量上限時,可配合管道及xargs來刪除。
8.刪除文件中不連續的重復行
當file中的重復行不再一起的時候,uniq沒法刪除所有的重復行。經過排序后,所有相同的行都在相鄰,因此unqi可以正常刪除重復行。
9.分組倒序排序列表
cat access_log | cut -d" " -f1|sort|uniq -c|sort -nr|head -n10
10.把多條命令當成一條命令集合來執行
id $1 &> /dev/null && echo "$1 user has added" || { useradd $1; echo "add user $1 success"; }
11.查看文件夾和文件的大小 du -sh
[root@centos7 ~]# du -sh appserver/ appserver是目錄
5.0M appserver/
[root@centos7 ~]# du -sh f1 f1是文件
4.0K f1
12.查看端口占用情況
1、lsof -i:端口號 用於查看某一端口的占用情況,比如查看8000端口使用情況,lsof -i:8000
可以看到8000端口已經被輕量級文件系統轉發服務lwfs占用
2、netstat -tunlp |grep 端口號,用於查看指定的端口號的進程情況,如查看8000端口的情況,netstat -tunlp |grep 8000
shell編程知識點
1.(cmd1;exit;) 和 {cmd2;exit;}的區別
()會開啟一個子線程,exit退出的是子進程,對執行線程沒有影響
{ }不會開啟子線程,exit退出的是執行進程本身.
2.source .bashrc和bash .bashrc的區別
source 表示.bashrc在當前shell進程中運行
bash 會開啟一個子shell進程來執行當前shell 腳本
3.字符串匹配
[ "$var"="ha" ] 精確判斷$var字符串是否等於ha
[[ "$var" ~="regx" ]]
[ x"$var"="x" ] 判斷$var字符串是否為空
4.變量格式的保留
echo $name 把所有的行壓縮成了一行,不保留文件內容換行格式.
echo "$name" 添加雙引號保留原文件內容的換行格式.
5.bash調試方式
1.檢查語法錯誤 bash -n test.sh
2.跟蹤調試執行腳本 bash -x test.sh
6.bash的配置文件
1.全局配置
1./etc/profile
2./etc/profile.d/*.sh
3./etc/bashrc
2.個人配置
1.~/.bash_profile
2.~/.bashrc
7.shell和其它語言的不同之處
shell把空字符串和1相加運算會得到1,並不會提示錯誤.其它語言空類型是不能和整數進行運算的

[root@centos7 ~]# a="" [root@centos7 ~]# b=a+1 [root@centos7 ~]# echo b b [root@centos7 ~]# echo $b a+1 [root@centos7 ~]# let b=a+1 [root@centos7 ~]# echo $b 1