【问题标题】:Why do backticks, when used for saving command output, cause an EOF error?为什么反引号在用于保存命令输出时会导致 EOF 错误?
【发布时间】:2019-06-17 15:14:58
【问题描述】:

我正在遍历一个 clearcase 文件列表,以查看文本“Merge ct describe 输出的一部分。

我已经尝试在这个 clearcase 文件列表上运行一个 while 循环,然后如果它满足我想要的条件,就将它附加到另一个文件中。以下是我使用的确切逻辑:

16 FILTER_LIST=cut -f1 -d'@' branchmerge_versions.txt
17 touch temp.txt
18 echo $FILTER_LIST > temp.txt
19 
20 while read t; do
21    isMerged=`cleartool describe t | grep -e "Merge <-"`
22   if [[ "x$isMerged" == "x" ]]; then
23          echo "$t" >> filesToMerge.txt
24   fi
25 done < temp.txt
26

在脚本上运行 bash -n 返回以下错误:

filter.sh: line 21: unexpected EOF while looking for matching ``'
filter.sh: line 26: syntax error: unexpected end of file

为什么命令反引号会导致意外的 EOF 错误?

【问题讨论】:

  • [[ $isMerged = "" ]] 就足够了,因为bash(以及几乎所有[ 的现代实现)都可以很好地处理空字符串。 [[ -z $isMerged ]] 会更好。
  • 第 1-20 行是否还有其他反引号? bash 可能认为第 21 行的第一个反引号实际上 关闭 前一个反引号,使最后一个反引号成为开头的反引号。无论如何,您应该用$(...) 替换任何反引号; bash 和任何其他符合 POSIX 的 shell 都支持它们。 isMerged=$(cleartool describ t | grep -e "Merge &lt;-").
  • 您查看temp.txt 的内容了吗?祝你好运。
  • 绝对没有必要将[[ "x$isMerged" == "x" ]] 用作成语。 if ! [[ $isMerged ]] 可以用作纯 bash 代码,或者如果您想要符合标准,[ -z "$isMerged" ]
  • ...没有符合 1992 POSIX sh 标准的 shell 需要 "x$Foo" 解决方法,也没有任何版本的 bash 或 ksh 曾经发布过。 (它在 1980 年后的 shell 上有用的唯一情况是,如果您将多个测试与过时的 -a-o 运算符组合在一起,但它们在标准中被标记为过时的,并且在 @987654342 中不受支持@无论如何)。

标签: bash clearcase backticks


【解决方案1】:

正如我在“What is the difference between $(command) and `command`` in shell programming?”中解释的那样

嵌入式命令替换和/或使用双引号需要小心地使用反斜杠字符进行转义。
我们更喜欢 $( ... )

在您的情况下,请尝试

isMerged=$(cleartool describe t | grep -e "Merge <-")

但是,如评论所述,请首先检查输入文件 temp.txt 的内容。

【讨论】:

    猜你喜欢
    • 2016-03-13
    • 2019-11-21
    • 2020-07-05
    • 1970-01-01
    • 2011-02-08
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多