如果队列$ name ==“已经存在”那么

时间:2013-12-04 08:56:41

标签: bash if-statement

是不是可能,我检查直到队列中的名字?

b=1      
 read -p "Enter how much databases you want to install: " COUNTER
    until [ ${a} -eq ${COUNTER} ]; do

    a=$((a+1))


    echo "What is the name for the $((b++)) database ?"
        read name

    if [ $name == "already there" ]; then
    echo " Please, don't use the same name for a database!"
    exit 1
    else
    :
    fi

我想,当名称已经存在时,脚本会退出...

任何想法?

2 个答案:

答案 0 :(得分:1)

使用双括号括起条件或双引号变量:

if [[ $name == "already there" ]]; then
    echo " Please, don't use the same name for a database!"
    exit 1
else
    #...
fi

if [ "$name" == "already there" ]; then
    echo " Please, don't use the same name for a database!"
    exit 1
else
    #...
fi

答案 1 :(得分:1)

已更新

您需要将输入的名称保存到数组中,并检查新插入的名称是否在那里。数组数组检查来自这里。 Check if an array contains a value

#!/bin/bash

has_element ()
{
  local e
  for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
  return 1
}

b=1
read -p "Enter how much databases you want to install: " COUNTER

let -a CONTAINER

a=0
until [ ${a} == ${COUNTER} ]
do
    a=$((a+1))

    echo "What is the name for the $((b++)) database ?"
    read name


    if has_element "$name" "${CONTAINER[@]}"
    then
        echo "already has"
        exit
    fi

    CONTAINER+=($name)

done

原稿。答案

我想你差不多了。修改了一些错误。

b=1
read -p "Enter how much databases you want to install: " COUNTER

a=0
until [ ${a} == ${COUNTER} ]
do
    a=$((a+1))

    echo "What is the name for the $((b++)) database ?"
    read name

    if [ "$name" == "already there" ]
    then
        echo " Please, don't use the same name for a database!"
        exit 1
    else
        echo "stay..."
    fi

done