一. shell基礎(chǔ)案例
1、第一個(gè)案例:helloworld
#!/bin/bash
function example {
echo "Hello world!"
}
example
2、打印運(yùn)行的python進(jìn)程
#!/bin/sh
pidlist=`ps -aux | grep python | awk '{print $2}'`
echo $pidlist
3、獲取并打印參數(shù)
#!/bin/bash
echo "$0 $1 $2 $3" // 傳入三個(gè)參數(shù)
echo $# //獲取傳入?yún)?shù)的數(shù)量
echo $@ //打印獲取傳入?yún)?shù)
echo $* //打印獲取傳入?yún)?shù)
4、用腳本寫for循環(huán)
#!/bin/bash
s=0;
for((i=1;i<100;i++))
do
s=$[$s+$i]
done
echo $s
r=0;
a=0;
b=0;
for((x=1;x<9;x++))
do
a=$[$a+$x]
echo $x
done
for((y=1;y<9;y++))
do
b=$[$b+$y]
echo $y
done
echo $r=$[$a+$b]
5、使用C語言風(fēng)格的for命令
#!/bin/bash
#testing the C-style for loop
for (( i=1; i<=10; i++ ))
do
echo "The next number is $i"
done
6、while循環(huán)案例
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
s=$[$s + $i]
i=$[$i + 1]
done
echo $s
echo $i
7、使用break跳出外部循環(huán)
#!/bin/bash
# break n,默認(rèn)為1
for (( a=1; a<=3; a++ ))
do
echo "Outer loop : $a"
for (( b=1; b < 100; b++ ))
do
if [ $b -gt 4 ]
then
break 2
fi
echo " Inner loop:$b"
done
done
8、使用continue命令
#!/bin/bash
#using the continue command
for (( var1 = 1; var1 < 15; var1++ ))
do
if [ $var1 -gt 5 ] && [ $var1 -lt 10 ]
then
continue
fi
echo "Iteration number:$var1"
done
9、case案例
#!/bin/bash
case $1 in
1)
echo "wenmin "
;;
2)
echo "wenxing "
;;
3)
echo "wemchang "
;;
4)
echo "yijun"
;;
5)
echo "sinian"
;;
6)
echo "sikeng"
;;
7)
echo "yanna"
;;
*)
echo "danlian"
;;
esac
10、判斷兩個(gè)數(shù)是否相等
num1=100
num2=100
if test $[num1] -eq $[num2]
then
echo '兩個(gè)數(shù)相等!'
else
echo '兩個(gè)數(shù)不相等!'
fi
11、使用雙圓括號(hào)
#!/bin/bash
# using double parenthesis
var1=10
if (( $var1 ** 2 > 90))
then
(( var2 = $var1 ** 2))
echo "The square of $var1 if $var2"
fi
12、使用雙方括號(hào)
#!/bin/bash
# using pattern matching
if [[ $USER == r* ]]
then
echo "Hello $USER"
else
echo "Sorry, I do not know you"
fi
13、反引號(hào)的使用
#!/bin/bash
#using the backtick character 會(huì)把反引號(hào)里面當(dāng)作一條命令來執(zhí)行
testing=`date`
echo "The date and time are:$testing"
14、字符串比較
#!/bin/bash
#testing string equality
testuser=tiandi
if [ $USER = $testuser ]
then
echo "Welcome $testuser"
fi
15、讀取列表中的值
#!/bin/bash
# basic for command
for test in Alabama Alaska Arizona
do
echo The next state is $test
done
16、打印99乘法表
#!/bin/bash
for i in `seq 9`
do
for j in `seq $i`
do
echo -n "$j*$i=$[i*j] "
done
echo
done
17、腳本編寫 求和 函數(shù)運(yùn)算 function xx()
#!/bin/bash
function sum()
{
s=0;
s=$[$1+$2]
echo $s
}
read -p "input your parameter " p1
read -p "input your parameter " p2
sum $p1 $p2
function multi()
{
r=0;
r=$[$1/$2]
echo $r
}
read -p "input your parameter " x1
read -p "input your parameter " x2
multi $x1 $x2
v1=1
v2=2
let v3=$v1+$v2
echo $v3
18、用戶猜數(shù)字
#!/bin/bash
# 腳本生成一個(gè) 100 以內(nèi)的隨機(jī)數(shù),提示用戶猜數(shù)字,根據(jù)用戶的輸入,提示用戶猜對了,
# 猜小了或猜大了,直至用戶猜對腳本結(jié)束。
# RANDOM 為系統(tǒng)自帶的系統(tǒng)變量,值為 0‐32767的隨機(jī)數(shù)
# 使用取余算法將隨機(jī)數(shù)變?yōu)?1‐100 的隨機(jī)數(shù)
num=$[RANDOM%100+1]
echo "$num"
# 使用 read 提示用戶猜數(shù)字
# 使用 if 判斷用戶猜數(shù)字的大小關(guān)系:‐eq(等于),‐ne(不等于),‐gt(大于),‐ge(大于等于),
# ‐lt(小于),‐le(小于等于)
while :
do
read -p "計(jì)算機(jī)生成了一個(gè) 1‐100 的隨機(jī)數(shù),你猜: " cai
if [ $cai -eq $num ]
then
echo "恭喜,猜對了"
exit
elif [ $cai -gt $num ]
then
echo "Oops,猜大了"
else
echo "Oops,猜小了"
fi
done
19、編寫剪刀 、 石頭、布游戲
#!/bin/bash
game=(石頭 剪刀 布)
num=$[RANDOM%3]
computer=${game[$sum]}
echo "請根據(jù)下列提示選擇您的出拳手勢"
echo " 1. 石頭"
echo " 2. 剪刀"
echo " 3. 布 "
read -p "請選擇 1-3 :" person
case $person in
1)
if [ $num -eq 0 ]
then
echo "平局"
elif [ $num -eq 1 ]
then
echo "你贏"
else
echo "計(jì)算機(jī)贏"
fi;;
2)
if [ $num -eq 0 ]
then
echo "計(jì)算機(jī)贏"
elif [ $num -eq 1 ]
then
echo "平局"
else
echo "你贏"
fi;;
3)
if [ $num -eq 0 ]
then
echo "你贏"
elif [ $num -eq 1 ]
then
echo "計(jì)算機(jī)贏"
else
echo "平局"
fi;;
*)
echo "必須輸入1-3 的數(shù)字"
esac
20、檢測當(dāng)前用戶是否為管理員
#!/bin/bash
# 檢測本機(jī)當(dāng)前用戶是否為超級(jí)管理員
if [ $USER == "root" ]
then
echo "您是管理員,有權(quán)限安裝軟件"
else
echo "您不是管理員,沒有權(quán)限安裝軟件"
fi
21、接收參數(shù)
傳入?yún)?shù)3運(yùn)行:sh demo.sh 3
,控制臺(tái)會(huì)打?。簑o ai wenxing
#!/bin/bash -xv
if [ $1 -eq 2 ] ;then
echo "wo ai wenmin"
elif [ $1 -eq 3 ] ;then
echo "wo ai wenxing "
elif [ $1 -eq 4 ] ;then
echo "wo de xin "
elif [ $1 -eq 5 ] ;then
echo "wo de ai "
fi
22、讀取控制臺(tái)傳入的參數(shù)
#!/bin/bash
read -t 7 -p "input your name " NAME
echo $NAME
read -t 11 -p "input you age " AGE
echo $AGE
read -t 15 -p "input your friend " FRIEND
echo $FRIEND
read -t 16 -p "input your love " LOVE
echo $LOVE
23、獲取用戶輸入
#!/bin/bash
# testing the reading command
echo -n "Enter your name:"
read name
echo "Hello $name, welcome to my program"
read -p "Please enter your age: " age
days=$[ $age * 365 ]
echo "That makes you over $days days old"
#指定多個(gè)變量,輸入的每個(gè)數(shù)據(jù)值都會(huì)分配給表中的下一個(gè)變量,如果用完了,就全分配各最后一個(gè)變量
read -p "Please enter name:" first last
echo "Checking data for $last. $first..."
#如果不指定變量,read命令就會(huì)把它收到的任何數(shù)據(jù)都放到特殊環(huán)境變量REPLY中
read -p "Enter a number:"
factorial=1
for (( count=1; count<=$REPLY; count++))
do
factorial=$[ $factorial * $count ]
done
echo "The factorial of $REPLY is $factorial"
24、根據(jù)計(jì)算機(jī)當(dāng)前時(shí)間,返回問候語
#!/bin/bash
# 根據(jù)計(jì)算機(jī)當(dāng)前時(shí)間,返回問候語,可以將該腳本設(shè)置為開機(jī)啟動(dòng)
# 00‐12 點(diǎn)為早晨,12‐18 點(diǎn)為下午,18‐24 點(diǎn)為晚上
# 使用 date 命令獲取時(shí)間后,if 判斷時(shí)間的區(qū)間,確定問候語內(nèi)容
tm=$(date +%H)
if [ $tm -le 12 ];then
msg="Good Morning $USER"
elif [ $tm -gt 12 -a $tm -le 18 ];then
msg="Good Afternoon $USER"
else
msg="Good Night $USER"
fi
echo "當(dāng)前時(shí)間是:$(date +"%Y‐%m‐%d %H:%M:%S")"
echo -e "\033[34m$msg\033[0m"
二. 文件操作
1、將字符串寫入到文件中
比如,將 I love cls 寫入到 demo.txt 文件中文章來源:http://www.zghlxwxcb.cn/news/detail-734488.html
#!/bin/bash
cd /home/wenmin/
touch demo.txt
echo "I love cls" >>demo.txt
2、目錄文件計(jì)數(shù)
#!/bin/bash
# count number of files in your PATH
mypath=`echo $PATH | sed 's/:/ /g'`
count=0
for directory in $mypath
do
check=`ls $directory`
echo $check
for item in $check
do
count=$(( $count + 1 ))
done
echo "$directory - $count"
count=0
done
3、從文件中讀取數(shù)據(jù)
#!/bin/bash
# reading data from a file
count=1
cat test | while read line
do
echo "Line $count: $line"
count=$[ $count + 1 ]
done
echo "Finished processing the file"
4、用腳本實(shí)現(xiàn)復(fù)制
#!/bin/bash
cp $1 $2
5、用腳本實(shí)現(xiàn)文件是否存在的判斷
#!/bin/bash
if [ -f file.txt ];then
echo "文件存在"
else
echo "文件不存在"
fi
6、檢查指定目錄下是否有指定文件
#!/bin/bash
if [ -f /home/wenmin/datas ]
then
echo "File exists"
fi
7、腳本 每周 5 使用 tar 命令備份/var/log 下的所有日志文件
#!/bin/bash
# 每周 5 使用 tar 命令備份/var/log 下的所有日志文件
# vim /root/logbak.sh
# 編寫備份腳本,備份后的文件名包含日期標(biāo)簽,防止后面的備份將前面的備份數(shù)據(jù)覆蓋
# 注意 date 命令需要使用反引號(hào)括起來,反引號(hào)在鍵盤<tab>鍵上面
tar -czf log-`date +%Y%m%d`.tar.gz /var/log
# crontab -e #編寫計(jì)劃任務(wù),執(zhí)行備份腳本
00 03 * * 5 /home/wenmin/datas/logbak.sh
8、sed文件操作
#!/bin/bash
#向文件寫入
sed '1,2w test1' test1
echo -e "next\n"
#從文件讀取
sed '3r ./test' ./test
echo -e "next\n"
#從文件讀取,并插入字符流
sed '/lazy/r test' test
#向數(shù)據(jù)流末尾添加數(shù)據(jù)
sed '$r test' test
echo -e "next1\n"
sed '/lazy/ {
r test
d
}' test
三. 實(shí)用工具
1、定時(shí)執(zhí)行腳本
#!/bin/bash
# testing the at command
at -f 4.sh 22:10
2、查看有多少ip在連接本機(jī)
#!/bin/bash
# 查看有多少遠(yuǎn)程的 IP 在連接本機(jī)(不管是通過 ssh 還是 web 還是 ftp 都統(tǒng)計(jì))
# 使用 netstat ‐atn 可以查看本機(jī)所有連接的狀態(tài),‐a 查看所有,
# -t僅顯示 tcp 連接的信息,‐n 數(shù)字格式顯示
# Local Address(第四列是本機(jī)的 IP 和端口信息)
# Foreign Address(第五列是遠(yuǎn)程主機(jī)的 IP 和端口信息)
# 使用 awk 命令僅顯示第 5 列數(shù)據(jù),再顯示第 1 列 IP 地址的信息
# sort 可以按數(shù)字大小排序,最后使用 uniq 將多余重復(fù)的刪除,并統(tǒng)計(jì)重復(fù)的次數(shù)
netstat -atn | awk '{print $5}' | awk '{print $1}' | sort -nr | uniq -c
3、實(shí)時(shí)監(jiān)控本機(jī)內(nèi)存和硬盤剩余空間
剩余內(nèi)存小于500M、根分區(qū)剩余空間小于1000M時(shí),發(fā)送報(bào)警郵件給root管理員文章來源地址http://www.zghlxwxcb.cn/news/detail-734488.html
#!/bin/bash
# 實(shí)時(shí)監(jiān)控本機(jī)內(nèi)存和硬盤剩余空間,剩余內(nèi)存小于500M、根分區(qū)剩余空間小于1000M時(shí),發(fā)送報(bào)警郵件給root管理員
# 提取根分區(qū)剩余空間
disk_size=$(df / | awk '/\//{print $4}')
# 提取內(nèi)存剩余空空間
mem_size=$(free | awk '/Mem/{print $4}')
while :
do
# 注意內(nèi)存和磁盤提取的空間大小都是以 Kb 為單位
if [ $disk_size -le 512000 -a $mem_size -le 1024000 ]
then
mail ‐s "Warning" root <<EOF
Insufficient resources,資源不足
EOF
fi
done
4、統(tǒng)計(jì)當(dāng)前 Linux 系統(tǒng)中可以登錄計(jì)算機(jī)的賬戶有多少個(gè)
#!/bin/bash
# 統(tǒng)計(jì)當(dāng)前 Linux 系統(tǒng)中可以登錄計(jì)算機(jī)的賬戶有多少個(gè)
#方法 1:
grep "bash$" /etc/passwd | wc -l
#方法 2:
awk -f : '/bash$/{x++}end{print x}' /etc/passwd
5、殺掉 tomcat 進(jìn)程并重新啟動(dòng)
#!/bin/bash
#kill tomcat pid
pidlist=`ps -ef|grep apache-tomcat-7.0.75|grep -v "grep"|awk '{print $2}'` #找到tomcat的PID號(hào)
echo "tomcat Id list :$pidlist" //顯示pid
kill -9 $pidlist #殺掉改進(jìn)程
echo "KILL $pidlist:" //提示進(jìn)程以及被殺掉
echo "service stop success"
echo "start tomcat"
cd /opt/apache-tomcat-7.0.75
pwd
rm -rf work/*
cd bin
./startup.sh #;tail -f ../logs/catalina.out
6、使用return命令返回函數(shù)
#!/bin/bash
# using the return command in a function
function db1 {
read -p "Enter a value:" value
echo "doubling the value"
return $[ $value * 2 ]
}
db1
echo "The new value is $?"
7、用腳本安裝memcached服務(wù)器
#!/bin/bash
# 一鍵部署 memcached
# 腳本用源碼來安裝 memcached 服務(wù)器
# 注意:如果軟件的下載鏈接過期了,請更新 memcached 的下載鏈接
wget http://www.memcached.org/files/memcached-1.5.1.tar.gz
yum -y install gcc
tar -xf memcached‐1.5.1.tar.gz
cd memcached‐1.5.1
./configure
make
make install
8、備份MySQL數(shù)據(jù)庫
#!/bin/sh
source /etc/profile
dbName=mysql
tableName=db
echo [`date +'%Y-%m-%d %H:%M:%S'`]' start loading data...'
mysql -uroot -proot -P3306 ${dbName} -e "LOAD DATA LOCAL INFILE '# /home/wenmin/wenxing.txt' INTO TABLE ${tableName} FIELDS TERMINATED BY ';'"
echo [`date +'%Y-%m-%d %H:%M:%S'`]' end loading data...'
exit
EOF
9、一鍵部署 LNMP(RPM 包版本)
#!/bin/bash
# 一鍵部署 LNMP(RPM 包版本)
# 使用 yum 安裝部署 LNMP,需要提前配置好 yum 源,否則該腳本會(huì)失敗
# 本腳本使用于 centos7.2 或 RHEL7.2
yum -y install httpd
yum -y install mariadb mariadb-devel mariadb-server
yum -y install php php-mysql
systemctl start httpd mariadb
systemctl enable httpd mariadb
四. 圖形化操作
1、打印帶顏色的棋盤
#!/bin/bash
# 打印國際象棋棋盤
# 設(shè)置兩個(gè)變量,i 和 j,一個(gè)代表行,一個(gè)代表列,國際象棋為 8*8 棋盤
# i=1 是代表準(zhǔn)備打印第一行棋盤,第 1 行棋盤有灰色和藍(lán)色間隔輸出,總共為 8 列
# i=1,j=1 代表第 1 行的第 1 列;i=2,j=3 代表第 2 行的第 3 列
# 棋盤的規(guī)律是 i+j 如果是偶數(shù),就打印藍(lán)色色塊,如果是奇數(shù)就打印灰色色塊
# 使用 echo ‐ne 打印色塊,并且打印完成色塊后不自動(dòng)換行,在同一行繼續(xù)輸出其他色塊
for i in {1..8}
do
for j in {1..8}
do
sum=$[i+j]
if [ $[sum%2] -eq 0 ];then
echo -ne "\033[46m \033[0m"
else
echo -ne "\033[47m \033[0m"
fi
done
echo
done
2、使用msgbox部件
#!/bin/bash
dialog --title text --msgbox "This is a test" 10 20
3、使用菜單顯示指令操作
#!/bin/bash
function menu {
clear
echo
echo -e "\t\tSys Admin Menu\n"
echo -e "\t1. Display disk space"
echo -e "\t2. Display logged on users"
echo -e "\t3. Display memory usage"
echo -e "\t0. Exit program\n\n"
echo -en "\t\tEnter option:"
read -n 1 option
}
function diskspace {
clear
df -k
}
function whoseon {
clear
who
}
function menusage {
clear
cat /proc/meminfo
}
while [ 1 ]
do
menu
case $option in
0)
break;;
1)
diskspace;;
2)
whoseon;;
3)
menusage;;
*)
clear
echo "Sorry, wrong selection";;
esac
echo -en "\n\n\t\tHit any key to continue"
read -n 1 line
done
clear
4、在腳本中使用dialog命令
#!/bin/bash
# using dialog to create a menu
temp=`mktemp -t test.XXXXXX`
temp2=`mktemp -t test2.XXXXXX`
function diskspace {
df -k > $temp
dialog --textbox $temp 20 60
}
function whoseon {
who > $temp
dialog --textbox $temp 20 50
}
function menusage {
cat /proc/meminfo > $temp
dialog --textbox $temp 20 50
}
while [ 1 ]
do
dialog --menu "Sys Admin Menu" 20 30 10 1 "Display disk space" 2 "Display users" 3 "Display memory usage" 0 "Exit" 2> $temp2
if [ $? -eq 1 ]
then
break
fi
selection=`cat $temp2`
case $selection in
1)
diskspace;;
2)
whoseon;;
3)
menusage;;
0)
break;;
*)
dialog --msgbox "Sorry,invalid selection" 10 30
esac
done
rm -f $temp 2> /dev/null
rm -f $temp2 2> /dev/null
5、使用select命令
#!/bin/bash
# using select in the menu
function diskspace {
clear
df -k
}
function whoseon {
clear
who
}
function menusage {
clear
cat /proc/meminfo
}
PS3="Enter option:"
select option in "Display disk space" "Display logged on users" "Display memory usage" "Exit program"
do
case $option in
"Exit program")
break;;
"Display disk space")
diskspace;;
"Display logged on users")
whoseon;;
"Display memory usage")
menusage;;
*)
clear
echo "Sorry, wrong selection";;
esac
done
clear
五. sed操作
1、sed編輯器基礎(chǔ)
#!/bin/bash
#sed編輯器基礎(chǔ)
#替換標(biāo)記
sed 's/lazy/ht/' ./test
echo -e "next\n"
#可用的替換標(biāo)記
#1.數(shù)字 表明新聞本將替換第幾處模式匹配的地方
sed 's/lazy/ht/2' ./test
#2.g 表明新文件將會(huì)替換所有已有文本出現(xiàn)的地方
sed 's/lazy/ht/g' ./test
#3.p 表明原來行的內(nèi)容要打印出來,替換后的
sed 's/lazy/ht/p' ./test
#4.w file 將替換的結(jié)果寫到文件中
sed 's/lazy/ht/w test1' ./test
echo -e "next\n"
#替換字符
sed 's/\/bin\/bash/\/bin\/csh/' /etc/passwd
#或者
sed 's!/bin/bash!/bin/csh!' /etc/passwd
echo -e "next\n"
#使用地址
#1.數(shù)字方式的行尋址
sed '2s/lazy/cat/' ./test
sed '2,3s/lazy/cat/' ./test
sed '2,$s/lazy/cat/' ./test
#2.使用文本模式過濾器
sed '/tiandi/s/bash/csh/' /etc/passwd
echo -e "next\n"
#組合命令
sed '2{
s/fox/elephant/
s/dog/cat/
}' test
sed '2,${
s/fox/elephant/
s/dog/cat/
}' test
echo -e "next\n"
#刪除行
sed '3d' ./test
sed '2,$d' ./test
sed '/number 1/d' ./test
#刪除兩個(gè)文本模式來刪除某個(gè)范圍的行,第一個(gè)開啟刪除功能,第二個(gè)關(guān)閉刪除功能
sed '/1/,/3/d' ./test
echo -e "next\n"
#插入和附加文本
sed '3i\
This is an appended line.' ./test
sed '$a\
This is a new line of text.' ./test
#修改行
sed '3c\
This a changed line of text.' ./test
sed '/number 1/c\
This a changed line of text.' ./test
#替換兩行文本
#sed '2,3c\
#This a changed line of text.' ./test
#轉(zhuǎn)換命令,處理單個(gè)字符
#sed 'y/123/789/' ./test
echo -e "next\n"
#回顧打印
# p 打印文本行
# -n 禁止其他行,只打印包含匹配文本模式的行
sed -n '/number 3/p' ./test
#查看修改之前的行和修改之后的行
#sed -n '/3/{
#p
#s/line/test/p
#}' ./test
echo -e "next\n"
# 打印行號(hào)
sed '=' ./test
#打印指定的行和行號(hào)
#sed -n '/lazy/{
#=
#p
#}' ./test
#列出行 打印數(shù)據(jù)流中的文本和不可打印的ASCII字符,任何不可打印的字符都用它們的八進(jìn)制值前加一個(gè)反斜線或標(biāo)準(zhǔn)C風(fēng)格的命名法,比如用\t來代表制表符
sed -n 'l' ./test
2、輸出末尾指定行數(shù)的數(shù)據(jù)
#!/bin/bash
#輸出末尾10行數(shù)據(jù)
sed '{
:start
$q
N
11,$D
b start
}' /etc/passwd
3、刪除指定的空白行和刪除html標(biāo)簽
#!/bin/bash
#多個(gè)空格只保留一個(gè)
#sed '/./,/^$/!d' test
#刪除開頭的空白行
#sed '/./,$!d' test
#刪除結(jié)尾的空白行
sed '{
:start
/^\n*$/{$d; N; b start}
}' test
#刪除html標(biāo)簽
#有問題
#s/<.*>//g
#sed 's/<[^>]*>//g' test1
#sed 's/<[^>]*>//g;/^$/d' test1
4、模式替代
#!/bin/bash
#and符號(hào),代表替換命令中的匹配模式,不管預(yù)定義模式是什么文本,都可以用and符號(hào)替換,and符號(hào)會(huì)提取匹配替換命令中指定替換模式中的所有字符串
echo "The cat sleeps in his hat" | sed 's/.at/"&"/g'
#替換單獨(dú)的單詞
echo "The System Administrator manual" | sed 's/\(System\) Administrator/\1 user/'
#在長數(shù)字中插入逗號(hào)
echo "1234567" | sed '{:start; s/\(.*[0-9]\)\([0-9]\{3\}\)/\1,\2/; t start}'
六. gawk操作
1、使用變量
#!/bin/bash
#使用內(nèi)建變量
# NF 當(dāng)前記錄的字段個(gè)數(shù)
# NR 到目前為止讀的記錄數(shù)量
#下面的程序在每行開頭輸出行號(hào),并在最后輸出文件的總字段數(shù)
gawk '{ total+=NF; print NR, $0 }END{ print "Total: ", total}'
gawk 'BEGIN {testing="This is a test"; print testing; testing=45; print testing}'
#處理數(shù)字值
gawk 'BEGIN{x=4; x= x*2+3; printx}'
#處理數(shù)組
gawk 'BEGIN{capital["Ill"] = "SprintField"; print capital["Ill"]}'
#遍歷數(shù)組變量
gawk 'BEGIN{
var["a"] = 1
var["g"] = 2
var["m"] = 3
for( test in var)
{
print "Index:",test,"- Value:",var[test]
}
}'
print "------"
#刪除數(shù)組變量
gawk 'BEGIN{
var["a"] = 1
var["g"] = 2
for (test in var)
{
print "Index:",test," - Value:", var[test]
}
delete var["g"]
print "----"
for (test in var)
{
print "Index;",test," - Value:", var[test]
}
}'
2、使用模式,結(jié)構(gòu)化命令
#!/bin/bash
#正則表達(dá)式
gawk 'BEGIN{FS=","}
/11/{print $1}
' test
#if-else語句
gawk '{
if($1 > 20)
{
x=$1*20
print x
}
else
{
x=$1/2
print x
}
}' test
#while 語句
gawk '{
total = 0
i=1
while(i<4)
{
total+=$i
i++
}
avg = total/3
print "Average:".avg
}' test
#do-while語句
gawk '{
total=0
i=1
do
{
total += $i
i++
}while(total < 150)
print total }' test
#for語句
gawk '{
total = 0
for (i=1; i<4; i++)
{
total+=$i
}
avg = total/3
print "Average:".avg
}' test
3、自定義函數(shù)
#!/bin/bash
#gawk 自定義函數(shù)
gawk '
function myprint()
{
printf "%-16s - %s\n", $1, $4
}
BEGIN{FS="\n"; RS=""}
{
myprint()
}' test
4、調(diào)用函數(shù)庫和腳本
#!/bin/bash
#使用函數(shù)庫和gawk腳本
gawk -f gawk函數(shù)庫 -f gawk腳本 test
5、輸出
#!/bin/bash
#print用于產(chǎn)生簡單輸出
#多個(gè)表達(dá)式的字符串值之間用輸出字段分隔符分開
gawk '{ print $1, $2 }'
#輸出字段分割符與輸出記錄分隔符存儲(chǔ)在內(nèi)建變量OFS與ORS中,
#初始情況下,OFS與ORS被設(shè)置成一個(gè)空格符與一個(gè)換行符,但它們的值可以在任何時(shí)候改變
#下面這個(gè)程序打印每一行的第1第2個(gè)字段,字段之間用分號(hào)分開,在每一行的第2個(gè)字段之后輸出兩個(gè)換行符
gawk 'BEGIN { OFS = ":"; ORS = "\n\n" }
{ print $1, $2 }'
#下面這個(gè)程序拼接第1個(gè)與第2個(gè)字段,兩個(gè)字段之間沒有輸出字段分隔符插入
gawk '{ print $1 $2 }'
#這兩句話等價(jià)
gawk '{ print }'
gawk '{ print $0 }'
#輸出空行
gawk '{ print "" }'
#printf用于產(chǎn)生格式化輸出
#printf不會(huì)自動(dòng)換行,需要手動(dòng)添加\n
#格式說明符以%開始,以轉(zhuǎn)換字符結(jié)束
# - 表達(dá)式在它的域內(nèi)左對齊,沒有則右對齊
# width 為了達(dá)到規(guī)定的寬度,必要時(shí)填充空格
# .prec 字符串最大寬度, 或十進(jìn)制數(shù)的小數(shù)部分的位數(shù)
gawk '{ printf ("Name:%-10sAge:%-5dWeight:%7.2f\n", $1, $2, $3) }'
#輸出到文件
#重定向運(yùn)算符>與>>用于將輸出重定向到文件,文件名必須用雙引號(hào)括起來
#下面這個(gè)程序?qū)⑺休斎胄械牡?個(gè)與第3個(gè)字段輸出到兩個(gè)文件中:如果第3個(gè)字段大于100,則輸出到bigpop,否則輸出到smallpop
gawk '{ print($1, $3) > ($3 > 100 ? "bigpop" : "smallpop") }'
#輸出到管道
#print的輸出將以管道的方式傳遞給command
# Canada 3852
# China 3705
# USA 3615
# Brazil 3286
gawk '{ pop[$1]+=$2 }
END{ for(c in pop) printf("%15-s%6d\n", c, pop[c]) | "sort -nk 2"; close("sort -nk 2") }'
#關(guān)閉文件與管道
#語句close(expression)關(guān)閉一個(gè)文件或管道,文件或管道由expression指定。
#expression的字符串值必須與最初用于創(chuàng)建文件或管道的字符串值相同。
#在同一個(gè)程序中,如果你寫了一個(gè)文件,而待會(huì)兒想要讀取它,那么就需要調(diào)用close。
#某一時(shí)刻,同時(shí)處于打開狀態(tài)的文件或管道數(shù)量最大值由實(shí)現(xiàn)定義。
close("sort -nk 2")
到了這里,關(guān)于常用的 55 個(gè) Linux Shell 腳本(包括基礎(chǔ)案例、文件操作、實(shí)用工具、圖形化、sed、gawk)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!