blogですかい

仕事、プライベートで学んだことなどを発信し、その内容がたとえ少数でも誰かの役に立ったらなら、それはとっても嬉しいなって

trackされてない新規ファイルをまとめてgit add するスクリプトを書いた

このツイートを拝見し、確かにそのようなコマンドは無いような気がして、そういう動作をするスクリプトを書いてみました。

#!/bin/bash

UNTRACKED_FILES=0

# to set InternalFieldSeparator only NewLine
IFS_ORG=$IFS
IFS=$'\n'

for row in `git status`
do

echo $row | grep '^no changes add' > /dev/null
if test 0 -eq $?
then
        UNTRACKED_FILES=0
fi

echo $row | grep '^# Untracked files:' > /dev/null
if test 0 -eq $?
then
        UNTRACKED_FILES=1
fi

if test 1 -eq $UNTRACKED_FILES
then
        FILE_PATH=`echo $row | awk '{print $2}'`
        if test -f "${FILE_PATH}"
        then
                git add ${FILE_PATH}
        fi
fi

done

IFS=$IFS_ORG

git statusの出力のうち、 Untracked files: 以下に表示されるファイル名をgit addします。 Changes not staged for commit: なファイルは add しません。

例えばこれをPATHの通った場所に、git-add-newfilesという名前で保存すれば

[prompt]$ git status
# On branch master
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   hoge.txt
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       bar.txt
#       foo.txt
#       fuga.txt
no changes added to commit (use "git add" and/or "git commit -a")
[prompt]$
[prompt]$
[prompt]$ git-add-newfiles 
[prompt]$
[prompt]$
[prompt]$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       new file:   bar.txt
#       new file:   foo.txt
#       new file:   fuga.txt
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   hoge.txt

と、このように、new file のみを add できます。