How do I properly pass arguments to my bash script for moving files?

March 18, 2026 3 answers
Asked by puzzle piece finder
I'm learning bash and trying to create a script that moves files to a specified directory using 'if' statements. I've written a script that checks if arguments have been passed before moving them, but I'm running into an issue when I pass fewer than the expected number of arguments. For instance, the script runs without issues for arguments that are provided, but I get an error message stating 'mv: missing destination file operand' for any missing arguments. It seems like my 'if' checks aren't working correctly. I thought the logic was correct, but I keep encountering these errors. What am I missing?

Answers

+tuning pegs~
Definitely add spaces around your operators! Also, if your goal is just to move any passed arguments, you might want to revise your approach to a single command like `mv -iv "$@" /your/destination/dir`. This way, you move all files at once, no fuss!
Reply to this answer
parcel tape dispenser
You're right about the logic, but just to point outโ€”make sure you're also quoting the variables. Use `[[ "$1" != "" ]]` to avoid issues with file paths that might have spaces. This is a good practice in bash scripting!
Reply to this answer
kaleidoscope repair
The issue is that you need spaces around the `!=` operator. Instead of using `[[ $1!="" ]]`, you should write it as `[[ $1 != "" ]]`. Without the spaces, it gets interpreted incorrectly. You could also simplify the checks by using `[[ -n $1 ]]` to check if the argument is non-empty. Additionally, consider using a loop or passing all arguments to `mv` at once instead of separate commands for each one.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions