将命令的输出存储在 shell 变量中

Vas*_*ass 30 command-line scripting bash shell-script coreutils

我有一个操作cut,我想将结果分配给一个变量

var4=echo ztemp.xml |cut -f1 -d '.'
Run Code Online (Sandbox Code Playgroud)

我收到错误:

ztemp.xml 不是命令

var4never的值被赋值;我正在尝试为其分配以下输出:

echo ztemp.xml | cut -f1 -d '.'
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Tok*_*Tok 43

您需要修改您的作业以阅读:

var4="$(echo ztemp.xml | cut -f1 -d '.')"
Run Code Online (Sandbox Code Playgroud)

$(…)构造称为命令 susbtitution

  • @Vass:更好:`var4=$(echo ztemp.xml | cut -f1 -d '.')`。`$(...)` 大部分等同于 `\`...\` `,除了在反引号内引用是特殊的(特别是不推荐嵌套反引号),而在 `$(...)` 内引用异常直观。此外,`$(...)` 比 ` \`...\` ` 更具可读性,后者在许多字体中很容易与 `'...'` 混淆。因此,如果您只想学习一个,请学习 `$(...)`。 (9认同)

Den*_*son 9

根据您使用的外壳,您可以使用参数扩展。例如在bash

   ${parameter%word}
   ${parameter%%word}
          Remove matching suffix pattern.  The word is expanded to produce
          a pattern just as in pathname expansion.  If the pattern matches
          a trailing portion of the expanded value of parameter, then  the
          result  of the expansion is the expanded value of parameter with
          the shortest matching pattern (the ``%'' case)  or  the  longest
          matching  pattern  (the ``%%'' case) deleted.  If parameter is @
          or *, the pattern removal operation is  applied  to  each  posi?
          tional  parameter  in  turn,  and the expansion is the resultant
          list.  If parameter is an array variable subscripted with  @  or
          *,  the  pattern  removal operation is applied to each member of
          the array in turn, and the expansion is the resultant list.
Run Code Online (Sandbox Code Playgroud)

在你的情况下,这意味着做这样的事情:

var4=ztemp.xml
var4=${var4%.*}
Run Code Online (Sandbox Code Playgroud)

请注意,字符#在字符串的前缀部分的行为方式类似。


Bru*_*ger 8

Ksh、Zsh 和 Bash 都提供了另​​一种可能更清晰的语法:

var4=$(echo ztemp.xml | cut -f1 -d '.')
Run Code Online (Sandbox Code Playgroud)

反引号(又名“重音符”)在某些字体中不可读。该$(blahblah)语法是很多更加明显,至少。

请注意,您可以将值通过管道传输到read某些 shell 中的命令中:

ls -1 \*.\* | cut -f1 -d'.' | while read VAR4; do echo $VAR4; done
Run Code Online (Sandbox Code Playgroud)

  • `$()` 由 POSIX 指定,因此它也可用于 Dash、Ash 等。在 Bash 中管道到 `read` 不起作用。 (2认同)
  • <() 构造本质上是一个反向管道;它被称为进程替换,并使用了一些其他技巧。值得注意的一点是它创建了一个文件描述符(在我的系统上,它往往是 /dev/fd/63)来存储进程的输出。这就是重定向工作的根本原因。<() 本身只是吐出一个文件名。< <() 重定向它的内容,就像 `< file` 一样。 (2认同)