I want to rename a file named "Hi Dude" to "Hi Bro".
If I run the following command in bash, it works.
mv Hi\ Dude Hi\ Bro
But when I execute following two commands:
arg="Hi\ Dude Hi\ Bro"
mv $arg
It is showing following error:
usage: mv [-f | -i | -n] [-v] source target
mv [-f | -i | -n] [-v] source ... directory
Any solution for this? I want to implement this for another bash script.
mv
needs (at least) two arguments (which are separated by spaces).
When you run mv Hi\ Dude Hi\ Bro
, Hi\ Dude
and Hi\ Bro
are identified as two separate arguments as you are signaling Bash to not to give any special meaning to the spaces by escaping them. (If you didn't escape the spaces, there will be four arguments)
If you want to pass values through variables, simplest solution is using two variables as below.
src="Hi Dude"
dst="Hi Bro"
mv "$src" "$dst"
This is the same as, mv "Hi Dude" "Hi Bro"
. Double quotes signal bash to consider entire thing inside as a single unit. So don't forget the double quotes. Otherwise it will be mv Hi Dude Hi Bro
, which does something completely different.