Bash 中的简单逻辑运算符 [英] Simple logical operators in Bash

查看:31
本文介绍了Bash 中的简单逻辑运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个变量,我想检查以下条件(用文字写出来,然后我尝试编写 bash 脚本失败):

I have a couple of variables and I want to check the following condition (written out in words, then my failed attempt at bash scripting):

if varA EQUALS 1 AND ( varB EQUALS "t1" OR varB EQUALS "t2" ) then 

do something

done.

在我失败的尝试中,我想出了:

And in my failed attempt, I came up with:

if (($varA == 1)) && ( (($varB == "t1")) || (($varC == "t2")) ); 
  then
    scale=0.05
  fi

推荐答案

你写的实际上几乎有效(如果所有变量都是数字,它会有效),但它根本不是惯用的方式.

What you've written actually almost works (it would work if all the variables were numbers), but it's not an idiomatic way at all.

  • (...) 括号表示 子外壳.它们内部的内容与许多其他语言中的表达方式不同.它是一个命令列表(就像外面的括号一样).这些命令在单独的子进程中执行,因此在括号内执行的任何重定向、赋值等在括号外都没有影响.
    • 以美元符号开头,$(...)命令替换:括号内有一个命令,该命令的输出用作命令行的一部分(在额外扩展之后,除非替换在双引号之间,但那是另一个故事).
    • (…) parentheses indicate a subshell. What's inside them isn't an expression like in many other languages. It's a list of commands (just like outside parentheses). These commands are executed in a separate subprocess, so any redirection, assignment, etc. performed inside the parentheses has no effect outside the parentheses.
      • With a leading dollar sign, $(…) is a command substitution: there is a command inside the parentheses, and the output from the command is used as part of the command line (after extra expansions unless the substitution is between double quotes, but that's another story).
      • 以美元符号开头,${VAR}参数扩展,扩展到变量的值,可能有额外的转换.
      • With a leading dollar sign, ${VAR} is a parameter expansion, expanding to the value of a variable, with possible extra transformations.
      • 在算术表达式 $((...)) 中使用相同的语法,它扩展为表达式的整数值.
      • The same syntax is used in arithmetic expressions $((…)), which expand to the integer value of the expression.

      这是在 bash 中编写测试的惯用方式:

      This is the idiomatic way to write your test in bash:

      if [[ $varA == 1 && ($varB == "t1" || $varC == "t2") ]]; then
      

      如果您需要对其他 shell 的可移植性,这将是方法(注意每个单独测试周围的额外引用和单独的括号集,以及使用传统的 = 运算符而不是ksh/bash/zsh == 变体):

      If you need portability to other shells, this would be the way (note the additional quoting and the separate sets of brackets around each individual test, and the use of the traditional = operator rather than the ksh/bash/zsh == variant):

      if [ "$varA" = 1 ] && { [ "$varB" = "t1" ] || [ "$varC" = "t2" ]; }; then
      

      这篇关于Bash 中的简单逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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