Skip to content

Instantly share code, notes, and snippets.

@kryten87
Last active May 3, 2018 15:43
Show Gist options
  • Save kryten87/7e6603903920a9a3f92d4216bcdb8d92 to your computer and use it in GitHub Desktop.
Save kryten87/7e6603903920a9a3f92d4216bcdb8d92 to your computer and use it in GitHub Desktop.
A bash function to build a path, complete with `.gitkeep` files
# paste this into your shell alias file
#
# Usage:
# mkfolder one/two/three/four
#
# This will produce a directory tree that looks like this:
#
# |-- one
# | |-- .gitkeep
# | `-- two
# | |-- .gitkeep
# | `-- three
# | |-- .gitkeep
# | `-- four
# | |-- .gitkeep
# | `-- five
# | |-- .gitkeep
# | `-- six
# | `-- .gitkeep
#
mkfolder () {
# get the current directory (to return to it at the end)
#
local start=$(pwd)
# get the requested path
#
local newpath="$1"
# is the path empty? if so, just exit quietly
#
if [ -z "$newpath" ]; then
exit 0
fi
# make the requested path, along with all the intermediate directories
#
mkdir -p "$newpath"
# cd into this path
#
cd "$newpath"
# get the current location
#
local curr=$(pwd)
# loop while we're not at the start and we're not at the root
#
while [[ "$start" != "$curr" ]] && [[ "$curr" != "/" ]]; do
# touch the .gitkeep file
#
touch .gitkeep
# move up one level
#
cd ..
# get the current directory
#
curr=$(pwd)
done
}
@kryten87
Copy link
Author

kryten87 commented May 3, 2018

When I'm working in git, I want my full directory tree to be saved in the repository, even if the directories are empty. To that end, I have adopted the convention of using .gitkeep files to maintain those directories. See this StackOverflow answer for an explanation.

To use it, just do mkfolder this/is/my/path and all the directories and .gitkeep files will be created. Then you can commit the .gitkeep files to your repository and the directories will be committed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment