skip to Main Content
DB_USER = 'db_user'
DB_PASS = 'db_pass'
DB_HOST = 'db_host'
DB = 'db'

function dbConnection() {
 echo "$1" | mysql -u${DB_USER} -p${DB_PASS} -h${DB_HOST} ${DB} -N
}

Request you to ignore the actual values of the db variables.
I wanted to understand the meaning of the above method. I have the following doubts:

  1. What is echo "$1" doing here?
  2. Why are we using the pipe operator?
  3. And what is the relation between the echo command and the mysql command?

2

Answers


  1. mysql is able to read queries from stdin and | connects the stdout of the left-hand side command to the stdin of the right-hand side command. So echo "$1" will write a query (the first argument passed to dbConnection) to stdout which will be then read by the mysql command from its stdin.

    Login or Signup to reply.
  2. Try passing it some valid SQL.

    dbConnection "SELECT 1+2;"
    

    The string passed becomes the argument passed in.

    echo "$1"
    

    becomes (effectively)

    echo "SELECT 1+2;"
    

    which the pipe then connects to mysql`’s stdin – it becomes the input to the program.

    It’s the script to execute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search