shell输入参数和内部菜单实现

@果酱  April 18, 2024

在shell外的参数,生成usage

#!/usr/bin/env bash

# grep " .)\ #" $0 === grep " .)\ #" 文件名, 打印出对应行
#    p)# Specify p value.
#    s)# Specify strength, either 45 or 90.
#    h|*)# Display help.
usage() { echo "$0 usage:" && grep " .)\ #" $0; exit 0; }

[ $# -eq 0 ] && usage

while getopts ":hs:p:" arg; do
        echo "arg is ${arg} option is ${OPTARG}"
  case $arg in
    p) # Specify p value.
      echo "p is ${OPTARG}"
      ;;
    s) # Specify strength, either 45 or 90.
      strength=${OPTARG}
      [ $strength -eq 45 -o $strength -eq 90 ] \
        && echo "Strength is $strength." \
        || echo "Strength needs to be either 45 or 90, $strength found instead."
      ;;
        :)#指令缺少参数
          echo "Option -$OPTARG requires an argument." >&2
          exit 1
          ;;
    h | *) # Display help.
      usage
      exit 0
      ;;
  esac
done

进入shell里面生成菜单

#! /bin/bash

read -a names
echo ${names[0]} ${names[1]}

function select_test(){
        echo ' '
        PS3='go select: '

        options=("a" "quit")
        echo "$options"
        echo "${options[@]}"
        select opt in "${options[@]}"
        do
                case $opt in
                        "a")
                                echo 'you select a';break;
                                ;;
                        "quit")
                                exit 0;
                                ;;
                        *)
                                echo 'invaild option $REPLY'
                                ;;
                esac
        done
}

https://github.com/haoel/cpu-cache/blob/master/test.sh
https://linuxize.com/post/bash-select/
https://web.archive.org/web/20200507131743/https:/wiki.bash-hackers.org/howto/getopts_tutorial


添加新评论