我需要编辑 bash 脚本以选择一个字母来执行单独的命令



我不确定下一步是让命令做我想做的事情。我想选择一个字母来执行命令。现在它允许您使用任何字母。

#!/bin/bash
echo "Please select l to list files of a directory, b to backup a file or directory, u to edit a user's password, and x to exit the script"
read $answer
if [ $answer="l" ]; then
printf "Please select folder:n"
select d in */; do test -n "$d" && break; echo ">>> Invalid Selection"; done
cd "$d" && pwd
ls
fi

使用案例语句

case expression in
    pattern1 )
        statements ;;
    pattern2 )
        statements ;;
    ...
esac

例如:

case $arg in
    l)
        printf "Please select folder:n"
        select d in */; do test -n "$d" && break; echo ">>> Invalid Selection"; done
        cd "$d" && pwd
        ls
        ;;
    cmd1)
        echo "Some other cmds line 1"
        echo "Some other cmds line 2"
        ;;
    -q) exit;;
    *) echo "I'm the fall thru default";;
esac
您可以使用

内置的select,这将允许您为每个选项使用数字而不是字母,但将负责读取和验证输入:

select cmd in 
  "List files of a directory" 
  "Backup a file or directory" 
  "Edit a user's password" 
  "Exit";
do
  case $cmd in
  1) do_list_files ;;
  2) do_backup_files ;;
  3) do_edit_password ;;
  4) exit 0 ;;
  esac
done

您可以通过设置 PS3 变量(例如 PS3="Your choice? "

最新更新