簡體   English   中英

如何在bash中間接分配變量以從Standard In,File和執行輸出中獲取多行數據

[英]How do I indirectly assign a variable in bash to take multi-line data from both Standard In, a File, and the output of execution

我在這里和其他地方發現了許多片段,可以回答部分問題。 我什至設法以低效的方式分多個步驟進行了此操作。 如果可能的話, 我真的很想找到可以執行此任務的單行執行 ,而不必分配給變量並復制幾次以執行任務。

例如

executeToVar ()
{
    # Takes Arg1: NAME OF VARIABLE TO STORE IN
    # All Remaining Arguments Are Executed
    local STORE_INvar="${1}" ; shift
    eval ${STORE_INvar}=\""$( "$@" 2>&1 )"\"
}

總體上是可行的,即$ executeToVar SOME_VAR ls -l * #實際上SOME_VAR使用從其余參數中獲取的ls -l *命令的執行輸出來填充SOME_VAR 但是,如果命令要在末尾輸出空行,(例如- echo -e -n '\\n\\n123\\n456\\n789\\n\\n'在開始和結束處應該有2 x新行)會被bash的子執行過程剝離。 我在類似的其他帖子中看到,已通過在流的末尾添加標記'x'來解決此問題,例如將子執行變成類似以下內容:

eval ${STORE_INvar}=\""$( "$@" 2>&1 ; echo -n x )"\" # <-- ( Add echo -n x )
# and then if it wasn't an indirect reference to a var:
STORE_INvar=${STORE_INvar%x} 
# However no matter how much I play with:
eval "${STORE_INvar}"=\""${STORE_INvar%x}"\"  
# I am unable to indirectly remove the x from the end.

無論如何,我還需要2個其他變體,一個將STDIN stream分配給var,另一個將文件內容分配給var,我認為這是涉及$( cat ${1} ) ,或者$( cat ${1:--} )給我一個'-'(如果沒有文件名)。 但是,所有這些都將無法正常工作,直到我可以確定需要刪除的x以確保准確分配多行變量為止。

我也嘗試過(但無濟於事):

IFS='' read -d '' "${STORE_INvar}" <<<"$( $@ ; echo -n x )"
eval \"'${STORE_INvar}=${!STORE_INvar%x}'\"

這接近最佳值,但會降低eval

executeToVar() { local varName=$1; shift; printf -v "$1" %s "$("$@")"; }

該公式仍然存在的一個問題是$()刪除尾隨的換行符。 如果要防止這種情況,則需要在子外殼中添加自己的尾隨字符,然后自己刪除它。

executeToVar() {
  local varName=$1; shift;
  local val="$(printf %s x; "$@"; printf %s x)"; val=${val#x}
  printf -v "$varName" %s "${val%x}"
}

如果要將所有內容從stdin讀取到變量中,這特別容易:

# This requires bash 4.1 for automatic fd allocation
readToVar() {
  if [[ $2 && $2 != "-" ]]; then
    exec {read_in_fd}<"$2"              # copy from named file
  else
    exec {read_in_fd}<&0                # copy from stdin
  fi
  IFS= read -r -d '' "$1" <&$read_in_fd # read from the FD
  exec {read_in_fd}<&-                  # close that FD
}

...用作:

readToVar var < <( : "run something here to read its output byte-for-byte" )

...要么...

readToVar var filename

測試這些:

bash3-3.2$ executeToVar var printf '\n\n123\n456\n789\n\n'
bash3-3.2$ declare -p var
declare -- var="

123
456
789

"

...和...

bash4-4.3$ readToVar var2 < <(printf '\n\n123\n456\n789\n\n')
bash4-4.3$ declare -p var2
declare -- var2="

123
456
789

"

存儲在文件中怎么了:

   $ stuffToFile filename $(stuff)

其中“ stuffToFile”測試一個。 > 1個參數,b。 在管道上輸入

   $ ... commands ... | stuffToFile filename   

   $ stuffToFile filename < another_file

其中“ stoffToFile”是一個函數:

function stuffToFile
{
    [[ -f $1 ]] || { echo $1 is not a file; return 1; }

    [[ $# -lt 2 ]] && { cat - > $1; return; }

    echo "$*" > $1
}

因此,如果“材料”具有空白行的開頭和結尾,那么您必須:

   $ stuff | stuffToFile filename

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM