当前位置: > shell编程 >

shell脚本实例:创建不存在的文件和目录

时间:2014-12-05 02:52来源:linux.it.net.cn 作者:IT

一段简单的shell脚本,用于创建不存在的文件与目录,其中创建了几个自定义函数,用来学习shell 函数很不错。

代码:
 

 

#!/bin/bash
# 创建不存在的文件与目录
# 此脚本演示了shell中函数的用法,以及使用getopts命令获取命令行参数的方法
# by www.it.net.cn
#
usage(){
 echo "Usage: $0 {-f filename} {-d dirname}"
 exit 1
}
 
createDir(){
 if [ ! -d $1 ]
 then
  /bin/mkdir -p $1 >/dev/null 2>&1 && echo "Directory $1 created." ||  echo "Error: Failed to create $1 directory."
 else
  echo "Error: $1 directory exits!"
 fi
}
 
createFile(){
 if [ ! -f $1 ] 
 then
  touch $1 > /dev/null 2>&1 && echo "File $1 created."  ||  echo "Error: Failed to create $1 files."
 else
  echo "Error: $1 file exists!"
 fi
}
 
while getopts f:d:v option
do
        case "${option}"
        in
                f) createFile ${OPTARG};;
                d) createDir ${OPTARG};;
                \?) usage
                    exit 1;;
        esac
done
 


(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容