1

This question already has an answer here:

I have a requirement to perform specific set of tasks based on server , So I want to have the condition(s) defined based on server. Here is the script I came up with and I have read multiple blogs and couldn`t find any mistake from my script. Can you guide on what I am overlooking here ?

#!/bin/bash
SERVER_NAME=`hostname -s`
hostname -s
DBServer=(servr1 servr2 servr3 servr4)
#AppServer=[hqidlfdiwa01 , hqiqlfdiwa01]
echo "Values of DBServer seeing is ${DBServer[*]}"
Values of DBServer seeing is servr1 servr2 servr3 servr4
for i in ${DBServer[*]}
do
  echo "current value in I is $i"
  echo "The server name found is $SERVER_NAME"
  if [$SERVER_NAME == $i]
  then
    echo "I am on one of the servers and it is $i"
  fi
done

Output I see on server is

current value in I is servr1
The server name found is servr1
-bash: [servr1: command not found
current value in I is servr2
The server name found is servr1
-bash: [servr1: command not found
current value in I is servr3
The server name found is servr1
-bash: [servr1: command not found
current value in I is servr4
The server name found is servr1
-bash: [servr1: command not found

marked as duplicate by steeldriver, Kusalananda bash May 10 at 5:46

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Whenever you have a shell script error, a good first step is to cut and paste your code into shellcheck.net and correct the errors (important) and warnings (might be important) that it identifies. If you have trouble understanding its messages, then come here and ask. – John1024 May 10 at 4:00
  • 1
    @John1024 this is a life saver. I never knew this is existed. – Vajra May 10 at 4:35
2

In shell, spaces matter.

Replace:

if [$SERVER_NAME == $i]

with:

if [ "$SERVER_NAME" = "$i" ]

Without the spaces, the shell thinks that you want to run a command named [$SERVER_NAME (such as [servr1) with arguments == and $i]. With the space, the shell runs the test command, denoted by [.

Also, always place shell variables in double quotes unless you understand what shell expansions would be applied and you explicitly want them to be applied.

Lastly, while bash accepts either == or = to mean string-equal inside [...], other shells only understand =. For portability, it is best practice to use = for string-equal inside [...].

  • 1
    Thank you for the answer and the Tips , really helpful . – Vajra May 10 at 4:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.