-
-
Save udkyo/babe725bb4c9c6b158d3641ba0f94159 to your computer and use it in GitHub Desktop.
mkgo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
} |
Author
udkyo
commented
Aug 11, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment