使用getopts导出变量后无法回显值

时间:2016-04-27 20:57:28

标签: bash shell unix getopts

我试图在我的脚本中弄清楚为什么在明确对该变量进行导出后使用dbname时未设置变量getopts。我尝试做一个echo,echo $dbname,它是唯一没有值的变量。这是我正在进行的代码:

#!/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

1 个答案:

答案 0 :(得分:1)

如果您在文件顶部运行getopts循环并更改

,该怎么办?
export SCHEMAMAIN="$dbname__source"

export SCHEMAMAIN="${dbname}__source"

修改

@EtanReisner已就此发表评论。