『练习』:编写脚本filectl.sh,filectl.sh -a filename添加文件;filectl.sh -d filename删除文件;filectl.sh -p filename备份文件;若非-a|-d|-p,则提醒“Please Input -a|-d|-p following filectl.sh“
<方法1:使用函数方式+if语句实现>
#!/bin/bash
ECHO()
{
echo -e "\033[${1}m$2\033[0m"
}
FILE()
{
read -p "Please Input filename: " FILE
}
if [ "$1" != "-a" -a "$1" != "-d" -a "$1" != "-p" ]
then
ECHO 31 "Please Input -a|-d|-p following $0 !"
elif [ "$1" = "-a" ]
then
FILE
if [ -e "$FILE" ]
then
ECHO 31 "$FILE is exist!"
FILE
fi
touch $FILE
ECHO 32 "$FILE is created successful !"
elif [ "$1" = "-d" ]
then
FILE
if [ ! -e "$FILE" ]
then
ECHO 31 "$FILE is not exist!"
FILE
fi
rm $FILE
ECHO 32 "$FILE is already delete !"
elif [ "$1" = "-p" ]
then
FILE
if [ ! -e "$FILE" ]
then
ECHO 31 "$FILE is not exist!"
FILE
fi
cp -rp $FILE /mnt/
ECHO 32 "$FILE is backuped successful !"
fi
<方法2:使用函数方式+if语句实现>
#!/bin/bash
ECHO()
{
echo -e "\033[${1}m$2\033[0m"
}
FILE()
{
read -p "Please Input filename: " FILE
}
if [ "$1" = "-a" ]
then
FILE
if [ -e "$FILE" ]
then
ECHO 31 "$FILE is exist!"
FILE
fi
touch $FILE
ECHO 32 "$FILE is created successful !"
elif [ "$1" = "-d" ]
then
FILE
if [ ! -e "$FILE" ]
then
ECHO 31 "$FILE is not exist!"
FILE
fi
rm $FILE
ECHO 32 "$FILE is already delete !"
elif [ "$1" = "-p" ]
then
FILE
if [ ! -e "$FILE" ]
then
ECHO 31 "$FILE is not exist!"
FILE
fi
cp -rp $FILE /mnt/
ECHO 32 "$FILE is backuped successful !"
else
ECHO 31 "Please Input -a|-d|-p following $0 !"
fi
<方法3:使用函数方式+if语句实现>
#!/bin/bash
Check_File()
{
if [ -e "$1" ]
then
$2
$3
fi
}
if [ "$#" -lt "2" ]
then
echo "Error: Please input option [-a|-d|-p] and filename following $0"
exit 1
fi
if [ "$1" = "-a" ]
then
Check_File $2 "echo $2 is exist !" exit
touch $2
elif [ "$1" = "-d" ]
then
Check_File $2 "rm -rf $2" exit
echo "$2 is not exit !"
elif [ "$1" = "-p" ]
then
Check_File $2 "cp -rp $2 /mnt" exit
echo "$2 is not exit !"
else
echo 31 "Please Input -a|-d|-p following $0 !"
fi
if语句
是顺序执行命令的,效率较低,故引入case语句
—>点名机制
查看if语句
的执行机制
执行-p
(备份)命令时要先执行-a
、-p
命令,耗时较长,效率较低
查看case语句
的执行机制
<方式4:使用函数方式+if语句+case语句实现>
#!/bin/bash
Check()
{
if [ -e "$1" ]
then
$2
$3
fi
}
if [ "$#" -lt "2" ]
then
echo "Error: Please input option [-a|-d|-p] and filename following $0"
exit 1
fi
case $1 in
-a)
Check $2 "echo $2 is exist !" exit
touch $2
;;
-d)
Check $2 "rm -rf $2" exit
echo "$2 is not exit !"
;;
-p)
Check $2 "cp -rp $2 /mnt" exit
echo "$2 is not exit !"
;;
*)
echo "Please Input -a|-d|-p following $0 !"
esac