Pass action as Parameter on Command Prompt (Linux)
Question
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.
Solution
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
OTHER TIPS
Sionide21 has it right.
There is a great little write up on this over here:
Here is an alternative to a case statement.
Start/Stop/restart/uninstall your program with an Argument using if statement in bash/shell.
#!/bin/bash
start_module() {
# Your start Code
}
stop_module() {
# Your stop Code
}
restart_module() {
# Your restart Code
}
uninstall_module() {
# Your uninstall Code
}
if [ $# != 1 ]; then # If Argument is not exactly one
echo "Some message"
exit 1 # Exit the program
fi
ARGUMENT=$(echo "$1" | awk '{print tolower($0)}') # Converts Argument in lower case. This is to make user Argument case independent.
if [[ $ARGUMENT == start ]]; then
start_module
elif [[ $ARGUMENT == stop ]]; then
stop_module
elif [[ $ARGUMENT == uninstall ]]; then
uninstall_module
elif [[ $ARGUMENT == restart ]]; then
restart_module
else
echo "Only one valid argument accepted: START | STOP | RESTART | UNINSTALL
case doesn't matter. "
fi
Save this code into myScript.sh
Usage:
./myScript.sh Start
./myScript.sh Stop
./myScript.sh check
./myScript.sh uninstall
Here is an example of a real-world program that embodies this style of execution.
Side-Note: Omitting any existing module/functionality or adding another can be done easily.
How to take out/suppress a specific module from running (say for maintenance)?
Taking out a specific module off if statement block will disable it since that module won't be called during runtime.