DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. A Rabbit Trail: Menu-Driven Bash Script -Part II

A Rabbit Trail: Menu-Driven Bash Script -Part II

Part II of this series will set us up to see how we can incorporate the use of the MySQL command-line client into our Bash scripting.

Eli Corrales user avatar by
Eli Corrales
·
Oct. 25, 16 · Tutorial
Like (3)
Save
Tweet
Share
5.64K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

In Part 1, we took a detour from our ongoing software journey, where we have been exploring and developing, and growing some software (Shape Calculator) into  various front-end Web Applications and Web Services, in order to start a command-line, menu-driven tool that could serve us in our normal project development.

It is written as a Bash shell script, and so far, it can start and stop our local MySQL database.

I want us to see more of what's going on in our MySQL database. For instance, what databases are available. Or what tables do they contain?

This will give us the motivation to see how we can incorporate the use of the mysql command-line client into our Bash scripting. This will introduce the idea of a HERE document.  (Wierd name, I know).

Latest Scripts

Here is the latest script.

First We Change Main Menu Selection

Choose your favorite editor (I use either gvim, or vim), open that file.

Since we are going to add some new MySQL-related features, we need to change the Main Menu selection to:

    echo "|=============================================|"
    echo "|              Main Menu                      |"
    echo "|=============================================|"
    echo "|1) MySQL Utiliies                            |"
    echo "|=============================================|"
    echo "|e) Exit                                      |"
    echo "|=============================================|"


Add New Selection To MySQL Menu

Then move up the file to the MySQL Menu and add a new selection:

3) Show Databases

    echo "|=============================================|"
    echo "|             MySQL Menu                      |"
    echo "|=============================================|"
    echo "|1) Start MySQL                               |"
    echo "|2) Stop  MySQL                               |"
    echo "|                                             |"
    echo "|3) Show Databases                            |"
    echo "|=============================================|"
    echo "|b) Back                                      |"
    echo "|e) Exit This Tool                            |"
    echo "|=============================================|"


Need New Menu Function

Now... since we'll probably want to (later) do something with these databases, let's make them menu selections.   That means we need a new function.  Let's call it mysql_show_databases_menu.

#######################################################################
function mysql_show_databases_menu {
#######################################################################
while [ 1 ];
do

    echo "|=============================================|"
    echo "|             MySQL Databases Menu            |"
    echo "|=============================================|"
                   ## DATABASE NAMES GO HERE ##
    echo "|=============================================|"
    echo "|b) Back                                      |"
    echo "|e) Exit This Tool                            |"
    echo "|=============================================|"


    menu_choice="";
    read -p "Please make a selection:" menu_choice

    case $menu_choice in
        b)
            break;
            ;;
        e)
            exit 0;
            ;;
        *)
            echo;echo;
            echo "Invalid selection: $menu_choice"
            echo;echo;
            ;;
    esac
done

return 0;
#######################################################################
} # end function mysql_show_databases_menu
#######################################################################

Let's See How To 'Show Databases'

First, let's do what we want, the simple way, by using the mysql command-line client:

Image title


Above, I've shown the commands we need, and the output we would like to capture.

Do Same Thing With HERE Document

A HERE document follows this basic template:

some-command  << SOME_LABEL
  inner commands understood by the 'some-command'
  etc...
SOME_LABEL

By convention, use capital letters for the identifying label.

So, we will use the above template, wth the MySQL command-line client.

Image title

In the above image, the 'some-command' is mysql, 

and the 'SOME_LABEL'  is MYSQL,

and the 'inner commands understood by ...'  is the show databases;

Ok?  Let's run it.

Image title

Remove Unwanted Text

This looks good.  In fact, the only output we DON'T want is the heading (Database). We will eliminate that.

But first, since we want to run the above inside our script, we need to capture that output into a variable.  So let's demo that part.

Image title

You already know what a HERE doc looks like.  All we did was place it inside   $( .... ); .

That runs any series of commands in a separate shell.   Then we captured the output by assigning it to a variable   databases=$(....);  .

The end of the screenshot shows us displaying the contents of the  $databases  variable.

Now... in order to remove the Database out of it, we could do it many different ways.

One way is using the sed  command.  The most common template for this command is as follows:

 sed -e 's/<replace-this>/<with-this>/' .

Let's try it.

Image title

Cygwin(Unix/Linux) commands can be chained together, by "piping" the output of one command, into the input of another.   And the symbol to do that is the "|" (pipe).

FOR Loops

We need one more thing.  A loop.   In Bash, a for loop usually looks like so:

for avar in <some white space delimited list>;
do
     something;
done;

Let's try a simple example:

Image title

Above, we entered the for-loop script, and hit <ENTER> and it executes immediately.

We can do the same with the  $databases  variable.

Image title

Remember that the $databases  variable contained the list of databases.

Ok, we are ready to put all that we have learned into our menu-driven tool.

Updated mysql_show_databases_menu  Function

#######################################################################
function mysql_show_databases_menu {
#######################################################################
while [ 1 ];
do

# a HERE DOCUMENT, output into a local Bash variable 'databases'.
databases=$(mysql -h 127.0.0.1 -u root << 'MYSQL'
show databases;
MYSQL
)

    databases=$(echo $databases|sed 's/Database//');

    echo "|=============================================|"
    echo "|             MySQL Databases Menu            |"
    echo "|=============================================|"

    ### for-loop to display our database list, numbered.
    i=1;
    for db in $databases;
    do
    echo "| $i) $db"
    i=$((i+1));
    done

    echo "|=============================================|"
    echo "|b) Back                                      |"
    echo "|e) Exit This Tool                            |"
    echo "|=============================================|"


    menu_choice="";
    read -p "Please make a selection:" menu_choice

    case $menu_choice in
        b)
            break;
            ;;
        e)
            exit 0;
            ;;
        *)
            echo;echo;
            echo "Invalid selection: $menu_choice"
            echo;echo;
            ;;
    esac
done

return 0;
#######################################################################
} # end function mysql_show_databases_menu
#######################################################################

Test The Script


Image title

It works.  We have a list of databases.   And, later, we can make them selectable as menu items.

Latest Scripts

You can get it here.

Next

In the next "A Rabbit Trail:" article, we'll tackle how to gracefully manage the database server when hitting CTRL-C in the main script tool.

Stay tuned!

Database Bash (Unix shell) MySQL

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Stop Using Spring Profiles Per Environment
  • Introduction to Spring Cloud Kubernetes
  • Building a Real-Time App With Spring Boot, Cassandra, Pulsar, React, and Hilla
  • Microservices Testing

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: