LoginSignup
13
11

More than 5 years have passed since last update.

shell の while read で -r を付与して \(バックスラッシュ)によるクォートを防止する。

Posted at

珍しくOracle Database以外のネタ、shell の while read に -r を付与して、
\(バックスラッシュ)によるクォートを防止してみるやで。彡(゚)(゚)

1. テスト用 の shell script

data.txt の内容を1行ずつ出力する単純なシェルです。


while_read.sh

#!/bin/bash

CNT=0;
cat data.txt | while read line
do
  CNT=`expr ${CNT} + 1`;
  echo "${CNT}:${line}";
done;

2. テストデータ(data.txt)

テストデータの中身です。
1行目の最終文字が\(バックスラッシュ)です。

cat data.txt

iii\
jjj
kkk

3. テスト用 shell script の実行結果

この状態での実行結果は下記の通りです。1行目の最終文字の
\(バックスラッシュ)で改行がクォートされてしまうため、
1行目と2行目が繋がって出力されてしまいますやね彡(゚)(゚)

./while_read.sh

1:iiijjj
2:kkk

4. read に -r を付与して実行

read に -r を付与して shell script を実行してみます。
改行がクォートされず、3行出力されましたやね彡(^)(^)

cat while_read.sh

#!/bin/bash

CNT=0;
cat data.txt | while read -r line
do
  CNT=`expr ${CNT} + 1`;
  echo "${CNT}:${line}";
done;

./while_read.sh

1:iii\
2:jjj
3:kkk

5. 参考

read コマンドの使い方 - 拡張 POSIX
シェルスクリプト Advent Calendar 2013 - ダメ出し Blog
https://fumiyas.github.io/2013/12/14/read.sh-advent-calendar.html

13
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11