WSL2 のセットアップスクリプトのなかで wsl.conf を作成する際に、改行を含んだ状態でファイルに出力しようとしました。
スクリプト内でファイル作成するということなので echo "hoge" > /path/to/wsl.conf
のように書きますが、改行文字 \n
がそのまま文字として出力されます。
$ echo "my\nname\nis\nyuta" my\nname\nis\nyuta
echo のヘルプを見ると -e
オプションで改行文字を改行として扱ってくれることがわかりました。
$ /usr/bin/echo --help Usage: /usr/bin/echo [SHORT-OPTION]... [STRING]... or: /usr/bin/echo LONG-OPTION Echo the STRING(s) to standard output. -n do not output the trailing newline -e enable interpretation of backslash escapes -E disable interpretation of backslash escapes (default) --help display this help and exit --version output version information and exit If -e is in effect, the following sequences are recognized: \\ backslash \a alert (BEL) \b backspace \c produce no further output \e escape \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \0NNN byte with octal value NNN (1 to 3 digits) \xHH byte with hexadecimal value HH (1 to 2 digits) NOTE: your shell may have its own version of echo, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> Full documentation <https://www.gnu.org/software/coreutils/echo> or available locally via: info '(coreutils) echo invocation'
実際に -e
オプションを付与してみると、改行として扱ってくれることがわかります。
$ echo -e "my\nname\nis\nyuta" my name is yuta
ファイルも改行込みで作成されました。
$ echo -e "my\nname\nis\nyuta" > tmp.txt $ cat tmp.txt my name is yuta
※参考
echo のヘルプを見る方法