shell处理用户输入总结

时间:2022-06-22
本文章向大家介绍shell处理用户输入总结,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

版权声明:本文为木偶人shaon原创文章,转载请注明原文地址,非常感谢。 https://blog.csdn.net/wh211212/article/details/81865144

处理简单选项

#/bin/bash
# extracting command line options as parameters

echo
while [ -n "$1" ]
do
  case "$1" in
    -a) echo "Found the -a option" ;;
    -b) echo "Found the -b option" ;;
    -c) echo "Found the -c option" ;;
    *) echo "$1 not an option";;
    esac
    shift
 done

分离参数与选项

#/bin/bash
# extracting options and parameters
echo
while [ -n "$1" ]
do
  case "$1" in
    -a) echo "Found the -a option" ;;
    -b) echo "Found the -b option" ;;
    -c) echo "Found the -c option" ;;
    --) shift
        break ;;
     *) echo "$1 not an option";;
    esac
    shift
 done 
 #
 count=1
 for param in "$@"
 do
   echo "Parameter #$count: $param"
   count=$[ $count + 1 ]
 done

处理带值的选项

#/bin/bash
# extracting command line and values
echo
while [ -n "$1" ]
do
  case "$1" in
    -a) echo "Found the -a option" ;;
    -b) param="$2"
        echo "Found the -b option,with parameter value $param"
        shift ;;
    -c) echo "Found the -c option" ;;
    --) shift
        break ;;
     *) echo "$1 not an option";;
    esac
    shift
 done 
 #
 count=1
 for param in "$@"
 do
   echo "Parameter #$count: $param"
   count=$[ $count + 1 ]
 done

使用getopt命令

  • getopt ab:cd -a -b test1 -cd test2 test3
 #/bin/bash
# extracting command line and values with getopt
set -- $(getopt -q ab:cd "$@")
#
echo
while [ -n "$1" ]
do
  case "$1" in
    -a) echo "Found the -a option" ;;
    -b) param="$2"
        echo "Found the -b option,with parameter value $param"
        shift ;;
    -c) echo "Found the -c option" ;;
    --) shift
        break ;;
     *) echo "$1 not an option";;
    esac
    shift
 done 
 #
 count=1
 for param in "$@"
 do
   echo "Parameter #$count: $param"
   count=$[ $count + 1 ]
 done
  • getopts
#!/bin/bash
# simple demonstration of the getopts command
#
echo
while getopts :ab:c opt
do
  case "$opt" in
    a) echo "Found the -a option" ;;
    b) echo "Found the -b option",with value $OPTARG ;;
    c) echo "Found the -c option" ;;   
    *) echo "Unknown option:  $opt" ;;
  esac
done 
  • 未完待续……