Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement to check $HOSTNAME in shell script

So I want to set some paths differently depending on the host, but unfortunately it's not working. Here is my script:

if [$HOSTNAME == "foo"]; then     echo "success" else     echo "failure" fi 

This is what happens:

-bash: [foo: command not found failure 

I know for certain that $HOSTNAME is foo, so I'm not sure what the problem is. I am pretty new to bash though. Any help would be appreciated! Thanks!

like image 246
Nicole Avatar asked Apr 12 '13 13:04

Nicole


People also ask

What is $? == 0 in shell script?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.

What is == in shell script?

== is a bash-specific alias for = and it performs a string (lexical) comparison instead of a numeric comparison.

How do you check if it is a directory in shell?

One can check if a directory exists in a Linux shell script using the following syntax: [ -d "/path/dir/" ] && echo "Directory /path/dir/ exists."


2 Answers

The POSIX and portable way to compare strings in the shell is

if [ "$HOSTNAME" = foo ]; then     printf '%s\n' "on the right host" else     printf '%s\n' "uh-oh, not on foo" fi 

A case statement may be more flexible, though:

case $HOSTNAME in   (foo) echo "Woohoo, we're on foo!";;   (bar) echo "Oops, bar? Are you kidding?";;   (*)   echo "How did I get in the middle of nowhere?";; esac 
like image 93
Jens Avatar answered Sep 20 '22 18:09

Jens


#!/bin/bash  if [[ $(hostname) == "home" ]] || [[ $(hostname) == "home2" ]]; then     echo "True" fi 
like image 34
alper Avatar answered Sep 21 '22 18:09

alper