1

I am very new to bash scripting. I am trying to create a script which creates a local txt file that is treated as a database. The commands the user can use is: quit, add, delete, printdb. How would I create a user prompt? If the user inputs quit how would I set up the quit function to quit the script and how would I pass the user input into the function?

I have done:

#!/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 () []

But it does not recognize if the commands are not valid.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Dynamics
  • 7
  • 4
  • 2
    You really should read a tutorial. If you have already worked on a script, post it in your question. Regards – Éric May 17 '20 at 20:55
  • I posted my work so far. Apologies. – Dynamics May 17 '20 at 21:17
  • You should use a `switch` instead of `if`: https://stackoverflow.com/questions/5562253/switch-case-with-fallthrough . Regards – Éric May 17 '20 at 21:25
  • and in shell scripting, `switch` statements are expressed as `case ${answer} in quit ) exit 0 ;; setdb ) set DB=$1 ;; * ) echo Unknown option provided $* ;; esac`. Good luck. – shellter May 17 '20 at 21:53

1 Answers1

0

This shows how you can use read and case to read input.

#!/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

References:

  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.
WindChimes
  • 2,955
  • 4
  • 25
  • 26
baltakatei
  • 113
  • 5