shell 带有用户提示符的Bash脚本

nwnhqdif  于 2023-03-30  发布在  Shell
关注(0)|答案(1)|浏览(95)

我是bash脚本的新手。我正在尝试创建一个脚本,它会创建一个本地txt文件,该文件被视为数据库。用户可以使用的命令是:quit,add,delete,printdb.如何创建用户提示符?如果用户输入quit,我如何设置quit函数来退出脚本,以及如何将用户输入传递到函数中?
我已完成:

#!/bin/bash
func () {
echo -n "% "
read answer
}
if [ $answer != "quit" ] && [ $answer != "setdb" ] && [ $answer != "add" ] && [ $answer != "delete" ] && [
$answer != "printdb" ]
then
 echo "Unrecognised command"
 func
else
 echo -n "%"
fi


#quit () {}

#setdb (){}

#add () {}

#delete () {}

#printdb () []

但它不识别命令是否无效。

0vvn1miw

0vvn1miw1#

这展示了如何使用readcase读取输入。

#!/bin/bash
while true; do
      echo -n "Enter command."
      read -r m
      case $m in
      quit) exit 0 ;; # exit without error
      add) echo "New line" >> printdb.txt ;; # add new line
      delete) sed -i '$d' printdb.txt ;; # delete last line
      printdb) cat printdb.txt ;; # show file
      *) echo "ERROR:Unknown command".; exit 1 ;; # handle invalid command
      esac
done

参考文献:

  1. read manual page
  2. Prompt user for input with read .
  3. How to program responses from read with case .
  4. How to delete a line from a file by line number with sed .
  5. Tool for getting suggestions while debugging your bash code.

相关问题