Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass action as Parameter on Command Prompt (Linux)

Tags:

linux

bash

shell

I have written a program in linux bash and following are ways to start/stop that program:

start_program
stop_program
restart_program.

I have copied above scripts in /usr/bin so these scripts are working as command. but I want that instead of above commands I just type program name then pass action as parameter. for example if i want to start program then i should write on command prompt:

ProgramName start

if i want to uninstall then

ProgramName uninstall

if restart

ProgramName restart

so how can i make it that i just write Program name then pass action as parameter and Press enter to do that thing.

like image 816
user115079 Avatar asked May 04 '12 11:05

user115079


1 Answers

A common approach is to use a case statement:

case "$1" in
  start)
    # Your Start Code
    ;;
  stop)
    # Your Stop Code
    ;;
  restart)
    # Your Restart Code
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}" >&2
    exit 1
    ;;
esac

If your restart is just stop then start, you can do:

start() {
  # Your Start Code
}

stop() {
  # Your Stop Code
}

case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo "Usage: $0 {start|stop|restart}" >&2
    exit 1
    ;;
esac
like image 94
Sionide21 Avatar answered Oct 24 '22 02:10

Sionide21