如何在流程替代中使用case/esac? [英] How to use case/esac in process substitution?

查看:71
本文介绍了如何在流程替代中使用case/esac?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的一行工作正常:

 而getopts:t t;在$ t中做$ t的情况吗?休息;esac;完毕 

但是,当我尝试将其用作命令替换时,bash会失败并显示错误.

代码:

 #!/usr/bin/env bash回声$ BASH_VERSION["$(while getopts:t t;在t中执行case $ t)echo $ t; break; esac; done)" ="t"]&&回显指定的选项". 

结果:

  $ ./test.sh -a -b -c -t4.3.42(1)-发布./test.sh:第3行:寻找匹配的"时出现意外的EOF./test.sh:第4行:语法错误:文件意外结束 

t)中的

反斜杠 \)无效.并且(t)语法在GNU bash 3.2.57中有效,但在4.3.42中不可用.

在两个版本中似乎都可以使用反引号:

  [`getopts:t t;在t中执行$ t的情况)echo $ t; break; esac; done`" ="t"]&&回显指定的选项". 

但是我不想使用该语法,因为它已已弃用.

如何在上述命令替换( $())中使用 case 语法?

或者也许有其他方法可以做同样的事情?

基本上检查是否已为脚本指定了 -t 参数,如果是,则执行一些命令.

解决方案

如果您使用的bash版本破坏了扫描程序,使其以仅在不平衡的)处终止,则当前版本4.3中不再存在的错误-您可以按以下方法解决此问题:

 #!/usr/bin/env bash["$(while getopts:t t;在(t)中执行$ t的情况,echo $ t; break ;; esac;完成)" ="t"]&&回显指定的选项". 

此处的主要区别是使用(t)而不是 t),因此导致括号之间的平衡.这是 POSIX sh标准中明确允许的语法.

I've the following line which works fine:

while getopts :t t; do case $t in t) echo $t; break; esac; done

however when I'm trying to use it as command substitution, the bash fails with error.

Code:

#!/usr/bin/env bash
echo $BASH_VERSION
[ "$(while getopts :t t; do case $t in t) echo $t; break; esac; done)" = "t" ] && echo "Option specified."

Result:

$ ./test.sh -a -b -c -t
4.3.42(1)-release
./test.sh: line 3: unexpected EOF while looking for matching `"'
./test.sh: line 4: syntax error: unexpected end of file

Backslashing \) in t) doesn't help. And (t) syntax works in GNU bash 3.2.57, but it's not in 4.3.42.

It seems using backticks works fine for both versions:

[ "`while getopts :t t; do case $t in t) echo $t; break; esac; done`" = "t" ] && echo "Option specified."

however I don't want to use that syntax as it's deprecated.

How I can use case syntax within the above command substitution ($())?

Or maybe there is other way of doing the same thing?

Basically to check whether -t parameter has been specified to the script and execute some command if so.

解决方案

If you have a version of bash where the scanner was broken in such a way as to only terminate at an unbalanced ) -- a bug which no longer exists in current 4.3 -- you could work around it as follows:

#!/usr/bin/env bash
[ "$(while getopts :t t; do case $t in (t) echo $t; break;; esac; done)" = "t" ] && echo "Option specified."

The key difference here is using (t) rather than t), thus resulting in parenthesis being balanced. This is syntax explicitly allowed in the POSIX sh standard.

这篇关于如何在流程替代中使用case/esac?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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