If you don't simply want to use mkdir -p
and then a cp
, then you may as well create a fairly robust function to copy it wall always be the same folder
to the directory name given by dirnm
as the first argument (in the current working directory if no second argument given) or to /destpath/dirnm
if a path representing destpath
is given in argument as the second argument.
In forming the paths involved, you will need to check for (and remove) leading and trailing '/'
characters in dirnm
and any trailing '/'
in destpath. You then attempt to create
destpath/dirnmas given and on success copy
it wall always be the same folderto
destpath/dirnm(with the
-a` option, or as desired). On failure, throw error and return. The following is one approach to such a function:
mkdircp ()
{
srcdir="NameOfDirToCopy" ## the name of the dir you always copy (w/full path)
[ -d "$srcdir" ] || { ## validate srcdir exists
printf "error: source directory '%s' does not exist.\n" "$srcdir"
return 1
}
[ -z $1 ] && { ## validate that required dirnm given
printf "usage: mdcp dirnm [destpath (default ./)]\n";
return 1
};
## trim leading/trailing '/' from dirnm
[ ${1:0:1} == '/' ] && dirnm="${1:1}" || dirnm="$1"
[ ${1:(-1)} == '/' ] && dirnm="${dirnm%/}"
## if destpath given, trim trailing '/' & set destdir
if [ -n "$2" ]; then
[ ${2:(-1)}x == '/x' ] && destpath="${2%/}" || destpath="$2"
[ -n "$2" ] && destdir="${destpath}/${dirnm}"
else
destdir="./$dirnm" ## default destdir in ./
fi
## create destdir & validate or throw error
[ -d "$destdir" ] || mkdir -p "$destdir"
[ -d "$destdir" ] || {
printf "error: unable to create destdir '%s'. (check permissions)\n" "$destdir"
return 1
}
## copy (-recursive -archive) "$srcdir" "$destdir"
printf "copying: %s -> %s\n" "$srcdir" "$destdir"
# cp -a "$srcdir" "$destdir" ## (uncomment for actual copy )
}
I would include the function in your ~/.bashrc
(or ~/.profile) or you can manually enter/export it in your current shell. I would also create a convenient alias
to cut down typing following the declaration in .bashrc
like:
alias mdcp='mkdircp'
With the alias, the use is:
mdcp dirnm [destpath (default: ./)]
To copy it wall always be the same folder
to destpath/dirnm
. Let me know if you have any questions or need to adjust things a bit.