シェルで改行を表現する方法は?

シェルで改行を表現する方法は?

私はdebian7.8 bashシェルを使用しています。

str="deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free  \n  
      deb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free  "

echo $str > test  

私のテストファイルでは、次のようになります。

deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free \n deb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free

私が望むもの:

deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free 
deb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free

改行を正しく表現する方法は?

答え1

Jasonwryanの提案に加えて、以下を使用することをお勧めしますprintf

$ printf "%s http://ftp.cn.debian.org/debian/ wheezy main contrib non-free\n" deb deb-src > test
$ cat test
deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free

printfフォーマット文字列は引数が使い果たされるまで再利用されるため、繰り返し行を印刷するための良い方法が提供されます。

答え2

引用符の中に実際の改行文字を含めるだけです(一重引用符または二重引用符で使用可能)。 2行目をインデントすると、スペースは文字列の一部になります。また変数の置換には常に二重引用符を使用してください。

str="deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free"
echo "$str" > test

$'…'Ksh、bash、およびzsh(通常のshではない)には、バックスラッシュがCと同様のエスケープシーケンスを開始する代替引用構文があるため、改行を表す\nために作成できます。あなたの場合は読みにくいです。

str=$'deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free\ndeb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free'
echo "$str" > test

ここのドキュメント通常、複数行の文字列を表示するより読みやすい方法です。ここで、ドキュメントはコマンドライン引数ではなくコマンドの標準入力に渡されます。

cat <<EOF >test
deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free
EOF

1またはより一般的には、代替ファイル記述子を指定した場合、入力として使用されます。

答え3

echo -e1つのオプションは、拡張エスケープシーケンスを使用することです。 2番目のオプションは単に「リテラル」改行文字を使用することです(で動作しますbash)。

str = "deb ... non-free  "$'\n'"deb-src ... non-free  "
echo "$str"

$'···'挿入されたテキストの記号を参照してください。

しかし、これらの変数に改行を追加するのは良い考えではありません。スクリプトを読むのは難しく、"$str"エスケープシーケンス(使用されている場合)がわからない場合や、\n単語の区切り(大文字と小文字)を使用する他のプログラムに提供されると、$''愚かなバグや不要な動作が発生する可能性があります。配列を使用して繰り返すと、行が増えるとスケーラビリティが向上します。

コードの1つの場所にのみ配置するには、2つのechoコマンドに分割する必要があります。それでは、少なくとも間違っているわけではありません。

ファイルに保存したい場合は、別の興味深い、おそらく最高の解決策がここに文書化されています。

cat > test <<EOF
deb http://ftp.cn.debian.org/debian/ wheezy main contrib non-free
deb-src http://ftp.cn.debian.org/debian/ wheezy main contrib non-free
EOF

追加資料: https://stackoverflow.com/questions/9139401/trying-to-embed-newline-in-a-variable-in-bash

関連情報