Rename command does not rename to 2 step command for files with space (mac terminal)

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 the following two commands:

arg="Hi\ Dude Hi\ Bro"
mv $arg

      

The following error appears:

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.

+3


source to share


1 answer


mv

it takes (at least) two arguments (which are separated by spaces).

When you run mv Hi\ Dude Hi\ Bro

, Hi\ Dude

and are Hi\ Bro

identified as two separate arguments, since you are signaling Bash to not emphasize spaces by avoiding them. (If you didn't escape whitespace, there will be four arguments)

If you want to pass values ​​through variables, the simplest solution is using two variables as shown below.



src="Hi Dude"
dst="Hi Bro"
mv "$src" "$dst"

      

This is the same as mv "Hi Dude" "Hi Bro"

. Bash double-quoted signal to treat the whole thing inside as a whole. So don't forget the double quotes. Otherwise it will be mv Hi Dude Hi Bro

doing something completely different.

+2


source







All Articles