c shell 命令行参数处理getopts.sh

发布于:2024-04-29 ⋅ 阅读:(40) ⋅ 点赞:(0)

  bash脚本自带处理函数:

while getopts "d:s:b:a:f:l:h" opt; do
  case $opt in
     d )  day="${OPTARG}"           ;;
     s )  dataset=${OPTARG}         ;;
     b )  backfile=${OPTARG}         ;;
     a )  maxdays=${OPTARG}         ;;
     l )  backlocaldir=${OPTARG}         ;;
     f )  full_cp_size=$(echo ${OPTARG}*1024*1024|bc)        ;;
     h )  help    ;      ;;
  esac
done

  c shell 我们也写一个,让它使用起来像: 

#!/bin/csh
set optsNoarg="dh"
while 1
  source ~/getopts.sh 
  if ( $status != 0 ) then 
    break
  endif

  switch ($opt)
    case "z":
      set dataset=($optarg)
      breaksw
    case "u":
      set backfile=($optarg)
      breaksw
    case "d":
      set fullbackdays=abc
      breaksw
    case "h":
      echo "This is a script program, please enter the parameters"
      echo "Usage:./a.sh -u 34242"
      echo '    ./a.sh -u "fsf sfsdf"'
      echo '    ./a.sh -u "fsf sfsdf" -d'
      breaksw
    default:
      echo "Invalid arg"
      breaksw
  endsw

end

echo $backfile
echo $fullbackdays
echo $dataset

getopts.sh:

#!/bin/csh
#process command line arg , -avalue --> -a value
#set opts that no args in var: optsNoarg before calling

if ( ! $?optsNoarg ) then
   set optsNoarg
endif

set optarg

if ( $#argv == 0 ) then
   exit 1
else
   set opt=`echo $argv[1]|cut -c 2`
   if (`echo $argv[1]|cut -c 1` == "-" && `echo $argv[1]|wc -L` > 2 ) then
      set opt=`echo $argv[1]|cut -c 2`
      set optarg=(`echo $argv[1]|cut -c 3-`)
      shift
   else
      if ( ! {(echo $optsNoarg | grep $opt >& /dev/null)} && $#argv > 1 ) then
         set optarg=($argv[2])
         shift
         shift
      else
         shift
      endif
   endif

   exit 0
endif


网站公告

今日签到

点亮在社区的每一天
去签到