Automate initialization of a directory with git, the initial tracking / staging of existing files, and your first commit with this script. A README.md and .gitignore file come as a bonus…
Git Init + Git Add + Git Commit
So, you are applying Git version control to a new directory of files. The standard sequence of commands looks like this:
1 2 3
And then you hammer away at your project with git capturing all of your moves.
This script allows you to consolidate that series of commands into a single statement, and throws in blank README.md and .gitignore files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
The script is also available on my GitHub repository. Either copy and paste the code above or download the raw script file from the repository and then run
chmod 744 gitinit.sh on the file to make the script executable. The following sections assume that you saved it in the path
Create a Bash Alias
Create an alias for the shell script so that you don’t have to type the full path to the script each time that you use it. Open your bash startup file (either
.bashrc) and enter the following line to create the alias gitinit:
To use this alias in your current shell process, use the source command on the bash startup file. Assuming that you placed this in the
.bash_profile file and your working directory contains that file, your command is:
It is not necessary to run the source command again when you close and then reopen your terminal.
Navigate to the directory that you would like to initialize with git and enter your alias:
Examine the directory and you will find a new .git directory, README.md file, and .gitignore file. With the unmodified shell script, all files in that were present in the directory (with the exception of the README.md and .gitignore that were just added) are tracked by git and an initial commit is performed with the commit message, “Initial commit”.
Limit Commit by File Type
You have the option to modify the script so that only a specific filetype is added to the initial commit. Use the
FILE_TYPE variable to indicate the filetype that you intend to commit. For example, if you want to add all Python files (.py), change the variable to:
While I haven’t tested this, it should work with multiple file types using your shell’s brace expansion feature. So, you could add all C source and C header files with a
FILE_TYPE variable like this:
Change Your Initial Commit Message
And if you would prefer a different initial commit message, just change the
INITIAL_COMMIT_MESSAGE variable at the top of the script to any message that you’d like. Make sure that you maintain the double quotes if there are spaces or special characters in the commit message.
If you’d like to add the README.md and/or .gitignore files to your commit, move the
touch README.md and
touch .gitignore commands in the script above the
git add "$FILE_TYPE" line (and don’t modify the default