Last active
June 10, 2021 13:54
-
-
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
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
#!/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