William William - 16 days ago 7
Bash Question

Shellscript - Show error for specific argument when using mv

I'm currently writing code for a script to move files to a "dustbin".
As it stands - the code works fine but I want it to produce a message when a file has been moved correctly and a message when a specific file has failed to move/doesn't exist.

My code will accept multiple filenames for input, e.g.

# del test1.txt *.html testing.doc
# Successfully moved to Dustbin


However if only one of these does not exist it still produces an error message.
How do I do this but still allow it to accept arguments as seen in the above example?

My code is as follows:

#!/bin/sh

if [$# -eq 0 ];
then echo "Usage : del <filepath>"
else
mkdir -p /root/Dustbin
if mv -u "$@" /root/Dustbin 2>/dev/null
then echo "Successfully moved to dustbin"
else echo "File/directory doesn't exist or hasn't been moved"
fi
fi

# END OF SCRIPT


Sorry for what is probably an obvious question! I'm completely new to shellscript !

Many thanks

Answer

You would have to iterate over the arguments and try to move each one:

for path in "$@"; do
    if mv -u "$path" /root/Dustbin 2>/dev/null; then
        echo "Success"
    else
        printf 'Failed to move %s\n' "$path"
    fi
done

As a shorthand for iterating over the arguments you can omit in "$@" like

for path; do
    if mv -u "$path" /root/Dustbin 2>/dev/null; then
        echo "Success"
    else
        printf 'Failed to move %s\n' "$path"
    fi
done