Command-Line

將命令的輸出儲存在 shell 變數中

  • June 1, 2015

我有一個操作cut,我想將結果分配給一個變數

var4=echo ztemp.xml |cut -f1 -d '.'

我得到錯誤:

ztemp.xml 不是命令

var4never的值被賦值;我正在嘗試為其分配以下輸出:

echo ztemp.xml | cut -f1 -d '.'

我怎樣才能做到這一點?

您需要將作業修改為:

var4="$(echo ztemp.xml | cut -f1 -d '.')"

$(…)構造稱為命令替代

根據您使用的外殼,您可以使用參數擴展。例如在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.

在你的情況下,這意味著做這樣的事情:

var4=ztemp.xml
var4=${var4%.*}

請注意,該字元#在字元串的前綴部分上的行為方式相似。

引用自:https://unix.stackexchange.com/questions/4569