本文介绍了为什么等于运营商如果不受空间环绕不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下面的脚本

#!/bin/bash
var1="Test 1" 
var2="Test 2"
if [ "$var1"="$var2" ] 
  then 
    echo "Equal" 
  else 
    echo "Not equal"
fi

这让我对等于。虽然它应该有印刷不等于

只有当我周围插入 = 的空间,它的工作如预期

Only when I inserted space around = it worked as intended

if [ "$var1" = "$var2" ] 

和印刷不等于

为什么会这样呢?为什么$ VAR1=$ VAR2不一样的$ VAR1=$ VAR2

Why is it so? Why "$var1"="$var2" is not same as "$var1" = "$var2"?

此外,当我写了如果[$ VAR1=$ VAR2] ,它给了

Moreover, when I wrote if [ "$var1"= "$var2" ], it gave

line 4: [: Test 1=: unary operator expected

这是什么意思?为什么它的期待单目运算符?

What does it it mean? How come its expecting unary operator?

推荐答案

测试(或 [EXPR] )是一个内置函数。就像在bash的所有功能,你通过它的参数作为空格分开的话。

test (or [ expr ]) is a builtin function. Like all functions in bash, you pass it's arguments as whitespace separated words.

至于bash的内置命令手册页指出:每个操作员和操作数必须是一个单独的参数

As the man page for bash builtins states: "Each operator and operand must be a separate argument."

这只是bash的方式和其他大多数Unix外壳工作。

It's just the way bash and most other Unix shells work.

变量赋值是不同的。

在bash的变量赋值的语法是:名称= [值] 。你不能把不带引号的空格周围的 = 因为bash的不会跨preT这是你打算转让。 bash的治疗的话大多数列表与参数的命令。

In bash a variable assignment has the syntax: name=[value]. You cannot put unquoted spaces around the = because bash would not interpret this as the assignment you intend. bash treats most lists of words as a command with parameters.

例如

# call the command or function 'abc' with '=def' as argument
abc =def

# call 'def' with the variable 'abc' set to the empty string
abc= def

# call 'ghi' with 'abc' set to 'def'
abc=def ghi

# set 'abc' to 'def ghi'
abc="def ghi"

这篇关于为什么等于运营商如果不受空间环绕不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 05:51