如何在变量中保存案例值

如何在变量中保存案例值
selection=

until [ "$selection" = "0" ]; do

  echo ""
  echo "PROGRAM MENU"
  echo "1 - display free disk space"
  echo "2 - display free memory"
  echo ""
  echo "0 - exit program"
  echo ""
  echo -n "Enter selection: "
  read selection
  echo ""
  case $selection in
      1 ) df ;;
      2 ) free ;;
      0 ) exit ;;
      * ) echo "Please enter 1, 2, or 0"
  esac
echo $selection

done

如果我按 2,它会显示可用空间,而 echo 显示 2,但我需要 echo 是“空闲”。

答案1

你不能。 case 语句使用选择来决定要做什么。它不是由 case 语句设置的。

您可能想尝试这样的事情:

selection=

until [ "$selection" = "0" ]; do

  cmd=''

  echo ""
  echo "PROGRAM MENU"
  echo "1 - display free disk space"
  echo "2 - display free memory"
  echo ""
  echo "0 - exit program"
  echo ""
  echo -n "Enter selection: "
  read selection
  echo ""

  case "$selection" in
      1) cmd='df' ;;
      2) cmd='free' ;;
      0) cmd='exit' ;;
      *) echo "Please enter 1, 2, or 0"
  esac

  if [ -n "$cmd" ] ; then 
    echo "selection $selection is '$cmd'"
    $cmd
  fi

done

注意,它会echo "selection $selection is '$cmd'在执行之前运行$cmd,否则会在echowhen$selection为0之前退出。

答案2

我将这样做。可能有帮助/有指导意义。

#!/bin/bash

menu() {
  cat >&2 <<EOF

PROGRAM MENU

1 - display free disk space
2 - display free memory

0 - exit program

EOF
}

while true; do
  menu
  read -p "Enter selection: " selection
  case "$selection" in
    1)
      echo df
      df
      ;;
    2)
      echo free
      free
      ;;
    0)
      echo exit
      exit
      ;;
    *)
      echo "Please enter 1, 2 or 0" >&2
      ;;
  esac
done

答案3

如果我按 2 它显示可用空间并且 echo 显示 2 但我需要 echo 是“空闲”

因此,目前免费echo $selection打印2,而您希望打印free。在这种情况下,请替换:

  2 ) free ;;

和:

  2 ) free; selection=free ;;

将变量selection设置为 string free,这会导致echo命令打印您想要的内容。

选择

作为另一种选择,但是不是作为精确替代,bash 命令select可用于通过更短的代码完成类似的操作:

PS3="Please enter 1, 2, or 3: "
select selection in "display free disk space" "display free memory" "exit program"
do
  case "$selection" in
      "display free disk space") df ;;
      "display free memory") free; selection=free ;;
      "exit program") exit ;;
  esac
  echo $selection
done

相关内容