别人的Linux私房菜(13)学习Shell脚本

时间:2022-01-14 07:16:04

CentOS6.x以前版本的系统服务启动接口在/etc/init.d/目录下,存放了脚本。

Shell脚本因调用外部命令和bash 的一些默认工具,速度较慢,不适合处理大量运算。

执行方式有:直接命令执行、绝对路径/相对路径执行、PATH执行、bash程序执行。

PATH中含有家目录的bin路径,可以在bin下写的脚本直接执行。

sh file

#!/bin/bash加载环境相关的配置文件,一般指代非登录的~/.bashrc

输入姓名并输出:

 read -p "Please input your first name: " firstname  # 提示使用者输入
read -p "Please input your last name: " lastname # 提示使用者输入
echo -e "\nYour full name is: $firstname $lastname" # 结果由萤幕输出

建立以前天,昨天,今天有关的文件名:

 echo -e "I will use 'touch' command to create 3 files." # 纯粹显示资讯
read -p "Please input your filename: " fileuser # 提示使用者输入 # . 为了避免使用者随意按 Enter ,利用变量功能分析档名是否有配置?
filename=${fileuser:-"filename"} # 开始判断有否配置档名 # . 开始利用 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} # . 将档名创建吧!
touch "$file1" # 底下三行在创建文件
touch "$file2"
touch "$file3"

简单加减乘除:

 echo -e "You SHOULD input 2 numbers, I will cross them! \n"
read -p "first number: " firstnu
read -p "second number: " secnu
total=$(($firstnu*$secnu))
echo -e "\nThe result of $firstnu x $secnu is ==> $total"

求余运算示例:echo $(( 13 % 3 ))

乘法运算的另一种方式:declare -i total=$firstnu*$secnu

计算含小数点的数据:echo "123.123*55.9" | bc

计算π值:echo "scale=10; 4*a(1)" | bc -lq#调用了4*a(1)函数,计算π并取小数点后10位。

直接执行的bash(绝对路径相对路径或PATH等),执行中的赋予新的子进程bash,使用子进程的bash配置,变量为局部变量。

利用source 来执行的脚本,变量成为全局变量。

test命令的测试功能:

如 test -e /home && echo "ok" || echo "no"检查目录是否存在

1. 关於某个档名的『文件类型』判断,如 test -e filename 表示存在否
http://cn.linux.vbird.org/linux_basic/0340bashshell-scripts_3.php

别人的Linux私房菜(13)学习Shell脚本

别人的Linux私房菜(13)学习Shell脚本

判断文件类型和权限:

 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
# . 判断文件是否存在?若不存在则显示信息并结束脚本
test ! -e $filename && echo "The filename '$filename' DO NOT exist" && exit
# . 开始判断文件类型与属性
test -f $filename && filetype="regulare file"
test -d $filename && filetype="directory"
test -r $filename && perm="readable"
test -w $filename && perm="$perm writable"
test -x $filename && perm="$perm executable"
# . 开始输出资讯!
echo "The filename: $filename is a $filetype"
echo "And the permissions are : $perm"

[ ] 判断符号

[ ]两端需要空格分隔,每个组件空格分隔,变量双引号,常数,单引号或双引号,参数基本同test命令。=和==相同

如检查变量是否为空:[ -z "$HOME" ] ; echo $?

使用中括号进行的判定示例:

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

shell脚本使用的默认变量:

$0表示该脚本名,$1-$.......表示执行该脚本接入的命令参数

$#接入的参数个数(除$0)     $@所有变量,$* 带分隔符的所有变量。

示例:输入参数即可测试。

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

shift:参数左偏移减少。示例如下:

 echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift # 进行第一次『一个变量的 shift 』
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"
shift # 进行第二次『三个变量的 shift 』
echo "Total parameter number is ==> $#"
echo "Your whole parameter is ==> '$@'"

使用if [];then   xxx fi 语句示例:

&& 等同 -a   ||  等同 -o

 read -p "Please input (Y/N): " yn

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

 if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
echo "OK, continue"
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
echo "Oh, interrupt!"
else
echo "I don't know what your choice is"
fi

查看端口是否打开:•80: WWW    •22: ssh    •21: ftp     •25: mail

 testing=$(netstat -tuln | grep ":80 ")   # 侦测看 port  在否?
if [ "$testing" != "" ]; then
echo "WWW is running in your system."
fi
testing=$(netstat -tuln | grep ":22 ") # 侦测看 port 在否?
if [ "$testing" != "" ]; then
echo "SSH is running in your system."
fi
testing=$(netstat -tuln | grep ":21 ") # 侦测看 port 在否?
if [ "$testing" != "" ]; then
echo "FTP is running in your system."
fi
testing=$(netstat -tuln | grep ":25 ") # 侦测看 port 在否?
if [ "$testing" != "" ]; then
echo "Mail is running in your system."
fi

判断输入是否8个数字,并计算时间差的天数:

 echo "This program will try to calculate :"
echo "How many days before your demobilization date..."
read -p "Please input your demobilization date (YYYYMMDD ex>20090401): " date2 # . 测试一下,这个输入的内容是否正确?利用正规表示法罗~
date_d=$(echo $date2 |grep '[0-9]\{8\}') # 看看是否有八个数字
if [ "$date_d" == "" ]; then
echo "You input the wrong date format...."
exit
fi # . 开始计算日期罗~
declare -i date_dem=`date --date="$date2" +%s` # 退伍日期秒数
declare -i date_now=`date +%s` # 现在日期秒数
declare -i date_total_s=$(($date_dem-$date_now)) # 剩余秒数统计
declare -i date_d=$(($date_total_s///)) # 转为日数
if [ "$date_total_s" -lt "" ]; then # 判断是否已退伍
echo "You had been demobilization before: " $((-*$date_d)) " ago"
else
declare -i date_h=$(($(($date_total_s-$date_d***))//))
echo "You will demobilize after $date_d days and $date_h hours."
fi

利用case...esac的语句进行选择判断:

结构:尾部分号为两个

 case  $变量名称 in   <==关键字为 case ,还有变量前有钱字号
"第一个变量内容") <==每个变量内容建议用双引号括起来,关键字则为小括号 )
程序段
;; <==每个类别结尾使用两个连续的分号来处理!
"第二个变量内容")
程序段
;;
*) <==最后一个变量内容都会用 * 来代表所有其他值
不包含第一个变量内容与第二个变量内容的其他程序运行段
exit
;;

示例:

 case $ in
"hello")
echo "Hello, how are you ?"
;;
"")
echo "You MUST input parameters, ex> {$0 someword}"
;;
*) # 其实就相当於万用字节,~无穷多个任意字节之意!
echo "Usage $0 {hello}"
;;
esac

示例2:

 echo "This program will print your selection !"
# read -p "Input your choice: " choice # 暂时取消,可以替换!
# case $choice in # 暂时取消,可以替换!
case $ in # 现在使用,可以用上面两行替换!
"one")
echo "Your choice is ONE"
;;
"two")
echo "Your choice is TWO"
;;
"three")
echo "Your choice is THREE"
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac

 函数设计与调用

其内置变量和shell名称相似,$0 -- $n,为函数的局部变量

示例:

 function printit(){
echo -n "Your choice is " # 加上 -n 可以不断行继续在同一行显示
} echo "This program will print your selection !"
case $ in
"one")
printit; echo $ | tr 'a-z' 'A-Z' # 将参数做大小写转换!
;;
"two")
printit; echo $ | tr 'a-z' 'A-Z'
;;
"three")
printit; echo $ | tr 'a-z' 'A-Z'
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac

带函数参数的示例:

 function printit(){
echo "Your choice is $1" # 这个 $ 必须要参考底下命令的下达
} echo "This program will print your selection !"
case $ in
"one")
printit # 请注意, printit 命令后面还有接参数!
;;
"two")
printit
;;
"three")
printit
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac

循环:

while []do done 循环  条件成立执行循环

until []do done 循环  条件不成立执行循环

示例1-n!!!!:真繁琐

 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 [ "$yn" == "yes" -o "$yn" == "YES" ]
do
read -p "Please input yes/YES to stop this program: " yn
done
echo "OK! you input the correct answer."

100内的累加:

 s=  # 这是加总的数值变量
i= # 这是累计的数值,亦即是 , , ....
while [ "$i" != "" ]
do
i=$(($i+)) # 每次 i 都会添加
s=$(($s+$i)) # 每次都会加总一次!
done
echo "The result of '1+2+3+...+100' is ==> $s"

for var in xxx  do  done 循环,xxx内轮询一遍就结束。

示例:

 for animal in dog cat elephant
do
echo "There are ${animal}s.... "
done

显示用户,和对应的号:

 users=$(cut -d ':' -f1 /etc/passwd)  # 撷取帐号名称
for username in $users # 开始回圈进行!
do
id $username
finger $username
done

批量ping ip地址:使用seq 1 100取值,也可以使用{1..100}取值  和{a..g}类似

 network="192.168.1"              # 先定义一个网域的前面部分!
for sitenu in $(seq ) # seq 为 sequence(连续) 的缩写之意
do
# 底下的程序在取得 ping 的回传值是正确的还是失败的!
ping -c -w ${network}.${sitenu} &> /dev/null && result= || result=
# 开始显示结果是正确的启动 (UP) 还是错误的没有连通 (DOWN)
if [ "$result" == ]; then
echo "Server ${network}.${sitenu} is UP."
else
echo "Server ${network}.${sitenu} is DOWN."
fi
done

获取目录下文件的权限:

 read -p "Please input a directory: " dir
if [ "$dir" == "" -o ! -d "$dir" ]; then
echo "The $dir is NOT exist in your system."
exit
fi # . 开始测试文件罗~
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

 for ((初始值;限制值;赋值运算)) do... done 循环:

示例:1到x的累加:

 read -p "Please input a number, I will count for 1+2+...+your_input: " nu

 s=
for (( i=; i<=$nu; i=i+ ))
do
s=$(($s+$i))
done
echo "The result of '1+2+3+...+$nu' is ==> $s"

随机数和数组示例:

a[1]="a"

a[2]="b"

a[3]="c"

check=$(( ${RANDOM}*3/32767+1))

echo "ans:${a[${check}]}"

shell脚本跟踪与调试

-n不执行脚本只查询语法,-v执行脚本前输出内容 -x使用到的脚本显示到屏幕上(跟踪)

例如:sh -x file