Linux – How to make a Bash Script take an input before the script is invoked

bashlinux

Basically, you call my Bash Script by typing mybashscript in console. Then this starts:

Welcome to mybashcript! Choose an option (login|logout|view|erase|quit|):

The user then types whichever input they want, which then activates a Python Script further down in each option's respective if tree.

What I'm wondering is, how can I make it so the user only has to type (if they've used the program before) something like mybashscript login or mybashscript view.

So whatever word is added after the name of the Bash script is then taken as the first input in the script itself. Is this possible?

Here is my script so far, I don't exactly understand how to incorporate $1 without also letting it ask if there isn't an argument.

#!/bin/bash

echo -n "Hello $USER, welcome to the guestbook! Choose an option (sign|view|save|erase):     "

read option

if [ "$option" == "sign" ]; then
  python /usr/local/bin/guestbook.data/sign_guestbook.py

 elif [ "$option" == "view" ]; then
  python /usr/local/bin/guestbook.data/view_guestbook.py

 elif [ "$option" == "save" ]; then
  python /usr/local/bin/guestbook.data/save_guestbook.py

 elif [ "$option" == "erase" ]; then
  python /usr/local/bin/guestbook.data/erase_guestbook.py

 else
  echo "Sorry, I didn't understand that." 

fi

Best Answer

#!/bin/bash

case $# in
0) echo -n "Hello $USER, welcome to the guestbook! Choose an option (sign|view|save|erase):     "
   read option ;;

1) option=$1 ;;

*) echo "Sorry, I didn't understand that (too many command line arguments)"
   exit 2 ;;

esac

if [ "$option" == "sign" ]; then
  python /usr/local/bin/guestbook.data/sign_guestbook.py

elif [ "$option" == "view" ]; then
  python /usr/local/bin/guestbook.data/view_guestbook.py

elif [ "$option" == "save" ]; then
  python /usr/local/bin/guestbook.data/save_guestbook.py

elif [ "$option" == "erase" ]; then
  python /usr/local/bin/guestbook.data/erase_guestbook.py

else
  echo "Sorry, I didn't understand that." 

fi
Related Question