Bash – Handling file names with spaces in shell script

bashshell

How to handle files with their names containing spaces in a shell script.

Here is what I am trying

    find /abc/xyz -name 'BY567*.csv' | while read fname
    do
        mv "$fname" ./archive/$(basename $fname)-$(date +%Y%m%d-%T)
    done

But when I do this it strips of the file name after space. Like if file name is BY567_Test file.csv , it will be changed to BY567_Test-datetimestamp and not BY567_Test file.csv-datetimestamp.

Best Answer

Put double-quotes arround the end of line and in basename :

mv "$fname" "./archive/$(basename "$fname")-$(date +%Y%m%d-%T)"

The variables will be interpreted and the spaces should be OK.

Related Topic