sh script does not have ${RANDOM} value which generates random value if used in bash script. Below is sample code explains how to use ${RANDOM} and define functions in bash scripts.
*** sample code (makeData.sh) ***
#!/bin/bash*** output from above script ***
function create_db(){
dbname=$1
dbuser=$2
dbpass=$3
PGPASSWORD=${dbpass} dropdb -U ${dbuser} ${dbname}
PGPASSWORD=${dbpass} createdb -U ${dbuser} ${dbname}
}
function create_tbl(){
id=0
dbname=$1
dbuser=$2
dbpass=$3
dbtable=$4
sql="CREATE TABLE ${dbtable} (id text, value int);"
PGPASSWORD=${dbpass} psql -U ${dbuser} -d ${dbname} -c "${sql}"
while [ ${id} -le 3 ]
do
id=`expr ${id} + 1`
sql="INSERT INTO ${dbtable} VALUES (${id}, ${RANDOM});"
PGPASSWORD=${dbpass} psql -U ${dbuser} -d ${dbname} -c "${sql}"
done
}
function select_tbl(){
dbname=$1
dbuser=$2
dbpass=$3
dbtable=$4
sql="SELECT * FROM ${dbtable};"
PGPASSWORD=${dbpass} psql -U ${dbuser} -d ${dbname} -q -c "${sql}"
}
function main(){
dbname=$1
dbuser=$2
dbpass=$3
create_db ${dbname} ${dbuser} ${dbpass}
sn=0
prefix="table_"
while [ ${sn} -le 23 ]
do
dbtable=${prefix}${sn}
create_tbl ${dbname} ${dbuser} ${dbpass} ${dbtable}
select_tbl ${dbname} ${dbuser} ${dbpass} ${dbtable}
sn=`expr ${sn} + 1`
done
}
# Program starts here!!!
if [ $# -ne 3 ]; then
echo "usage: bash $0 dbname dbuser dbpass"
exit
fi
main $1 $2 $3
yaboo@maniac:~$ bash makeData.sh mydb test test
id | value
----+-------
1 | 632
2 | 5999
3 | 3495
4 | 3127
(4 行)
id | value
----+-------
1 | 29475
2 | 7581
3 | 17044
4 | 12726
(4 行)
id | value
----+-------
1 | 13619
2 | 25982
3 | 21835
4 | 23054
(4 行)
id | value
----+-------
1 | 726
2 | 15405
3 | 16549
4 | 16405
(4 行)
id | value
----+-------
1 | 14362
2 | 22030
3 | 16364
4 | 24379
(4 行)
...
id | value
----+-------
1 | 8468
2 | 10413
3 | 12345
4 | 30637
(4 行)
id | value
----+-------
1 | 8372
2 | 16466
3 | 31683
4 | 23073
(4 行)
yaboo@maniac:~$
No comments:
Post a Comment