LoginSignup
4
4

More than 5 years have passed since last update.

ファイルへのユニークな追記

Last updated at Posted at 2014-10-21

とあるプログラムのインストールスクリプトを作っていて、何度も実行してテストしてたんだけどそのたびに.bashrcに設定が追記されて面倒だったので
書きたい文言が既に書かれてたら書かない、書いてなかったら書く みたいな関数を作った。

中身

grepして何も帰ってこなかったら書いてないとみて追記するだけ。
引数足りなかったらおわる。
ファイルなかったら書いておわる。

uniqadd()
function uniqadd() {
    if [ $# != '2' ] ;then
        echo "usage: uniqadd() need 2 args..."
        echo "usage: $ uniqadd filename add_article"
        return 0
    fi

    local dst=$1
    local article=$2

    if [ -e "${dst}" ] ;then
        echo ${article} > ${dst}
        return 0
    fi

    local written=`grep ${article} ${dst}`

    if [ "$written" = "" ] ;then
        echo ${article} >> ${dst}
    fi
}

使い方

$ cat hoge.txt
hoge

$ uniqadd hoge.txt hoge
$ cat hoge.txt
hoge

$ uniqadd hoge.txt hogefuga
$ cat hoge.txt
hoge
hogefuga

だけども

grepして書いてるか確認するとこは使ったけど、この関数は結局使わなかった。

4
4
1

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
4
4