Skip to content

Instantly share code, notes, and snippets.

@egladman
Last active June 10, 2021 13:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egladman/0a97dc39f774cb3b620763adf849525e to your computer and use it in GitHub Desktop.
Save egladman/0a97dc39f774cb3b620763adf849525e to your computer and use it in GitHub Desktop.
Move a file, and create the destination directory if it doesn't exist
#!/bin/sh
# Usage: mvp <src> <dest>
# Move a file, and create the destination directory if it doesn't exist
__dirname() {
# Usage: dirname "path"
# https://github.com/dylanaraps/pure-sh-bible
# If '$1' is empty set 'dir' to '.', else '$1'.
dir=${1:-.}
# Strip all trailing forward-slashes '/' from
# the end of the string.
#
# "${dir##*[!/]}": Remove all non-forward-slashes
# from the start of the string, leaving us with only
# the trailing slashes.
# "${dir%%"${}"}": Remove the result of the above
# substitution (a string of forward slashes) from the
# end of the original string.
dir=${dir%%"${dir##*[!/]}"}
# If the variable *does not* contain any forward slashes
# set its value to '.'.
[ "${dir##*/*}" ] && dir=.
# Remove everything *after* the last forward-slash '/'.
dir=${dir%/*}
# Again, strip all trailing forward-slashes '/' from
# the end of the string (see above).
dir=${dir%%"${dir##*[!/]}"}
# Print the resulting string and if it is empty,
# print '/'.
printf '%s\n' "${dir:-/}"
}
mvp() {
dest_dirname="$(__dirname "${2:?}")"
[ $? -ne 0 ] && return 1
if [ -n "$dest_dirname" -a ! -d "$dest_dirname" ]; then
mkdir -p "$dest_dirname"
[ $? -ne 0 ] && return 1
fi
mv "${1:?}" "$dest"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment