Bash if语句:比较不适用于赋值 [英] Bash if statement: Comparison not working with assignment

查看:114
本文介绍了Bash if语句:比较不适用于赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的test_if2()可以按预期工作,但test_if则不能.区别在于,在test_if()中,我进行了变量分配.错误在哪里?

In the following test_if2() works as expected but test_if not. The difference is that in test_if() I do a variable assignment. Where is the error?

test_if() {
  declare file_path
  if [[ -n ${file_path=$(echo "")} || -n ${file_path=$(echo "Hi")} ]]; then
    echo Non null: ${file_path}
  else
    echo null
  fi      
}

test_if2() {
  declare file_path
  declare greet="Hello"
  if [[ -n $(echo "") || -n $(echo "Hi") ]]; then
    echo Non null
  else
    echo null
  fi      
}

test_if #prints null
test_if2 #prints Non null

推荐答案

对于要查找的行为,请使用:=而不是=.

Use := instead of = for the behavior you are looking for.

${param=word}不会进行分配.也可以使用${param:=word}覆盖空参数的情况.

${param=word} does not make the assignment if param is set but empty (which is what declare param does). Use ${param:=word} to cover the case of an empty param as well.

您的问题是未执行分配,并且返回的值为空.

Your issue is that the assignment is not being performed and the returned value is empty.

我在MacOS上测试了您的表情,如下所示:

I tested your expression on MacOS as follows:

file_path=Bye
echo ${file_path=$(echo "Hi")}  # returns Bye 
echo $file_path                 # returns Bye

或者:

unset file_path
echo ${file_path=$(echo "Hi")}  # returns Hi 
echo $file_path                 # returns Hi

最后,让我们看看在考虑设置为unset和empty时是否存在不同的行为:

Lastly let's see if there is a different behavior when consider unset and empty:

file_path=""
echo ${file_path=$(echo "Hi")}  # returns nothing 
echo $file_path                 # returns nothing

我们也可以完全重复您的代码:

And we may as well repeat your code exactly:

declare file_path
echo ${file_path=$(echo "Hi")}  # returns Nothing
echo $file_path                 # returns Nothing

因此,如果我们查看您的代码,就可以知道为什么test_if()返回"null".

So, if we review your code, we can see why test_if() return "null".

因此,我要得出的结论是,只有在未设置param的情况下,$ {param = word}才能进行赋值.请考虑以下代码:

Thus, I'm going to conclude that ${param=word} makes the assignment only if param is unset. Consider this code instead:

test_if() {
  declare file_path
  if [[ -n ${file_path:=$(echo "")} || -n ${file_path:=$(echo "Hi")} ]]; then
    echo Non null: ${file_path}
  else
    echo null
  fi      
}

echo "test_if() returns $(test_if)" # test_if() returns Non null: Hi

如果参数为空或未设置,则使用:=会分配一个值.因此,这将使您的代码正常工作,因为您声明了file_path,但最初并未分配值,而是将其保留为空(但已设置).

The use of := assigns a value if the param is empty or unset. So, this will make your code work , since you declare file_path but didn't assign a value initially, leaving it empty (but set).

这篇关于Bash if语句:比较不适用于赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆