Why I can't escape spaces on a bash script?

  • I'm trying to escape the space char for a path in Bash, but neither using a backslash or quotes works.

    .sh script:

    ROOT="/home/hogar/Documents/files/"
    FILE=${ROOT}"bdd.encrypted"
    DESTINATION="/home/hogar/Ubuntu\ One/folder"
    
    mv ${FILE} ${DESTINATION}
    

    After execute the script (./file) this is the result:

    mv: target 'One/folder' is not a directory
    

    Why does the mv command split the string, and how do I stop this from happening?

  • Braiam

    Braiam Correct answer

    7 years ago

    You are expanding the DESTINATION variable, if you did echo this is what you would get:

    echo ${DESTINATION}
    /home/hogar/Ubuntu\ One/folder
    

    But mv doesn't understand this:

    mv ${FILE} ${DESTINATION}                                                
    mv: cannot move '/home/hogar/Documents/files/bdd.encrypted' to '/home/hogar/Ubuntu\\ One/folder': No such file or directory
    

    (for some reason my mv is more verbose)

    To prevent this you should use quotes instead:

    mv "${FILE}" "${DESTINATION}"
    

    If you don't need expansion (since you are already expanding before) just using "$..." should suffice:

    mv "$FILE" "$DESTINATION"
    

    Furthermore, if you double-quote everything consistently, you don't need the backslash before the space.

    `${variable}` and `$variable` are equivalent in all ways, unless immediately followed by a character that is valid in a variable name.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM