1

Inside script I have SQL queries which I execute. But I would like to do a variable which indicates what exact SQL script I want to run. For example:

#!/bin/bash

SQL1 = "Select * from dual"

SQL1 = "Select sysdate from dual"

SQL3 = "Select sysdate+1 from dual"

Now, I would like to run a script eg. ./script.sh 2 - > which indicates that I want to run second SQL query.

Probably the easiest way is to do it this way:

if [ $1 = 1 ] then
SQL1 = "Select * from dual"
if [ $1 = 2] then
SQL2 = "Select sysdate from dual"
if [ $1 = 3] then
SQL3 = "Select sysdate+1 from dual"
fi fi fi

Now, the question is, what if I want to run all of them, so I will run my script: ./script.sh (without variable).

I know I cant use [-z] but, I don't want to repeat SQL queries eg.

if [ $1 = 1 ] then
    SQL1 = "Select * from dual"
    if [ $1 = 2] then
    SQL2 = "Select sysdate from dual"
    if [ $1 = 3] then
    SQL3 = "Select sysdate+1 from dual"
    fi fi fi
if [ -z $1 ] then
SQL1 = "Select * from dual"

and so on... How to handle with that ?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
bazyl
  • 263
  • 1
  • 7
  • 17

2 Answers2

4

Why don't you use an array and check if the index exists or not and act accordingly?

See it just printing:

#!/bin/bash

commands=("SELECT 1" "SELECT 2" "SELECT 3")
line=$(($1 - 1))
[ "${commands[$line]+abc}" ] && echo "${commands[$line]}" || printf "%s\n" "${commands[@]}"

This uses the nice trick to check an index or a key in an array.

Let's execute it:

$ ./myscript.sh 5
SELECT 1
SELECT 2
SELECT 3
$ ./myscript.sh 2
SELECT 2
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

you can check the number of arg instead of -z.

if [ $# -eq 0 ]; then .....