Bash script for removing spaces from a file name

Viewed 248

I'm writing a bash script which change spaces to underscores in the names of the files in the current directory. This is the script:

#!/bin/bash


for fil in "$(pwd)"/*; do 
    basefil=$(basename "$fil") #get name of file
    name=${basefil// /_}
    
    if [[ ! -f "$name" ]]; then
        echo "$fil" "$name"
        mv "$fil" "$name"
        
    fi
done

The problem is that I get something like this:

mv: cannot move '/home/gustavolozada/Downloads/prueba' to a subdirectory of itself, 'prueba/prueba'

I only get this with directories. I added the echo "$fil" "$name" to get a little more info and this is what it shows:

/home/gustavolozada/Downloads/prueba prueba

I do not understand what is the problem, because the command is basically:

mv /home/gustavolozada/Downloads/prueba prueba

which to me does not have any problem whatsoever (besides the fact that they are the same file, but I already check if there is a file with that name in the directory with if [[ ! -f "$name" ]]; then

1 Answers

Just a bizarre idea for an explanation: Since name in your error case has the value of prueba/prueba, but has been calculated via basename, it should not contain any slashes. Could it be that Downloads/prueba is a symlink?

Related