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

0
1
Asked By CuriousCoder99 On

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

Answered By BashBuddy42 On

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.

Answered By SyntaxSavant88 On

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!

Answered By ScriptNinja2023 On

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

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.