Reputation: 85
I want to send a number of predefined queries to mysql. i will use the variable defined internally by using the externally inputted variable as below. But not good.
[testuser@testserver work]$ cat test1.sh
#!/bin/sh
query1='select * from mysql.user limit 2;'
query2="select * from mysql.user limit 2;"
echo $1
echo "$1"
#mysql -uuser-p -e "$1"
this is result
[testuser@testserver work]$ sh test3.sh query1
query1
query1
but i want result
[testuser@testserver work]$ sh test1.sh query1
select * From mysql.user limit 1
how to modify this bash scrpit?
Upvotes: 1
Views: 1965
Reputation: 2488
Can also use a case statment:
#!/usr/bin/env bash
case "$1" in
--query1)
echo "select * from mysql.user limit 1;"
;;
--query2)
echo "select * from mysql.user limit 2;"
;;
*)
echo "unkown option"
exit 1
;;
esac
then run something like: ./test --query1
Upvotes: 1
Reputation: 70742
Try simply:
#!/bin/bash
query1='select * from mysql.user limit 2;'
query2="select * from mysql.user limit 2;"
echo "${!1}"
#mysql -uuser-p -e "${!1}"
But you could:
#!/bin/bash
queries=('select * from mysql.user limit 2;'
"select * from mysql.user limit 2;")
echo "${queries[$1]}"
#mysql -uuser-p -e "${queries[$1]}"
Then run ./test 0
or ./test 1
.
Or even
#!/bin/bash
declare -A queries=$'(
[query1]=\047select * from mysql.user limit 2;\047
[query2]="select * from mysql.user limit 2;")'
echo "${queries[$1]}"
#mysql -uuser-p -e "${queries[$1]}"
Note: Syntax $'....\047...\047...'
is a trick for using simple quotes in quoted string.
Then run ./test3 query1
.
Upvotes: 4
Reputation: 766
You can add the following lines:
#!/bin/bash
query1='query 1'
query2='query 2'
eval var="$"$1
echo $var
Edit: This uses eval which should be avoided, which might be unsafe if you don't trust the data. There is for Bash scripts variable indirection via the mechanism "${!VARNAME}", so you can use "${!1}".
Upvotes: 0