【Linux命令】《鳥哥Linux基礎》第十二章 學習shell腳本

第十二章 學習shell腳本

通常利用shell腳本完成服務器的檢測工作,不涉及大量運算。

12.1 簡單shell腳本介紹

12.2 簡單shell腳本練習

12.2.1 簡單範例

範例1:永遠的開端Helloworld

cat hello.sh 
輸出:
#!/bin/bash   
#Program:
#	This program shows "hello world!" in your screen.
#History:
#2020/06/07	dj	First release
PATH=/bin:/sbin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo -e "hello world! \a \n"
exit 0

#! 用來聲明這個腳本使用的shell版本。
註釋包括:

  1. 腳本的內容與功能;
  2. 腳本的版本信息;
  3. 腳本的作者與聯繫方式;
  4. 腳本的版權生命方式;
  5. 建立文件日期;
  6. 腳本的歷史記錄History;
  7. 腳本內較特殊的命令,使用【絕對路徑】的方式執行;給與足夠的註釋;
  8. 腳本運行時需要的環境變量預先聲明和設置。
chmod a+x hello.sh	 給3者都加上x的權限,這3者指的是文件所有者、文件所屬組、其他人

範例2:與用戶交互

cat showname.sh 
輸出:
#!bin/bash
#Program:
#	User inputs his first name and last name. Program shows his full name.
#History:
#2020/06/08	dj	First relese
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
read -p "Please input your first name:" firstname
read -p "Please input your last name:" lastname
echo -e "\nYour full name is: ${firstname} ${lastname}"

範例3:隨日期變化的文件名

cat create_3_filename.sh 
輸出:
#!/bin/bash
#Program:
#	Program create three files,which named by user's input and date command.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# 1.get file name from user
echo -e "I will use 'touch' command to create 3 files."
read -p "Please input your file name:" fileuser

# 2.
filename=${fileuser:-"filename"}

# 3.get file name from date
date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}

# 4.create file
touch "${file1}"
touch "${file2}"
touch "${file3}"

需要注意,date1=$(date --date='2 days ago' +%Y%m%d)'2 days ago'%Y%m%d之間務必要有一個空格!

[dj@study bin]$ sh create_3_filename.sh 
I will use 'touch' command to create 3 files.
Please input your file name:djTest
[dj@study bin]$ ll
總用量 12
-rw-rw-r--. 1 dj dj 674 6月   8 11:13 create_3_filename.sh
-rw-rw-r--. 1 dj dj   0 6月   8 11:10 djTest
-rw-rw-r--. 1 dj dj   0 6月   8 11:13 djTest20200606		這裏可以看到新建的三個文件
-rw-rw-r--. 1 dj dj   0 6月   8 11:13 djTest20200607		這裏可以看到新建的三個文件
-rw-rw-r--. 1 dj dj   0 6月   8 11:13 djTest20200608		這裏可以看到新建的三個文件
-rwxrwxr-x. 1 dj dj 224 6月   7 20:14 hello.sh
-rw-rw-r--. 1 dj dj 370 6月   8 10:57 showname.sh

範例4:求兩個整數的乘積(bash shell裏只能算整數)

cat multiplying.sh 
輸出:
#!/bin/bash
# Program:
#	User inputs 2 integer numbers;program will cross these two numbers.
# History:
# 2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo -e "You SHOULD input 2 numbers,I will multiplying them!\n"
read -p "first number:" firstnumber
read -p "second number:" secondnumber
total=$((${firstnumber}*${secondnumber}))
declare -i total1=${firstnumber}*${secondnumber}
echo -e "\nThe result of ${firstnumber} x ${secondnumber} is ==> ${total}"
echo -e "\nThe result of ${firstnumber} x ${secondnumber} is ==> ${total1}"

命令執行情況:

[dj@study bin]$ sh multiplying.sh 
You SHOULD input 2 numbers,I will multiplying them!

first number:10
second number:6

The result of 10 x 6 is ==> 60

The result of 10 x 6 is ==> 60

說明這兩種計算方式都是可以的:

total=$((${firstnumber}*${secondnumber}))
declare -i total1=${firstnumber}*${secondnumber}

推薦:

var=$((運算內容))

通過bc命令協助,計算含有小數點的數。

echo "123.123*2.3"|bc
輸出:
283.182

範例5:利用bc求圓周率Pi

cat cal_pi.sh 
輸出:
#!/bin/bash
#Program:
#	User input a scale number to calculate pi number.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo -e "This program will calculate pi value.\n"
echo -e "You should input a float number to calculate pi value.\n"
read -p "The scale number (10~10000) ? " checking
num=${checking:-"10"}
echo -e "Starting calculate pi value. Be paient."
time echo "scale=${num};4*a(1)" | bc -lq

其中,4*a(1)是bc提供的一個計算Pi的函數。運行情況:

[dj@study bin]$ sh cal_pi.sh 
This program will calculate pi value.

You should input a float number to calculate pi value.

The scale number (10~10000) ? 10
Starting calculate pi value. Be paient.
3.1415926532

real	0m0.004s
user	0m0.002s
sys	0m0.002s

12.2.2 腳本執行方式的差異(source、sh script、./script)

利用直接執行的方式執行腳本,絕對路徑、相對路徑、${PATH}內、利用bash、利用sh,該腳本都會使用一個新的bash環境來執行腳本內的命令。是在子進程中執行的。 執行完畢後,所有數據被刪除,父進程中讀取不到。

利用source來執行腳本,在父進程中執行。 執行完畢後,數據都保留在父進程中。因此,爲了讓更新後的~/.bashrc生效,需要使用source ~/.bashrc,而不能用bash ~/.bashrc

12.3 善用判斷式

$? && ||

12.3.1 利用test命令的測試功能

test用來檢測系統上某些文件或是相關屬性。

test -e /dj			檢查這個文件或目錄是否存在,執行後不會顯示任何信息

搭配 $?&&|| 來展現結果:

test -e /dj  &&  echo "exist" || echo "Not exist"	如果文件存在,繼續執行&&右邊的,否則,忽略&&直接執行||右邊的

關於test的參數,書本第396頁有個巨大的表格,可以參考。
常用如下:

測試的參數 意義
-e 看文件是否存在
-f 看文件是否存在且爲文件
-d 看文件是否存在且爲目錄
cat file_perm.sh
輸出:
#!/bin/bash
#Program:
#	User input a filename,program will check the following:
#	1)exist? 2)file/directory? 3)file permissions
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/.bashrc
export PATH

# 1. 檢查用戶輸入的內容是否爲空
echo -e "Please input a filename,I will check the filename's type and permission.\n\n"
read -p "Input a filename:" filename
test -z ${filename}  && echo "You MUST input a filename."  && exit 0

# 2. 判斷文件是否存在,不存在就退出
test ! -e ${filename} && echo "The filename '${filename}' DO NOT EXIST" && exit 0

# 3. 判斷是文件還是目錄;判斷權限
test -f ${filename} && filetype="regular file"
test -d ${filename} && filetype="directory"
test -r ${filename} && perm="readable"
test -w ${filename} && perm="${perm} writable"
test -x ${filename} && perm="${perm} executable"

# 4. 輸出判斷結果
echo "The filename: ${filename} is a ${filetype}"
echo "And the permissions for you are:${perm}"

執行結果:

[dj@study bin]$ sh file_perm.sh 
Please input a filename,I will check the filename's type and permission.


Input a filename:/home/dj
The filename: /home/dj is a directory
And the permissions for you are:readable writable executable

12.3.2 利用判斷符號[]

判斷變量${HOME}是否爲空:
[ -z "${HOME}" ];echo $?	尤其注意,中括號[右側有一個空格,中括號]左側也有一個空格,否則報錯
輸出:
1

範例6:利用[]做判斷

cat ans_yn.sh 
輸出:
#!/bin/bash
#Program:
#	This program shows the user's choice
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "Please input (Y/N):" yn
[ "${yn}" == "Y" -o "${yn}" == "y" ] && echo "OK,continue" && exit 0
[ "${yn}" == "N" -o "${yn}" == "n" ] && echo "Oh,interrupt!" && exit 0
echo "I donot know what your choice is" && exit 0

執行結果:

[dj@study bin]$ sh ans_yn.sh 
Please input (Y/N):
I donot know what your choice is
[dj@study bin]$ sh ans_yn.sh 
Please input (Y/N):y
OK,continue
[dj@study bin]$ sh ans_yn.sh 
Please input (Y/N):N
Oh,interrupt!

12.3.3 shell腳本的默認變量($0、$1…)

/path/to/scriptname		opt1	opt2	opt3
		$0				 $1		 $2		 $3
特殊變量 意義
$# 後接的參數個數,此處未3
$@ “$1” “$2” “$3”,每個變量是獨立的
$* “$1c$2c$3”,c爲分隔字符,默認爲空格

範例7:輸出當前執行命令的參數信息

cat show_paras.sh 
輸出:
#!/bin/bash
#Program:
#	Program shows the script name,parameters...
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "The script name is ===>  ${0}"
echo "Total parameter number is ===>  $#"
[ "$#" -lt 2 ] && echo "The number of parameters is less than 2. Stop here." && exit 0
echo "Your whole parameters is  ===>  '$@'"
echo "The 1st parameter  ===>  ${1}"
echo "The 2nd parameter  ===>  ${2}"

執行情況:

sh show_paras.sh theone thetwo thethree
The script name is ===>  show_paras.sh
Total parameter number is ===>  3
Your whole parameters is  ===>  'theone thetwo thethree'
The 1st parameter  ===>  theone
The 2nd parameter  ===>  thetwo

範例8:shift的使用,拿掉最前面幾個參數

cat shift_paras.sh 
#!/bin/bash
#Program:
#	Program shows the effect of shift function.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"

shift
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"

shift 3
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"

執行情況:

[dj@study bin]$ sh shift_paras.sh theone thetwo thethree thefour thefive thesix
Total parameter number is ==> 6
Your whole parameter is ==> 'theone thetwo thethree thefour thefive thesix'
Total parameter number is ==> 5
Your whole parameter is ==> 'thetwo thethree thefour thefive thesix'
Total parameter number is ==> 2
Your whole parameter is ==> 'thefive thesix'

12.4 條件判斷式

if then

12.4.1 利用if…then

簡單的版本:

if [條件判斷式]; then
	條件判斷式成立時,進行的命令工作內容;
fi

範例9:用if…then改寫範例6

cat ans_yn-2.sh 
輸出:
#!/bin/bash
#Program:
#	This program shows the user's choice
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "Please input (Y/N):" yn
if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then
	echo "OK,continue" 
	exit 0
fi

if [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then
	echo "Oh,interrupt!"
	exit 0
fi
echo "I donot know what your choice is" && exit 0

複雜的版本:

if [條件判斷式]; then
	條件判斷式成立時,進行的命令工作內容;
else
	條件判斷式不成立時,進行的命令工作內容;
fi

更復雜的版本:

if [條件判斷式1]; then
	條件判斷式1成立時,進行的命令工作內容;
elif [條件判斷式2]; then
	條件判斷式2成立時,進行的命令工作內容;
else
	條件判斷式1和2都不成立時,進行的命令工作內容;
fi

範例10:用if…elif…then改寫範例6

cat ans_yn-3.sh 
#!/bin/bash
#Program:
#	This program shows the user's choice
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "Please input (Y/N):" yn
if [ "${yn}" == "Y" ] || [ "${yn}" == "y" ]; then
	echo "OK,continue" 
	exit 0
elif [ "${yn}" == "N" ] || [ "${yn}" == "n" ]; then
	echo "Oh,interrupt!"
	exit 0
else
	echo "I donot know what your choice is" && exit 0
fi

範例11:判斷用戶輸入的額外指令

cat hello-2.sh 
輸出:
#!/bin/bash
#Program:
#	This program check $1 is equal to "hello"
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

if [ "${1}" == "hello" ];then
	echo "Hello,how are you?"
elif [ "${1}" == "" ];then
	echo "You MUST input parameters,ex> { ${0} someword }"
else 
	echo "The only parameter is 'hello',ex> {${0} hello}"
fi

範例12:查看自己的主機是否開啓了主要的網絡服務端口

命令netstat,可以查詢到目前主機開啓的網絡服務端口。
每個端口都有其特定的網絡服務,常見的端口與相關網絡服務:

端口 服務
80 WWW
22 ssh
21 ftp
25 mail
111 RPC(遠程過程調用)
631 CUPS(打印服務功能)
netstat -tuln
輸出:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN     
tcp        0      0 192.168.122.1:53        0.0.0.0:*               LISTEN     
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN     
tcp6       0      0 ::1:631                 :::*                    LISTEN     
tcp6       0      0 ::1:25                  :::*                    LISTEN     
tcp6       0      0 :::111                  :::*                    LISTEN     
tcp6       0      0 :::22                   :::*                    LISTEN     
udp        0      0 0.0.0.0:908             0.0.0.0:*                          
udp        0      0 0.0.0.0:44545           0.0.0.0:*                          
udp        0      0 192.168.122.1:53        0.0.0.0:*                          
udp        0      0 0.0.0.0:67              0.0.0.0:*                          
udp        0      0 0.0.0.0:111             0.0.0.0:*                          
udp        0      0 0.0.0.0:5353            0.0.0.0:*                          
udp6       0      0 :::908                  :::*                               
udp6       0      0 :::111                  :::*  
cat netstat.sh 
輸出:
#!/bin/bash
#Program:
#	Using netstat and grep to detect WWW,SSH,FTP and Mail service.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# 1.
echo "Now,I will detect your linux server's services!"
echo -e "The www,ftp,ssh,mail(smtp) will be detect!\n"

# 2.
testfile=/dev/shm/netstat_checking.txt
netstat -tuln > ${testfile}
testing=$(grep ":80" ${testfile})
if [ "${testing}" != "" ];then				
	echo "WWW is running in your system."
fi

testing=$(grep ":22" ${testfile})
if [ "${testing}"!="" ];then
	echo "SSH is running in your system."
fi

testing=$(grep ":21" ${testfile})
if [ "${testing}"!="" ];then
	echo "FTP is running in your system."
fi

testing=$(grep ":25" ${testfile})
if [ "${testing}"!="" ];then
	echo "MAIL is running in your system."
fi

注意:if [ "${testing}" != "" ];thenif[之間有個空格,不能缺少。
執行情況:

[dj@study bin]$ sh netstat.sh 
Now,I will detect your linux server's services!
The www,ftp,ssh,mail(smtp) will be detect!

SSH is running in your system.
FTP is running in your system.
MAIL is running in your system.

12.4.2 利用case…esac判斷

case $變量名稱 in
 "第一個變量內容")
 	程序段
 	;;
 "第二個變量內容")
	程序段
	;;
 *)		
 	程序段
 	;;
esac

*表示其他所有情況。

12.4.3 利用function功能

function fname(){
	程序段	
}

範例13:打印用戶的選擇,one、two、three

cat show123.sh 
輸出:
#!/bin/bash
#Program:
#	Use function to repeat information.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

function printit(){
	echo -n "Your choice is "
}
echo "This program will print your selection!"
case ${1} in
 "one")
 	printit;echo ${1} | tr 'a-z' 'A-Z'
	;;
 "two")
 	printit;echo ${1} | tr 'a-z' 'A-Z'
	;;
 "three")
 	printit;echo ${1} | tr 'a-z' 'A-Z'
	;;
 *)
 	echo "Usage ${0} {one|two|three}"
	;;
esac

函數function內部也有$0 $1 $2...這種變量,容易與shell腳本的$0 $1 $2...搞混.

12.5 循環(loop)

12.5.1 while do done、until do done(不定循環)

while [ condition ]
do
	程序段落
done
until [ condition ]
do 
	程序段落
done

範例14:循環直到用戶輸入正確的字符

使用while:

cat yes_to_stop.sh 
輸出:
#!/bin/bash
#Program:
#	Repeat question until user input correct answer.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

while [ "${yn}" != "yes" -a "${yn}" != "YES" ]
do
	read -p "Please input yes/YES to stop this program: " yn
done

echo "OK! you input the correct answer."

使用until:

cat yes_to_stop-2.sh 
輸出:
#!/bin/bash
#Program:
#	Repeat question until user input correct answer.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

while [ "${yn}" == "yes" -a "${yn}" == "YES" ]    只需要修改這裏爲==即可
do
	read -p "Please input yes/YES to stop this program: " yn
done

echo "OK! you input the correct answer."

範例15:用循環計算1+2+3+…+100

cat cal_1_100.sh 
輸出:
#!/bin/bash
#Program:
#	Use loop to calculate "1+2+3+4+5+...+100" result.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

s=0
i=0

while [ "${i}" !=  "100" ]
do 
	i=$(($i + 1))
	s=$(($s+$i))
done
echo "The result of '1+2+3+...+100' is ==> $s"

執行情況:

sh cal_1_100.sh 
輸出:
The result of '1+2+3+...+100' is ==> 5050

範例16:範例15中最大數n由用戶指定,1+2+3+…+user_input

cat cal_1_100.sh 
輸出:
#!/bin/bash
#Program:
#	User input n,I will use loop to calculate "1+2+3+4+5+...+n" result.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "Please input n:" n
s=0
i=0
while [ "${i}" != "${n}" ]
do 
	i=$(($i + 1))
	s=$(($s+$i))
done
echo "The result of '1+2+3+...+ '${n} is ==> $s"

執行情況:

sh cal_1_100.sh 
Please input n:10
The result of '1+2+3+...+ '10 is ==> 55

12.5.2 for…do…done(固定循環)

前面while和until都是必須要符合某個條件,而for是已知要進行幾次循環。

for var in con1 con2 con3...
do 
	程序段
done

範例17:檢查用戶的標識符和特殊參數

通過管道命令的cut識別出單純的賬號名稱,以id分別檢查用戶的標識符與特殊參數。

cat userid.sh 
輸出:
#!/bin/bash
#Program:
#	Use id,finger command to check system account's information.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

users=$(cut -d ':' -f1 /etc/passwd)
for username in ${users}
do 
	id ${username}
done
sh userid.sh
輸出:
uid=0(root) gid=0(root)=0(root)
uid=1(bin) gid=1(bin)=1(bin)
uid=2(daemon) gid=2(daemon)=2(daemon)
uid=3(adm) gid=4(adm)=4(adm)
...
uid=38(ntp) gid=38(ntp)=38(ntp)
uid=72(tcpdump) gid=72(tcpdump)=72(tcpdump)
uid=1000(dj) gid=1000(dj)=1000(dj),10(wheel)

範例18:檢查192.168.1.1~192.168.1.100共100臺主機目前是否與自己的主機連通

cat pingip.sh 
輸出:
#!/bin/bash
#Program:
#	Use ping command to check the network's PC state.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

network="192.168.1"
for sitenu in $(seq 1 100)
do
	ping -c 1 -w 1 ${network}.${sitenu} &> /dev/null && result=0 || result=1
	if [ "${result}" == 0 ];then
		echo "Server ${network}.${sitenu} is UP."
	else 
		echo "Server ${network}.${sitenu} is DOWN."
	fi
done

此處, $(seq 1 100)可以用{1..100}替換。類似的,連續輸出a-g的字符,echo {a..g}

範例19:用戶輸入一個目錄,程序找出目錄內所有文件名的權限

cat dir_perm.sh 
輸出:
#!/bin/bash
#Program:
#	User input dir name,I find the permission of files.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# 1.
read -p "Please input a directory: " dir
if [ "${dir}" == "" -o ! -d "${dir}" ];then
	echo "The ${dir} is NOT exist in your system."
	exit 1
fi

# 2.
filelist=$(ls ${dir})
for filename in ${filelist}
do 
	perm=""
	test -r "${dir}/${filename}" && perm="${perm} readable"
	test -w "${dir}/${filename}" && perm="${perm} writable"
	test -x "${dir}/${filename}" && perm="${perm} executable"
	echo "The file ${dir}/${filename}'s permission is ${perm}"
done

執行情況:

sh dir_perm.sh 
輸出:
Please input a directory: /home/dj
The file /home/dj/a2's permission is  readable writable executable
The file /home/dj/bin's permission is  readable writable executable
The file /home/dj/catfile's permission is  readable writable
The file /home/dj/homefile's permission is  readable writable
The file /home/dj/last.list's permission is  readable writable
The file /home/dj/list_error's permission is  readable writable
The file /home/dj/list_right's permission is  readable writable
The file /home/dj/regular_express.txt's permission is  readable writable
The file /home/dj/公共's permission is  readable writable executable
The file /home/dj/模板's permission is  readable writable executable
The file /home/dj/視頻's permission is  readable writable executable
The file /home/dj/圖片's permission is  readable writable executable
The file /home/dj/文檔's permission is  readable writable executable
The file /home/dj/下載's permission is  readable writable executable
The file /home/dj/音樂's permission is  readable writable executable
The file /home/dj/桌面's permission is  readable writable executable

12.5.3 for…do…done的數值處理

for (( 初始值;限制值;賦值運算 ))
do
	程序段
done

範例20:同範例16,範例15中最大數n由用戶指定,1+2+3+…+user_input

cat cal_1_100-2.sh 
輸出:
#!/bin/bash
#Program:
#	Try to calculate 1+2+3+...+${your_input}
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

read -p "Please input a number, I will count for 1+2+3+...+your_input:" nu
s=0
for (( i=1;i<=${nu};i=i+1 ))
do	
	s=$((${s}+${i}))
done
echo "The result of '1+2+3+...+${nu}' is ==> ${s}"

執行情況:

sh cal_1_100-2.sh 
輸出:
Please input a number, I will count for 1+2+3+...+your_input:10
The result of '1+2+3+...+10' is ==> 55

12.5.4 搭配隨機數與數組的實驗

這裏面的邏輯有些理不順,後續繼續學習。

cat what_to_eat.sh 
輸出:
#!/bin/bash
#Program:
#	Try do tell you what you may eat.
#History:
#2020/06/08	dj	First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

eat[1]="maidangdanghanbao1"
eat[2]="maidangdanghanbao2"
eat[3]="maidangdanghanbao3"
eat[4]="maidangdanghanbao4"
eat[5]="maidangdanghanbao5"
eat[6]="maidangdanghanbao6"

eatnum=6
eated=0
while [ "${eated}" -lt 3 ];do
	check=$(( ${RANDOM} * ${eatnum} / 32767 + 1))
	mycheck=0
	if [ "${eated}" -ge 1 ];then
		for i in  $(seq 1 ${eated})
		do 
			if [ ${eatedcon[$i]} == $check ];then
				mycheck=1
			fi
		done
	fi
	if [ ${mycheck} == 0 ];then
		echo "you may eat ${eat[${check}]}"
		eated=$(( ${eated} + 1 ))
		eatedcon[${eated}]=${check}
	fi
done

運行情況:

sh what_to_eat.sh 
you may eat maidangdanghanbao1
you may eat maidangdanghanbao4
you may eat maidangdanghanbao5

12.6 腳本的跟蹤與調試

sh [-nvx] scripts.sh
	  -n  不要執行腳本,僅檢查語法問題
	  -v  在執行腳本前,現將腳本文件內容輸出到屏幕上
	  -x  將使用到的腳本內容顯示到屏幕上(相當有用)

sh -x scripts.sh   進行程序的debug
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章