Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created November 26, 2025 13:43
Show Gist options
  • Select an option

  • Save pmarreck/11a7ea6d66b10dc1356f8c50719081e3 to your computer and use it in GitHub Desktop.

Select an option

Save pmarreck/11a7ea6d66b10dc1356f8c50719081e3 to your computer and use it in GitHub Desktop.
mkdir but takes a -c/--cd argument that cd's into the new directory
# I got tired of this pattern: mkdir -p path/to/dir && cd path/to/dir
# So now mkdir will take a -c or --cd argument to do it all at once.
mkdir-custom () {
local do_cd=false;
local mkdir_args=();
local target_dir="";
function show_help ()
{
cat <<-'EOF'
Usage: mkdir-custom [OPTIONS] DIRECTORY
Create a directory with optional automatic cd.
Options:
-c, --cd After creating directory, change into it
-p Create parent directories as needed (passed to mkdir)
-m MODE Set file mode (passed to mkdir)
-v, --verbose Print a message for each created directory (passed to mkdir)
-h, --help Display this help message
--test Run associated tests
All other options are forwarded to the system mkdir command.
Examples:
mkdir-custom mydir # Create mydir
mkdir-custom -c mydir # Create mydir and cd into it
mkdir-custom -c -p a/b/c # Create nested dirs and cd to a/b/c
Note: The -c/--cd option only affects the current shell when used
through the 'mkdir' alias. Use 'alias mkdir=mkdir-custom' in your
shell configuration.
EOF
};
if [[ "$1" == "--test" ]]; then
if [[ -x "$HOME/dotfiles/bin/test/mkdir-custom_test" ]]; then
"$HOME/dotfiles/bin/test/mkdir-custom_test" > /dev/null;
return $?;
else
echo "Error: Test file not found or not executable" 1>&2;
return 1;
fi;
fi;
while [[ $# -gt 0 ]]; do
case "$1" in
-h | --help)
show_help;
return 0
;;
-c | --cd)
do_cd=true;
shift
;;
-*)
mkdir_args+=("$1");
shift
;;
*)
target_dir="$1";
shift
;;
esac;
done;
if [[ -z "$target_dir" ]]; then
echo "Error: No directory specified" 1>&2;
show_help 1>&2;
return 1;
fi;
if ! command mkdir "${mkdir_args[@]}" "$target_dir"; then
return $?;
fi;
if [[ "$do_cd" == true ]]; then
cd "$target_dir" || return $?;
fi;
return 0
}
alias mkdir='mkdir-custom'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment