我正在使用psql来获取已经在我的机器上运行的数据库的列表,以及一个具有数据库名称列表的用户定义的变量。如何检查用户定义的变量是否包含已经作为数据库存在的名称? 这是我到目前为止所做的,但结果不一致
x=`psql -l | awk '{print $1}' | grep -v "+" | grep -v "Name" | grep -v "List" | grep -v "(" | grep -v "template" | grep -v "postgres" | grep -v "|" | grep -v ":"`
db_name=test1,test2
array=(${x})
for i in "${array[@]}"
do
for db in $(echo ${db_name} | tr ',' ' '); do
if [[ ${i} != ${db} ]] ; then
echo ${db} "Does not exists"
fi
done
答案 0 :(得分:0)
尝试一下:
DB_LIST=$(psql -l | awk '{print $1}' | grep -v "+" | grep -v "Name" | grep -v "List" | grep -v "(" | grep -v "template" | grep -v "postgres" | grep -v "|" | grep -v ":")
for DB_NAME in test1 test2
do
DB_COUNT=$(echo $DB_LIST|grep $DB_NAME|wc -l)
if [ $DB_COUNT -eq 1 ]; then
echo $DB_NAME exists
fi
done
答案 1 :(得分:0)
只需创建两个数组,然后像Array intersection in bash中那样获得它们的交点
sqlist=($(psql -l | awk '$1 !~ /[+(|:]|Name|List|template|postgres/ {print $1}'))
userlist=(test1 test2)
intersection=()
for sqitem in "${sqlist[@]}"; do
for usitem in "${userlist[@]}"; do
if [[ $sqitem = $usitem ]]; then
intersection+=("$sqitem")
fi
done
done
printf '%s\n' "${intersection[@]}"
还请注意,简化了原始psql
后处理中的useless uses of grep
。