if语句在shell脚本中检查$ HOSTNAME

时间:2021-03-02 23:49:33

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!

我肯定知道$ HOSTNAME是foo,所以我不确定问题是什么。虽然我很吵。任何帮助,将不胜感激!谢谢!

2 个解决方案

#1


46  

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

用于比较shell中的字符串的POSIX和可移植方式是

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

#2


0  

You're missing a space after the opening bracket. It's also good "not to parse" the variable content using double quotes :

在开始括号后你错过了一个空格。使用双引号“不解析”变量内容也很好:

if [ "$HOSTNAME" = "foo" ]; then 
...

#1


46  

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

用于比较shell中的字符串的POSIX和可移植方式是

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

#2


0  

You're missing a space after the opening bracket. It's also good "not to parse" the variable content using double quotes :

在开始括号后你错过了一个空格。使用双引号“不解析”变量内容也很好:

if [ "$HOSTNAME" = "foo" ]; then 
...