noober noober - 7 months ago 19
Bash Question

unable to echo value after exporting variable using getopts

I'm trying to figure out in my script, why my variable

dbname
isn't being set when using
getopts
after explicitly doing an export on that variable. I tried do an echo,
echo $dbname
and its the only variable that doesn't have a value. Here's my code in progress:

#!/bin/bash

# Setup VARS
export SCHEMAMAIN="$dbname__source"
export OLD="/tmp/Old.out"
export NEW="/tmp/New.out"
PSQL=$(which psql)

usage () {
echo "Usage: $0 -o oldhosts" -d dbname -t table -n newhosts""
}

while getopts ":o:d:t:n:" opt; do
case $opt in
o) oldhosts="$OPTARG";;
d) export dbname=${OPTARG};;
t) export table=${OPTARG};;
n) newhosts="$OPTARG";;
*) echo "Error unknown option -$OPTARG"
usage
exit 1
;;
esac
done

if [[ $oldhosts == 'hosts1' ]]; then
HOST="myevents-01.foobar.au-fareast-1.foobar.amazonaws.com"
elif [[ $oldhosts == 'hosts2' ]]; then
HOST="myevents-02.foobar.au-fareast-1.foobar.amazonaws.com"
else
echo "Old source hosts is incorrect:"
exit 1
fi

if [[ $newhosts == 'hosts3' ]]; then
HOST2="myhost-foobar-hosts-3-foobarhosts-1vjldgvvna7.foobar.au-fareast-1.foobar.amazonaws.com"
elif [[ $newhosts == 'hosts4' ]]; then
HOST2="myhost-foobar-hosts-4-foobarhosts-1dy7izxwwol.foobar.au-fareast-1.foobar.amazonaws.com"
elif [[ $newhosts == 'hosts5' ]]; then
HOST2="myhost-foobar-hosts-5-foobarhosts-krovbibhvo.foobar.au-fareast-1.foobar.amazonaws.com"
else
echo "New hosts is incorrect:"
exit
fi


echo "$HOST"
echo "$dbname"
echo "$SCHEMAMAIN"
echo "$table"
"$PSQL" -h "$HOST" -U masteruser -d "$dbname" -p 5439 << EOF
\a
\t
\o $OLD
SELECT column_name
FROM information_schema.columns
WHERE table_schema = '$SCHEMAMAIN'
AND table_name = '$TBL'
order by ordinal_position;
EOF


echo "$HOST2"
"$PSQL" -h "$HOST2" -U masteruser -d "$dbname" -p 5439 << EOF
\a
\t
\o $NEW
SELECT column_name
FROM information_schema.columns
WHERE table_schema = '$SCHEMAMAIN'
AND table_name = '$TBL'
order by ordinal_position;
EOF

Answer

What if you run the getopts loop at the top of the file and change

export SCHEMAMAIN="$dbname__source"

to

export SCHEMAMAIN="${dbname}__source"

?

Edit

@EtanReisner made a comment on it already.