本文最后更新于 2024-10-15,文章内容距离上一次更新已经过去了很久啦,可能已经过时了,请谨慎参考喵。

title: Shell脚本简单示例
tags:
  - Bash
categories:
  - Linux
top_img: false
cover: '/upload/cdn0files/20200721122919.png'
abbrlink: 6526142f
date: 2019-12-29 15:08:15
updated: 2019-12-29 15:08:15

hello wrold

#!/bin/bash
## program:
## shows "hello world!" in your screen
## history:
## 2019/8/21	laugh	first release
## 2019/8/21	laugh	second modify
## 修复了在./下执行时路径找不到的问题;第一行‘#!’为声明使用的shell名称,解释器的作用,并不是注释
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo -e "hello world! \a \n"
exit 0

计算从1累加到100

#!/bin/bash
## program:
## 计算1+2+3+...+100的数值
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
s=0 #求和的数值变量
i=0 #累计的数值,就是123等等
while [ "${i}" != "100" ]
do 
	i=$(( $i+1 ))
    s=$(( $s+$i ))
done 
echo "The result of 1+2+3++100 is ==> $s"

计算从1累加到指定数值

#!/bin/bash
## program:
## 计算从1累加到用户指定的数字为止
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
read -p "Please input a number , I will help you to sum 1+2+3+...+your number :" nu 
s=0
for (( i=1; i<=${nu}; i=i+1 ))
do 
	s=$(( ${s} + ${i} ))
done 
echo "1+2+3+4+...+${nu}==>${s}"

键盘读取和输出语句

#!/bin/bash
#program:
#显示用户输入的用户名
#history:
#2019/8/22	laugh	first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
read -p "Please input your first name:" firstname
read -p "Please input your last name:" lastname
echo -e "\nYour fullname is: ${firstname} ${lastname}"

用if elif else语句实现y/n的选择

#!/bin/bash
## program:
## 判断输入字符并输出相应信息
## history:
## 2019/8/22   laugh	  first
## 2019/8/23   laugh   second
## 修改了[]的用法和使用了if判断式
## 2019/8/23  laugh   3
## 使用了多重条件判断式
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
read -p "Please input (Y/N):" yn
if [[ ${yn} == "Y" ]] || [[ ${yn} == "y" ]]; then
	echo "Ok,continue "
    elif [ "${yn}" == "N" -o "${yn}" == "n" ]; then
		echo "No,interrupt "
	else
		echo "I don't know what your choice is " && exit 0
fi

用if语句实现y/n的选择

#!/bin/bash
## program:
## 判断输入字符并输出相应信息
## history:
## 2019/8/22   laugh   first
## 2019/8/23   laugh   second
## 修改了[]的用法和使用了if判断式
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
read -p "Please input (Y/N):" yn
if [[ ${yn} == "Y" ]] || [[ ${yn} == "y" ]]; then
	echo "Ok,continue "
	exit 0
fi
if [ "${yn}" == "N" -o "${yn}" == "n" ]; then
	echo "No,interrupt "
	exit 0
fi
echo "I don't know what your choice is " && exit 0

利用正则表达式实现y/n的选择

正则表达式,又称规则表达式**。**(英语:Regular Expression,在代码中常简写为regex、regexp或RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。

许多程序设计语言都支持利用正则表达式进行字符串操作。例如,在Perl中就内建了一个功能强大的正则表达式引擎。正则表达式这个概念最初是由Unix中的工具软件,例如sed和[grep普及开的。正则表达式通常缩写成“regex”,单数有regexp、regex,复数有regexps、regexes、regexen。

#!/bin/bash
## program:
## 判断输入字符并输出相应信息
## history:
## 2019/8/22	laugh	first
## 2019/8/22	laugh	second
## 修改了[]和[[]]还有“”的用法,详情看下面代码
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
read -p "Please input (Y/N):" yn
[[ ${yn} == "Y" ]] || [[ ${yn} == "y" ]] && echo "Ok,continue " && exit 0
[ "${yn}" == "N" -o "${yn}" == "n" ] && echo "No,interrupt " && exit 0
echo "I don't know what your choice is " && exit 0

计算指定位数的圆周率

#!/bin/bash
## program:
## 计算圆周率Pi
## history:
## 2019/8/22	laugh	first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
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 calcuate pi value. Be patiant."
time echo "scale=${num}; 4*a(1)" | bc -lq

计算日期

#!/bin/bash 
## program:
## 倒数还有多长时间退伍
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo "This program will try to calculate :"
echo "How many days before your demobilization date..."
read -p "Please input your demobilization date (YYYYMMDD ex>20190823) : " date2
date_d=$(echo ${date2} | grep '[0-9]\{8\}')    #利用正则表达式测试是否为八个数字
if [ "${date_d}" == "" ]; then  #判断输入字符
	echo "You input the wrong date forment..."
	exit 1
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} /60/60/24 ))  #转为日数
if [ "${date_total_s}" -lt "0" ]; then  #判断是否已经退伍
 	echo "You had been demobilization before :" $(( -1*${date_d} )) " ago"
else 
	declare -i date_h=$(( $(( ${date_total_s}-${date_d}*60*60*24 )) /60/60 ))
	echo "You will demobilization after ${date_d} days and ${date_h} hours. "
fi

建立三个文件,文件名是前天,昨天和今天的日期加指定的文件名

#!/bin/bash
#program:
## 建立三个文件,文件名的开头由用户指定,其他由今天日期决定,三个文件分别是前天、今天和明天
## history:
## 2019/8/22	laugh	first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo -e "I will ues 'touch' command to create 3 files."		#显示提示信息
read -p "Please input your filename:" fileuser		#输入文件名
filename=${fileuser:-"filename"}		#利用变量功能分析文件名是否设置,避免用户错误使用【enter】
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}"

输入文件夹名,检索文件夹内所有文件并输出权限信息

#!/bin/bash
## program:
## 用户输入目录名,自动检索该目录内文件并输出文件权限信息
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
#先查看这个目录是否存在
read -p "Please input a directory :" dir 
if [ "${dir}" == "" -o ! -d "${dir}" ]; then 
	echo "The ${dir} is NOT exist in your system."
	exit 0
fi 
#开始测试文件
filelist=$( ls ${dir} )
for filename in ${filelist}
do 
perm=""
test -r "${dir}/${filename}" && perm="${perm} r"
test -w "${dir}/${filename}" && perm="${perm} w"
test -x "${dir}/${filename}" && perm="${perm} x"
echo "The file ${dir}/${filename}'s permission is ${perm} "
done

判断指定文件名是否为文件夹,若不是则检查该文件的权限信息并输出

#!/bin/bash
## program:
## 输入一个文件名,查询这个文件名是否存在,是否是文件还是目录,并输出相关权限信息,本脚本不建议用root用户执行
## history:
## 2019/8/22	laugh	first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo -e "Please input a filename,I will check the filename's type and permission. \n\n"
read -p "input your filename:" filename	#读取键盘输入并赋值变量
test -z ${filename} && echo "you MUST input a filename" && exit 0	#判断用户是否输入文件名并提示
test ! -e ${filename} && echo "The file '${filename}' do not exist!" && exit 0	#判断文件是否存在
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 "The filename permission for you are:${perm}"	#输出文件权限

示例for do done 的用法

#!/bin/bash
## program:
## 示例for do done 的用法
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
for animal in dog pig cat
do 
	echo "There are ${animal}s ..."
done

case判断,用户输入hello程序回应相对应对话

#!/bin/bash
## program:
## 用户输入hello程序回应相对应对话
## history:
## 2019/8/23  laugh   first
## 2019/8/23  laugh   second
## 改为case判断
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
case ${1} in 
	"hello")
		echo "Hello ,how are you !"
	;;
	"")
		echo "you must input parameters , ex> { ${0} someword }"
	;;
	*)  #相当于通配符,任意字符
		echo "Usage ${0} {hello}"
	;;
esac

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

if语句实现指定对话

#!/bin/bash
## program:
## 用户输入hello程序回应相对应对话
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
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 parameters is 'hello' , ex> {${0} hello}"
fi

shift变量偏移的示例用法

#!/bin/bash
## program:
## 示例shift变量偏移的作用
## history:
## 2019/8/22	laugh	first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo "Please input 6 to show 'shift' "
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	==> '$@' "

程序的文件名是什么,共有几个参数,若参数少于2则告诉用户参数太少,全部的参数内容是什么,第一个参数是什么,第二个参数是什么,参数的用法

#!/bin/bash
## program:
## 程序的文件名是什么,共有几个参数,若参数少于2则告诉用户参数太少,全部的参数内容是什么,第一个参数是什么,第二个参数是什么
## history:
## 2019/8/22	laugh	first
## 2019/8/22	laugh	second
## 显示变量的时候$(1)不需要括号
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo "The script name	==> ${0}"
echo "Total parameter number is	==> $#"
[ "$#" -lt 2 ] && echo "The number of parameter is less then 2. Stop here." && exit 0
echo "Your whole parameter is	==> '$@' "
echo "The 1st parameter	==> $1 "
echo "The 2nd parameter	==> $2 "

乘法运算

#!/bin/bash
## program:
## 由用户输入两个整数数字,计算其乘积并输出
## history:
## 2019/8/22	laugh	first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo -e "Please input 2 int numbers,I will multiplying them !"		#显示提示信息
read -p "firstnumber:" first		#读取第一个数字
read -p "secondnumber:" second		#读取第二个数字
total=$((${first}*${second}))		#进行乘法运算
echo -e "\nThe result of ${first}*${second} is ==> ${total}"		#输出结果

扫描指定端口并输出结果

#!/bin/bash
## program:
## 检测主机的80端口(www服务)、22端口(ssh服务)、21端口(ftp服务)、25端口(mail服务)
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo "Now, I will detect your linux server's services!"
echo -e "The www, ftp, ssh and mail(smtp) will be detect!"  #告知信息
testfile=~/Desktop/netstat_checking.txt
netstat -tuln > ${testfile}
testing=$(grep ":80 " ${testfile})
if [ "${testing}" != "" ]; then
	echo "WWW is runing in your system."
fi
testing=$(grep ":22 " ${testfile})
if [ "${testing}" != "" ]; then
	echo "SSH is runing in your system."
fi
testing=$(grep ":21 " ${testfile})
if [ "${testing}" != "" ]; then
	echo "FTP is runing in your system."
fi
testing=$(grep ":25 " ${testfile})
if [ "${testing}" != "" ]; then
	echo "MAIL is runing in your system."
fi

让用户输入one two three三个变量,并输出到屏幕上,如果不是,就告知用户其他的选择(function的用法)

#!/bin/bash
#program:
#让用户输入one two three三个变量,并输出到屏幕上,如果不是,就告知用户其他的选择
#history:
#2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
function printit () {			#函数一定要放在最前面!
	echo -n "Your choice is ${1} "
}
echo "This progarm will print your selection !"
case ${1} in
	"one")
		printit 1;
	;;
	"two")
		printit 2;
	;;
	"three")
		printit 3;
	;;
	 *)
		echo "Usage ${0} {one|two|three}"
	;;
esac

让用户输入one two three三个变量其中的一个,并输出到屏幕上,如果不是,就告知用户其他的选择,两种语法选择

#!/bin/bash
#program:
#让用户输入one two three三个变量,并输出到屏幕上,如果不是,就告知用户其他的选择
#history:
#2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
function printit ()         #函数一定要放在最前面!
	{
	echo -n "Your choice is :"
}
echo "This progarm 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

用参数输出指定内容

#!/bin/bash
## program:
## 让用户输入one two three三个变量,并输出到屏幕上,如果不是,就告知用户其他的选择
## history:
## 2019/8/23  laugh   first
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/sbin
export PATH
echo "This program will print your selection !"
#read -p "input your choice:" choice    #暂时不用
#case ${choice} in  #暂时不用
case ${1} 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