Skip to content

Instantly share code, notes, and snippets.

@NigoroJr
Created February 27, 2017 11:14
Show Gist options
  • Save NigoroJr/28cc1389f578ef92d46cf27ae4831ec4 to your computer and use it in GitHub Desktop.
Save NigoroJr/28cc1389f578ef92d46cf27ae4831ec4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env zsh
# If all of the following conditions are met, treats destination as file
# (i.e. mkdir the dirname, and move & rename to basename).
#
# - there is only one source
# - that source is a file
# - basename of the destination has an extension
#
# To suppress this behavior, use the -n option.
# To force treating destination as a file, use the -f option.
local -a src
local dst_dir
local dst_file
local force_rename=false
local guess=true
while getopts 'hfn' flag; do
case "$flag" in
f)
force_rename=true
;;
n)
guess=false
;;
h)
echo "Usage: $0 [-h] [-f] [-n] <src [src...]> <dst>"
exit 0
esac
done
shift $(( $OPTIND - 1 ))
src=( ${(@)argv[1,-2]} )
dst_dir="${argv[-1]}"
dst_file=""
if $force_rename || \
(( $#src == 1 )) && [[ -f $src[1] ]] && \
[[ -n $dst_dir:e ]] && $guess; then
dst_file="${dst_dir:t}"
dst_dir="${dst_dir:h}"
fi
echo "mkdir -p \"${dst_dir}\""
echo "mv ${(@)src} \"${dst_dir}/${dst_file}\""
return
mkdir -p "${dst_dir}" && mv ${(@)src} "${dst_dir}/${dst_file}"
% pwd
$HOME/tmp
% ls -F
bar/ foo.txt
% # File exists
% mkmv foo.txt ~/foo/bar
mkdir -p "$HOME/foo/bar"
mv foo.txt "$HOME/foo/bar/"
% mkmv foo.txt ~/foo/bar/baz.txt
mkdir -p "$HOME/foo/bar"
mv foo.txt "$HOME/foo/bar/baz.txt"
% mkmv -n foo.txt ~/foo/bar/baz.txt
mkdir -p "$HOME/foo/bar/baz.txt"
mv foo.txt "$HOME/foo/bar/baz.txt/"
% # Non-existent file
% mkmv hage.txt ~/foo/bar
mkdir -p "$HOME/foo/bar"
mv hage.txt "$HOME/foo/bar/"
% # For directory
% mkmv bar ~/foo/bar/
mkdir -p "$HOME/foo/bar/"
mv bar "$HOME/foo/bar//"
% mkmv bar ~/foo/bar/baz.txt
mkdir -p "$HOME/foo/bar/baz.txt"
mv bar "$HOME/foo/bar/baz.txt/"
% mkmv -f bar ~/foo/bar/baz.txt
mkdir -p "$HOME/foo/bar/baz.txt"
mv bar "$HOME/foo/bar/baz.txt/"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment