Korn Shell 脚本入门
2008-08-20 08:18:43 来源:WEB开发网TIME=$(date +%H%M)
清单 13 中所显示的代码将在晚上 10:00 和晚上 11:00 删除某个文件。因此,每次执行这个代码段的时候,将检查 $TIME 是否匹配 case 语句所指定的时间。如果匹配,那么将执行相应的代码。
清单 13. 用于检查时间的 case 语句
case $TIME in
"2200") #This means 10:00
rm –rf /tmp/file1
;;
"2300")#This means 11:00
rm –rf /tmp/file1
;;
"*")
echo "Do nothing" > /dev/null
;;
esac
综合使用完整的脚本
到目前为止,您已经创建了一个脚本标头和一些简单变量,并且添加了一个函数,如清单 14 所示。
清单 14. 示例 Korn shell 脚本
$vi my_second_script.ksh
#!/bin/ksh
###################################################
# Written By: Jason Thomas
# Purpose: This script was written to show users how to develop their first script
# May 1, 2008
###################################################
#Define Variables
HOME="/home/jthomas" #Simple home directory
TIME=$(date +%H%M) # Set DATE equal to the output of running the shell command date
HOSTNAME=$(hostname) # Set HOSTNAME equal to the output of the hostname command
##################
function if_error
##################
{
if [[ $? -ne 0 ]]; then # check return code passed to function
print "$1" # if rc > 0 then print error msg and quit
exit $?
fi
}
if [[ -e /tmp/file ]]; then #Check to see if the file exists first
rm –rf /tmp/file #Delete file
if_error "Error: Failed removing file /tmp/file"
else
print "/tmp/file doesn’t exist"
fi
if [[ -e /tmp/test ]]; then
mkdir /tmp/test #Create the directory test
if_error "Error: Failed trying to create directory /tmp/test"
else
print "Directory exists, no need to create directory"
fi
case $TIME in
"2200")
rm –rf /tmp/file1
;;
"2300")
rm –rf /tmp/file1
;;
#End Script
更多精彩
赞助商链接