Solved

Simple bash script to see status and restart a service using if then

Posted on 2013-05-31
7
427 Views
Last Modified: 2013-06-03
I am wondering if someone could post an example of an interactive bash script that prompts the user with a menu with 2 choices:

1.  Do you want to see service status
2.  Do you want to stop, start, restart service

If 1. show status, if 2 go to another menu.  The 2nd menu would give options for either stopping, starting, or restarting the service.

I know there are many ways to do this but I am trying to understand if this can be done using just if / then statements and if you could post the code it would help me understand as I am just starting to learn about bash scripts.
0
Comment
Question by:dmwynne
  • 3
  • 2
  • 2
7 Comments
 
LVL 78

Accepted Solution

by:
arnold earned 250 total points
ID: 39212371
#!/bin/bash

echo -n "Select to see
1 Do you want to see service status
2. Do you want to stop, start, restart the service
q: to exit
?: "
while read a; do

if [ "$a" = "q" ] ; then
   break;

elif [ "$a" = "1" ] ; then
     echo "service status is: "
elif [ "$a" = "2" ] ; then
     echo "other sub menu should appear to give you the options:"
else
     echo "You made a choice that is invalid."
     echo -n "Select to see
1 Do you want to see service status
2. Do you want to stop, start, restart the service
q: to exit
?: "
fi
done

Open in new window

0
 
LVL 34

Assisted Solution

by:Duncan Roe
Duncan Roe earned 250 total points
ID: 39212850
bash actually has a select command which can do the above rather more easily. I realize you're just starting with bash, but I advise you might as well start properly.
For a quick description of how to use select, type help select at the bash prompt. You'll see straight away how it already handles verification of the input, so you don't need to code for that (if you enter an invalid choice, you are prompted again).
select keeps prompting you for menu items until you select an item with an implementation that ends with a break command. I've assumed that in your top-level menu, you want to keep going until you select exit but level 2 is always single-shot.
#!/bin/bash

# Because we'll be testing against the choice strings,
# put them in variables so we only have to define them once.
# Use meaningful names which are still short,
# e.g. "m1a1" for Menu 1, Alternative 1.

m1a1="see service status"
m1a2="stop, start or restart the service"
m1a3="exit this menu"
m2a1="stop service"
m2a2="start service"
m2a3="restart service"

# select prompts with PS3 which by default is "#?" (i.e. "which number").
# We can make it a little more user-friendly,
PS3="Enter the number of your choice> "

# After displaying the sub_menu,
# you really want to re-display the top_level menu.
# Hence this loop
while true
do

  echo "Here's what you can do:"

# We must use quotes because the variables expand to strings with spaces in them.
# This applies from now on.
select i in "$m1a1" "$m1a2" "$m1a3"
  do
  if [ "$i" = "$m1a1" ]; then

# This is stub code.
# In case you didn't know,
# a stub is where you display a message
# because you haven't written the actual code yet.
    echo service status stub

  fi
  if [ "$i" = "$m1a2" ]; then
    select i in "$m2a1" "$m2a2" "$m2a3"
    do
      if [ "$i" = "$m2a1" ]; then
        echo service stop stub
        break
      elif [ "$i" = "$m2a2" ]; then
        echo service start stub
        break
      elif [ "$i" = "$m2a3" ]; then
        echo service restart stub
        break
      fi
    done

# This is a little tricky:
# we want the outer menu to be repeated now,
# but if we took no special action then all we would get is another prompt
# (for a choice from the outer menu).
# That would be really confusing,
# so break from the outer menu here -
# it will be re-displayed becuse of the while loop.
    echo    # Output a blank line
    break
  fi

# This is a concise alternative to using the if command.
# It's particularly suitable when the command to be executed is a 1 -liner,
# although you can do multiple lines using curly braces,
# and many project managers prefer to have scripts written that way.
# Again I'm thinking of what you'd be well-advised to learn,
# rather than sticking to the constraints of your question.
# The "&&" says to obey the 2nd command if the first command succeeds,
# i.e. if the test passes.
# "&&" along with its partner "||" has many other uses -
# post back if you'd like me to describe a few.
[ "$i" = "$m1a3" ] && exit

  done
done

Open in new window

A bit more than you asked for, but considering the extra functionality it's only gone from21 lines in the preceding post to 35 (after removing comments and blank lines).
0
 
LVL 34

Expert Comment

by:Duncan Roe
ID: 39212856
In answer to your original question can this be done using just if / then statements I would have to say the answer is no. Restricting yourself to only a few statements can make things very hard, and you often can't get what you really want.
By the way, here's some output from my previous post
22:36:28$ ./ee102.sh 
Here's what you can do:
1) see service status                  3) exit this menu
2) stop, start or restart the service
Enter the number of your choice> 2
1) stop service
2) start service
3) restart service
Enter the number of your choice> 4
Enter the number of your choice> 3
service restart stub

Here's what you can do:
1) see service status                  3) exit this menu
2) stop, start or restart the service
Enter the number of your choice> 3
22:46:31$ ./ee102.sh 
Here's what you can do:
1) see service status                  3) exit this menu
2) stop, start or restart the service
Enter the number of your choice> 1
service status stub
Enter the number of your choice> 2
1) stop service
2) start service
3) restart service
Enter the number of your choice> 1
service stop stub

Here's what you can do:
1) see service status                  3) exit this menu
2) stop, start or restart the service
Enter the number of your choice> 2
1) stop service
2) start service
3) restart service
Enter the number of your choice> 2
service start stub

Here's what you can do:
1) see service status                  3) exit this menu
2) stop, start or restart the service
Enter the number of your choice> 2
1) stop service
2) start service
3) restart service
Enter the number of your choice> 3
service restart stub

Here's what you can do:
1) see service status                  3) exit this menu
2) stop, start or restart the service
Enter the number of your choice> 3
22:57:17$ 

Open in new window

0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 14

Author Comment

by:dmwynne
ID: 39212857
So I ran the script and selected option 2 and it gave me "other sub menu should appear to give you the options:" line.  Shouldn't it display option 2.  Do you want to stop...

Also how do I get the command to run when they select option 1.  So the user picks 1 to see service status, how do I actually put the command service sshs status or something in the script?
0
 
LVL 78

Expert Comment

by:arnold
ID: 39212924
The script was an example and not a functional one.
The detail on what to do when an option is selected requires a process. i.e. if the service is running, prompt to stop/restart
if the service is stopped, option to start
this is why the selection of option 2 would in general require a sub-menu display
The current status is X
what do you want to do:
1. st

etc.

For whom are you creating this script/process?  Usually service management can only be done by those who have elevated or root rights.
0
 
LVL 14

Author Comment

by:dmwynne
ID: 39212955
Arnold - thank you.  This is a script for me to use on a Centos box I admin.  This was really an exercise for me to learn something that I was having trouble grasping, being new to scipting.  I know Linux well enought to get a box up and running and to perform a function like monitor with nagios or backup machines but want to expand my knowledge to scripting.  Thanks for your help.

duncan_roe - thanks.  I really appreciate you providing the detailed answer you did.  I am going to split points because you both helped me very much.

Thanks
0
 
LVL 78

Expert Comment

by:arnold
ID: 39212979
Look at any if the startup scripts in /etc/init.d
 
There are many learn bash scripting sites/examples.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to know the backup date of a restored DB? 4 46
SMTP log file for IMSVA 5 26
Ruby or Python 7 41
Move files based on file names? 8 16
Utilizing an array to gracefully append to a list of EmailAddresses
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

679 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question