linux基础之Shell Script入门介绍

2019-09-23 09:44:38于丽

touch "$filename2"
touch "$filename3"
exit 0

调用:


$ bash sh03.sh
I will use 'touch' to create three files.
Please input your filename:WhoKnows
$ ls W*
WhoKnows20130201  WhoKnows20130202  WhoKnows20130203

3 判断式
3.1 测试文件是否存在
test -e filename会根据filename是否存在返回0或1,再交由echo显示结果:


$ test -e sh01.sh  && echo "Exists" || echo "Not exists"
Exists
$ test -e sh0x.sh  && echo "Exists" || echo "Not exists"
Not exists

3.2 test常用选项
3.2.1 文件类型


-e file :file是否存在
-f file :file是否存在且为文件
-d file :file是否存在且为目录

3.2.2 权限
-r file :file是否有读的权限

3.2.3 文件新旧比较
-nt file1 file2 : file1 是否比 file2新

3.2.4 整数,字符串,多重条件判断
-z string: string是否为空
例:输出指定文件类型及属性


# !/bin/bash
# Program:
#       This program is used to output type and permission of the target file
# History:
# 2013/2/3 on_1y First release
PATH=$PATH
export PATH
# Get filename from user
echo -e "Input name of the file that you want to check.n"
read -p "Filename:" filename
test -z $filename && echo "You must input a filename." && exit 0
# Check whether the file exists or not
test ! -e $filename && echo "The file '$filename' DO NOT exists" && exit 0
# Check type and permission of the file
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"
# Output result
echo "The filename:$filename is a $filetype"
echo "And Permissions are :$perm"
exit 0

调用:


$ bash sh04.sh
Input name of the file that you want to check.

Filename:sh01.sh
The filename:sh01.sh is a regular file
And Permissions are :readable writable executable

3.3 使用[]判断

测试文件是否存在


$ [ -e "sh01.sh" ] ; echo $?
0
$ [ -e "sh0x.sh" ] ; echo $?
1

注意[]内空格必须有
这种方法和test的test -e "sho1.sh" ; echo $? 是一致的

4 Shell Script 参数


# !/bin/bash
# Program:
#       This program is used to ouput parameter of the shell script
# History:
# 2013/2/3 on_1y First release
PATH=$PATH
export PATH
echo "The script's name is ==> $0"
echo "Total parameter number is ==> $#"
# Check whether number of the parameter is less than 2
[ "$#" -lt 2 ] && echo "The number of parameter is less than 2.Stop here." && exit 0
echo "The whole parameter is ==> '$@'"
echo "The first parameter is ==> $1"
echo "The first parameter is ==> $2"