首页 > 解决方案 > Bash:-c:第 0 行:意外的 EOF

问题描述

我尝试在终端中运行以下命令:

bash -c 's="test"; s=$(echo "word1  word2 " | awk '{print $1;}'); echo $s;'

它给了我以下错误:

bash: -c: line 0: unexpected EOF while looking for matching `)'
bash: -c: line 1: syntax error: unexpected end of file
}); echo $s;: command not found

当我将脚本保存在文件中时,不会出现此问题。

标签: linuxbashsh

解决方案


您使用 -c 传递给 bash 的参数使用单引号。这将“保护”内部双引号,但不能保护用于在awk程序中隐藏 '$1' 的引号。

来自 bash Man

Enclosing  characters in single quotes preserves the literal value of
each character within the quotes.  A single quote may not occur between 
single quotes, even when preceded by a backslash.

鉴于只需要引用单个字符,请考虑在awk程序中使用双引号,并转义 '$'

bash -c 's="test"; s=$(echo "word1  word2 " | awk "{print \$1;}"); echo $s;'

Output:
word1

推荐阅读