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?
3 Answers
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.
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!
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!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically