Skip to content

Instantly share code, notes, and snippets.

@udkyo
Last active August 11, 2023 23:56
Show Gist options
  • Save udkyo/babe725bb4c9c6b158d3641ba0f94159 to your computer and use it in GitHub Desktop.
Save udkyo/babe725bb4c9c6b158d3641ba0f94159 to your computer and use it in GitHub Desktop.
mkgo
# mkgo: A handy shell function to create directories and cd/popd to them
# immediately, supports optional permissions and owner adjustments.
#
# Usage: mkgo [-p] [-m mode] [-o owner] [-s] [-f] directory
# See --help for more details.
#
# (source this or pop it in your profile)
mkgo() {
VERSION="mkgo 2.0.0"
usage() {
echo "Usage: mkgo [-p] [-m mode] [-o owner] [-f] [-s] directory"
echo
echo "Options:"
echo " -p Create intermediate directories as necessary."
echo " -m mode Set file mode (as in chmod)."
echo " -o owner Change file owner (as in chown)."
echo " -f Force mode and owner change if directory already exists."
if command -v pushd > /dev/null 2>&1; then
echo " -s Push directory to stack (like pushd)."
fi
echo " --help Display this help message."
echo " --version Display version information."
return
}
P_FLAG=0
FORCE_FLAG=0
STACK_FLAG=0
MODE=""
OWNER=""
DIR=""
# Parse arguments
while [ "$#" -gt 0 ]; do
key="$1"
case "$key" in
-p)
P_FLAG=1
shift
;;
-m)
MODE="$2"
shift
shift
;;
-o)
OWNER="$2"
shift
shift
;;
-f)
FORCE_FLAG=1
shift
;;
-s)
if command -v pushd > /dev/null 2>&1; then
STACK_FLAG=1
else
echo "Warning: pushd not available on this system. Ignoring -s flag."
fi
shift
;;
--help)
usage
return
;;
--version)
echo "$VERSION"
return
;;
*)
DIR="$1"
shift
;;
esac
done
if [ -z "$DIR" ]; then
echo "Error: No directory provided."
usage
return
fi
if [ -d "$DIR" ]; then
if [ $FORCE_FLAG -eq 0 ]; then
echo "Directory '$DIR' already exists. Use -f to force mode and owner changes."
return
else
echo "Directory '$DIR' already exists. Changing mode and owner as specified."
fi
elif [ $P_FLAG -eq 1 ]; then
mkdir -p "$DIR" 2>/dev/null
else
mkdir "$DIR" 2>/dev/null
fi
# Check if mkdir was successful
if [ $? -ne 0 ]; then
echo "Error: Failed to create '$DIR'. Ensure parent directories exist or use the -p option."
return
fi
if [ -n "$MODE" ]; then
chmod "$MODE" "$DIR"
fi
if [ -n "$OWNER" ]; then
chown "$OWNER" "$DIR"
fi
if [ $STACK_FLAG -eq 1 ]; then
pushd "$DIR" > /dev/null
else
cd "$DIR"
fi
}
@udkyo
Copy link
Author

udkyo commented Aug 11, 2023

FROM alpine
ADD https://gist.githubusercontent.com/udkyo/babe725bb4c9c6b158d3641ba0f94159/raw/b1c132409481c948e7cb219cbc7423503a250499/mkgo /etc/profile.d/mkgo.sh
RUN chmod a+x /etc/profile.d/mkgo.sh
SHELL ["/bin/sh", "-l", "-c"]

RUN set -x \
    && mkgo /foo/bar/bam/baz/code -p -m 0700 -o 1234:5678 -s

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