-1

I am writing a shell script which takes 1 parameter table name. Inside the same shell script I have a db2 query - "Select * from table_name". I want to provide a table name for db2 query which I received from shell script parameter. How do I achieve this.

My Script so far -

    echo "Content Display"
        while [ -n "$1" ]; do
          case "$1" in
          -f) echo "File mode has selected" ;;
          --)
          shift
          break
          ;;
    esac
    shift
    done
    param = "$1"
    db2 "select * from 'param'"
  • Could you post your script so far to give people a starting point and see exactly what you're trying to do? without that the most useful thing people can do is probably just link you to documentation. – Ryan Oct 25 '19 at 20:18
  • Sorry my bad, updated the post – mandar munagekar Oct 25 '19 at 20:28
  • Is your question "how do I use a variable in a string in bash?" – that other guy Oct 25 '19 at 20:48
  • I am storing value received from parameter into a variable called param. I want to use the variable in db2 query. So basically user will provide a table name and I want to return contents of the table by running a db2 select query on it. – mandar munagekar Oct 25 '19 at 20:52
  • I think you mean `db2 "select * from ${param}"` instead of `db2 "select * from 'param'"`? – richyen Oct 25 '19 at 20:55

2 Answers2

1

To expand a variable in a double quoted string, just put a $ in front of the variable name:

param="world"
echo "Hello $param"

In your case:

param="$1"
db2 "select * from $param"

If you ever need to disambiguate, you can use ${}:

param="29"
echo "It is $paramC outside"  # Wrong, accesses $paramC
echo "It is ${param}C outside # Right, accesses $param and appends the letter C
that other guy
  • 116,971
  • 11
  • 170
  • 194
1

Here would be a sample shell script based on your requirement. It is verifed on AIX and Linux.

  1. Save below as prep.sh, run "chmod 777 prep.sh" and execute it.
#!/bin/sh

# prepare objects for test
db2 -v "drop db db1"
db2 -v "create db db1"
db2 -v "connect to db1"
db2 -v "create table hotel (c1 char(20))"
db2 -v "insert into hotel values ('Nice hotel')"
db2 -v "insert into hotel values ('Good hotel')"
db2 -v "insert into hotel values ('Fancy hotel')"
db2 -v "terminate"
  1. Save below as get.sh and run "chmod 777 get.sh".
#!/bin/sh

if [ -z "$1" ] ; then
  echo "no table name"
  exit
else
  tabname=$1
fi

db2 -v "connect to db1"
db2 -v "select * from $tabname"
db2 -v "terminate"
  1. Execute get.sh as below:

./get.sh hotel

Note: It connects database db1, select hotel table and then returns three rows as below:

C1
--------------------
Nice hotel
Good hotel
Fancy hotel

  3 record(s) selected.

Hope this helps.

hidehy
  • 179
  • 5