如何在Bash中將Heredoc值分配給變量?

我有這個多行字符串(包括引號): bash

abc'asdf"
$(dont-execute-this)
foo"bar"''

如何在Bash中使用Heredoc將其分配給變量? 編輯器

我須要保留換行符。 this

我不想轉義字符串中的字符,這很煩人... spa


#1樓

我發現本身必須讀取其中包含NULL的字符串,所以這是一個解決方案,它將讀取您在其中拋出的任何內容。 儘管若是您實際上正在處理NULL,則將須要在十六進制級別進行處理。 命令行

$ cat> read.dd.sh 3d

read.dd() {
     buf= 
     while read; do
        buf+=$REPLY
     done < <( dd bs=1 2>/dev/null | xxd -p )

     printf -v REPLY '%b' $( sed 's/../ \\\x&/g' <<< $buf )
}

證實: code

$ . read.dd.sh
$ read.dd < read.dd.sh
$ echo -n "$REPLY" > read.dd.sh.copy
$ diff read.dd.sh read.dd.sh.copy || echo "File are different"
$

HEREDOC示例(帶有^ J,^ M,^ I): 文檔

$ read.dd <<'HEREDOC'
>       (TAB)
>       (SPACES)
(^J)^M(^M)
> DONE
>
> HEREDOC

$ declare -p REPLY
declare -- REPLY="  (TAB)
      (SPACES)
(^M)
DONE

"

$ declare -p REPLY | xxd
0000000: 6465 636c 6172 6520 2d2d 2052 4550 4c59  declare -- REPLY
0000010: 3d22 0928 5441 4229 0a20 2020 2020 2028  =".(TAB).      (
0000020: 5350 4143 4553 290a 285e 4a29 0d28 5e4d  SPACES).(^J).(^M
0000030: 290a 444f 4e45 0a0a 220a                 ).DONE

#2樓

VAR=<<END
abc
END

不起做用,由於您將標準輸入重定向到無關的東西,即分配 字符串

export A=`cat <<END
sdfsdf
sdfsdf
sdfsfds
END
` ; echo $A

能夠,可是裏面有一個小問題,可能會阻止您使用它。 另外,您應該避免使用反引號,最好使用命令替換符號$(..)it

export A=$(cat <<END
sdfsdf
sdfsdf
sdfsfds
END
) ; echo $A

#3樓

使用$()將cat的輸出分配給您的變量,以下所示:

VAR=$(cat <<'END_HEREDOC'
abc'asdf"
$(dont-execute-this)
foo"bar"''
END_HEREDOC
)

# this will echo variable with new lines intact
echo "$VAR"
# this will echo variable without new lines (changed to space character)
echo $VAR

確保以單引號分隔END_HEREDOC開頭。

請注意,此行末尾定界符END_HEREDOC必須單獨存在(所以,圓括號末尾位於下一行)。

感謝@ephemient的回答。


#4樓

$TEST="ok"
read MYTEXT <<EOT
this bash trick
should preserve
newlines $TEST
long live perl
EOT
echo -e $MYTEXT

#5樓

您能夠使用如下方法避免沒必要要地使用cat並更好地處理不匹配的引號:

$ read -r -d '' VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

若是您在回顯變量時未引用該變量,則會丟失換行符。 引用它能夠保留它們:

$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

若是要在源代碼中使用縮進以提升可讀性,請在小於號後使用破折號。 縮進必須僅使用製表符(不能使用空格)完成。

$ read -r -d '' VAR <<-'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
    EOF
$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''

相反,若是您想將選項卡保留在結果變量的內容中,則須要從IFS刪除選項卡。 此處文檔( EOF )的終端標記不得縮進。

$ IFS='' read -r -d '' VAR <<'EOF'
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''
EOF
$ echo "$VAR"
    abc'asdf"
    $(dont-execute-this)
    foo"bar"''

能夠經過按Ctrl - V Tab在命令行中插入選項卡 。 若是您使用的是編輯器(取決於哪個),它也可能起做用,或者您可能必須關閉自動將製表符轉換爲空格的功能。

相關文章
相關標籤/搜索