Search code examples
bashshellterminalmv

Linux MV command failing from Script - using variables


I'm trying to move files from within a bash script,

I have the source and destination saved to variables:

source='/Users/usr/Downloads/Drop/test\ movie.m4v'
dest='/Users/usr/Downloads/Movies/test\ movie.m4v'

And I'm running:

mv $source $dest

I get the output:

usage: mv [-f | -i | -n] [-v] source target
   mv [-f | -i | -n] [-v] source ... directory

What am I doing wrong!?

The files I'm moving may or may not contain spaces in their paths. I'm using sed to add the escape char before the space.

Thanks in advance :)


Solution

  • There are a bunch of ways to deal with filenames that contain spaces, one quick solution might be to wrap the variables in the mv command in quotes:

    #!/bin/bash
    
    source=/path/to/file\ with\ space
    dest=/path/to/file\ with\ space2
    
    mv "$source" "$dest"