Search code examples
bashshellmv

Bash problem with function that hides files


I have this function

function hide {
    for f in "$@"; do
        if [[ ! ${f::1} == '.' ]]; then
            mv $f .$f
        fi
    done
}

that should hide a file passed as input, if it is not already hidden.

When I use it on files whose names contain spaces, like:

touch "ciao ciao"
hide ciao\ ciao

it doesn't work and I get this error instead:

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

I tried changing .$f to ."$f" in the mv command but I still get the error.


Solution

  • Per @Jetchisel, you need to quote the variables when passing args to mv to ensure spaces are preserved:

    function hide {
        for f in "$@"; do
            if [[ ! ${f::1} == '.' ]]; then
                mv "$f" ".$f"  # <= note variable references are quoted
            fi
        done
    }