株式会社ヴァンデミックシステム

Blog

<スポンサーリンク>

以下のようなファイルがあるとすると

[yuta@SERVER test]$ cat files_test
/etc/hosts,
ip a,
netstat -rn,

シェル内でスペース区切り文字を読み込むとスペースで区切られてしまう

[yuta@SERVER test]$ cat test.sh
#!/bin/bash

for LINE in `cat $1`
do
        echo $LINE
done
[yuta@SERVER test]$ sh test.sh files_test
/etc/hosts,
ip
a,
netstat
-rn,

IFS(Internal Field Separator)の環境変数に区切り文字を指定する。
環境変数設定前に現在の状態を保存し、処理終了後に元に戻す。

[yuta@SERVER test]$ cat test.sh
#!/bin/bash

PRE_IFS=$IFS
IFS=$'\n'

for LINE in `cat $1`
do
        echo $LINE
done
IFS=$PRE_IFS
[yuta@SERVER test]$ sh test.sh files_test
/etc/hosts,
ip a,
netstat -rn,

という感じで。

<スポンサーリンク>

コメントを残す

Allowed tags:  you may use these HTML tags and attributes: <a href="">, <strong>, <em>, <h1>, <h2>, <h3>
Please note:  all comments go through moderation.

*

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)