简体   繁体   English

使用awk在bash函数中使用命令输出到变量时出错

[英]Error using command-output to variable in bash functions using awk

I'm getting an error trying to write the output of a command into a variable, which is defined in a function. 尝试将命令的输出写入变量(在函数中定义)时遇到错误。

chk()
        hostsum=$(md5sum /etc/hosts | awk -F" " '{print $1}')
chk

It tells me about a syntax error: 它告诉我一个语法错误:

./testchk.sh: Zeile 3: Syntaxfehler beim unerwarteten Wort hostsum=$(md5sum /etc/hosts | awk -F" " '{print $1}')' ./testchk.sh: Zeile 3: hostsum=$(md5sum /etc/hosts | awk -F" " '{print $1}')' ./testchk.sh:Zeile 3:Syntaxfehler beim unerwarteten Wort hostsum=$(md5sum /etc/hosts | awk -F" " '{print $1}')' ./testchk.sh: Zeile 3: hostsum = $(md5sum / etc / hosts | awk -F“”'{print $ 1}')'

It works outer the function, but just won't because of the function adding some extra quotes. 它在函数外部起作用,但是不会因为该函数添加一些额外的引号而起作用。 Any ideas except using it out of the function? 除了在功能之外使用它,还有其他想法吗?

I think you just need to add braces: 我认为您只需要添加括号:

chk() { hostsum=$(md5sum /etc/hosts | awk -F" " '{print $1}') ; }

Works fine for me here. 这里对我来说很好。 The bash man page says that a function has to contain a compound command, of which { list ; bash手册页说一个功能必须包含一个复合命令,其中{ list ; } is one example. 是一个例子。

try: 尝试:

chk() {
        hostsum=$(md5sum /etc/hosts | awk -F" " '{print $1}')
}
chk

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM