如何在shell中测试一个变量是否等于一个数字

use*_*805 22 linux bash shell shell-script

我有这个无法正常工作的 shell 脚本。

输入:

Server_Name=1
if [ $Server_Name=1 ]; then  
echo Server Name is 1  
else
echo Server Name is not 1
fi
Run Code Online (Sandbox Code Playgroud)

输出:

Server Name is 1
Run Code Online (Sandbox Code Playgroud)

但是,如果我改变Server_Name=2,输出是:

Server Name is 1
Run Code Online (Sandbox Code Playgroud)

当我更改Server_Name为 时2,我希望它说:Server Name is 2

我知道这是if [ $Server_Name=1 ];一部分。

我如何解决它?

Iva*_*hau 37

您的脚本表明您正在使用字符串比较。

假设服务器名称可以是字符串而不是数字。

对于字符串比较
if [[ "$Server_Name" == 1 ]]; then

笔记:

  • == 周围的间距是必须的
  • 周围的间距 =必须
    if [ $Server_Name=1 ]; then是错误的

  • [[ ... ]] 减少了错误,因为在 [[ 和 ]] 之间没有发生路径名扩展或分词

  • 更喜欢引用作为“单词”的字符串

对于整数比较
if [[ "$Server_Name" -eq 1 ]]; then


更多信息:

  • `[[` 是 bash 语法,OP 正在询问 shell,它在哪里不起作用 (4认同)

Spa*_*sle 7

尝试这个:

if [ $Server_Name -eq 1 ];then
Run Code Online (Sandbox Code Playgroud)