二重引用符で囲まれた文字列で \ を bash として解釈しないでください。

二重引用符で囲まれた文字列で \ を bash として解釈しないでください。

こんなことができるようにしたい

VAR='\\'
echo "$VAR"

そして結果を得る

\\

私が実際に得た結果は

\

実際には、\\がたくさん含まれている非常に長い文字列があります。これを印刷すると、bashは最初の\\を削除します。

ベストアンサー1

組み込みコマンドが指定された文字列と改行文字をそのまま出力するには、次のものがbash必要です。echo

# switch from PWB/USG/XPG/SYSV-style of echo to BSD/Unix-V8-style of echo
# where -n/-e options are recognised and backslash sequences not enabled by
# default
shopt -u xpg_echo

# Use -n (skip adding a newline) with $'\n' (add a newline by hand) to make
# sure the contents of `$VAR` is not treated  as an option if it starts with -
echo -n "$VAR"$'\n'

または:

# disable POSIX mode so options are recognised even if xpg_echo is also on:
set +o posix

# use -E to disable escape processing, and we use -n (skip adding a newline)
# with $'\n' (add a newline by hand) to make sure the contents of `$VAR` is not
# treated  as an option if it starts with -
echo -En "$VAR"$'\n'

これはシェルによって異なるbashため、他のシェルには異なるアプローチを取る必要があり、echo一部の実装では任意の文字列を出力できないことに注意してください。

printfただし、ここでは標準コマンドを使用する方が良いです。

printf '%s\n' "$VAR"

バラよりなぜprintfがechoより優れているのですか?もっと学ぶ。

おすすめ記事