0

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

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"
   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
noober
  • 1,427
  • 3
  • 23
  • 36
  • 2
    Why are you exporting the variables in the first place? You only need to export a variable if it's going to be used by a program you run from the shell. – Barmar Apr 27 '16 at 20:59
  • I tried your script, it worked fine. Are you sure you gave a `-d` option when you ran the script? – Barmar Apr 27 '16 at 21:04
  • The only variable that didn't show was `$SCHEMAMAIN` because I didn't have `$dbname__source` exported. – Barmar Apr 27 '16 at 21:05
  • 2
    `SCHEMAMAIN` is being set *well* before `dbname` can be given a value. Is this just an ordering problem? Are you expecting `$dbname` in the `SCHEMAMAIN` assignment to be expanded only *after* you assign to `dbnam` in the `getopts` case? Also `$dbname__source` is seen as a single variable. If you want that to be `${dbname}__source` you need the brackets. – Etan Reisner Apr 27 '16 at 21:09
  • As an aside, options should be used to specify *optional* things. – tripleee Apr 28 '16 at 08:18

1 Answers1

1

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.

totoro
  • 2,469
  • 2
  • 19
  • 23