linux - 我可以使用具有退出状态的命令替换,而不是标准输出吗?

标签 linux bash

给定:

tty --quiet
echo $?
0

...和...

tty --quiet && echo foo || echo bar
foo

为什么这是错误的?

[ $(tty --quiet) ] && echo foo || echo bar   
bar

即为什么命令替换的退出状态不为零?

是不是因为上面的命令没有stdout输出?还是我在空格/间距方面做错了什么?

understand对于 $(command),bash 通过在子 shell 环境中执行命令并将命令替换替换为命令的标准输出来执行扩展。

但是,我想要做的是使用 $(command) 的退出状态作为一个逻辑门一系列复杂的操作(用echo代替),如下:

[ $(command1) ] && {
    [ $(command2) ] && {
        echo "Conditions 1 and 2 are true."
      } || {
        echo "Condition 1 is true.  Condition 2 is false."
    }
  } || {
    [ $(command3) ] && {
        echo "Condition 1 is false.  Condition 3 is true."
      } || {
        echo "Conditions 1 and 3 are false."
    }
}

顺便说一句,我的X-Y Problem涉及处理交互式登录 shell 的设置,我知道最好像 THIS 这样解决。但现在我需要修改这个垃圾脚本,它经常使用 tty --quiet,皱眉。

无论如何,如果命令替换不能按我想要的方式工作,我可以将其写成...

if [ $(command1) ] ; then
  if [ $(command2) ] ; then

...等等但这种方法似乎更优雅。

最佳答案

[ $(tty --quiet) ] 测试 tty 的结果是否为空字符串。唯一涉及的退出状态是 [ 本身; tty 的退出状态被忽略。

你只是想要

if command1; then
   if command2; then
       echo "1 and 2 are true"
   else
       echo "1 is true; 2 is false"
   fi
elif command3; then
    echo "1 is false; 3 is true"
else
    echo "1 and 3 are false"
fi

关于linux - 我可以使用具有退出状态的命令替换,而不是标准输出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48104274/

相关文章:

linux - 谁能帮助纠正我的 bash 脚本 : Custom user creation in bash?

bash - Linux shell 脚本中表格的单元格求和

linux - shell脚本: syntax error near unexpected token `while'

node.js - 将 Node 作为 Cron 任务运行

Python - 如何在 gtk.Window 中加载 Google Chrome 或 Chromium 浏览器,如 webkit.WebView()?

linux - Bash 脚本 linux : Lay-out and output of a script

c++ - 如何从 GStreamer 中的应用程序获取事件?

java - Raspberry Ad-hoc U 广播

linux - 将两个定界符分隔变量的列表通过管道传输到 BASH 中的新命令

linux - for i in {00..03} 不适用于 nohup