shell 脚本必须要以"#!/bin.bash"开头。
脚本建议内容:
- 脚本的功能
- 脚本的版本信息
- 脚本的作者与联系方式
- 脚本的版权声明方式
- 脚本的History
- 脚本内特殊的命令,使用【绝对路径】的方式来执行
- 脚本运行时需要的环境变量预先声明预设置
示例:
#!/bin/bash
# Program:
# This program shows "create 2 day age,1 day age and today filename"
#
#Creat:
# 2021/11/11
#
#Hirstory:
#
#
#Creater/Contact:
# Mr_Chang 1135130670@qq.com
#
read -p "Please input filename" userfile
userfilename=${userfile:-"filename"}
date1=$(date --date='2 days ago' +%y-%m-%d)
date2=$(date --date='1 days ago' +%y-%m-%d)
date3=$(date +%y-%m-%d)
filename1=${userfilename}-${date1}
filename2=${userfilename}-${date2}
filename3=${userfilename}-${date3}
touch "${filename1}"
touch "${filename2}"
touch "${filename3}"
进行数值运算时需用$(())引起来计算。
$((计算式))
#!/bin/bash
# Program:
# This program shows "multiplay"
#
#Creat:
# 2021/11/11
#
#Hirstory:
#
#
#Creater/Contact:
# Mr_Chang 1135130670@qq.com
#
read -p "file number:" fNum
read -p "secound number:" sNum
sum=$((${fNum}+${sNum}))
echo "total --> ${sum}"
脚本执行方式的差异(source、sh script 、./script)
source或./script:在当前环境下的shell执行,脚本运行结束后,脚本内的变量在当前shell中依然存在。
sh script:另打开一个子bash shell,运行完后子shell内的变量随着进程结束而消失,要想保留则需export来声明成环境变量。
test 判别式
test可以使用 [ ] 来替换
[-z "${
HOME}"] ; echo $?
使用 [ ] 时特别注意:
- 中括号内每个组件都需要使用空格来分隔开
- 中括号内的每个变量最好都使用双引号引起来
- 中括号内的常数最好以单或双引号括起来
shell脚本的默认变量
/tmp/shell/scriptname opt1 opt2 opt3 opt4
$0 $1 $2 $3 $4
$0:表示脚本名
$1:表示第一个变量
$2:表示第二个变量
.
.
.
$#:表示参数总个数
$@:表示【 “$1” “$2” “$3” “$4” 】之意,每个变数是独立的(用双引号括起来);
$*:表示【 “$1c$2c$3c$4” 】,其中 c 为分隔符,默认为空格, 前面代表【 “$1 $2 $3 $4” 】之意。
shift 造成号码偏移
#!/bin/bash
# Program:
# This program shows shell shift functionasily
#
#Creat:
# 2021/11/11
#
#Hirstory:
#
#
#Creater/Contact:
# Mr_Chang 1135130670@qq.com
#
echo "shell variables count: $#"
echo "show shell variable : '$@'"
echo "used shift"
shift
echo "shell variables count: $#"
echo "show shell variable : '$@'"
echo "used shift 3"