I am writing a bash script to copy ONE or MORE THAN ONE or ALL files to a destination, and create the destination if it does not exist.
I have already gone through this solution but it does not complete my requirements.
My code (Which does not work for idk what reasons):
# copy files and make a directory if does not exist
mkcp() {
# last argument is destination
dir="${@: -1}"
# create directory if does not exist
mkdir -p "$dir"
# loop over all arguments
for file in "$@"
do
# if file is last argument (directory) then break loop
if [ "$file" == "$dir" ]; then
break
fi
# else keep copying files
cp -R "$file" "$dir"
done
}
I want all these commands to be working:
# copies "text.txt" to "testdir" (testdir may or may not exist so it must be created first)
$ mkcp test.txt ~/desktop/testdir
# copies "test1.txt" and "test2.txt" to "testdir" (conditions are same)
$ mkcp test1.txt test2.txt ~/desktop/testdir
# copies "all files" to "testdir" (conditions are same)
$ mkcp * ~/desktop/testdir
If there's any other solution that can complete my requirements, I am okay with it too.
Note: The mkcp
function is stored in .zshrc
.