Shell Script to Abort if file name has space.

Hi,
In my shell script I use the following code to copy files from one directory to other.

 
    for file in `ls`; do
 
    #----------------- Copy Files From INDIR to OUTDIR  -------------#
        echoen "Copying File ${INDIR}/$file to ${OUTDIR}/${file}"
        cp ${INDIR}/$file  ${OUTDIR}/$file
        if [[ $? == 0 ]]; then
            echoen "Copy Successful ${INDIR}/$file to ${OUTDIR}/$file!!"
        else
            echoen "Could not copy file ${INDIR}/$file to ${OUTDIR}/$file"
            exit -15
        fi
 
    done

I would like to add logic that before copy happens I would like to check if the file name has any spaces in it. If it has space then I would like to abort the process.
The reason why I want to abort is in next part of shell script I remove/delete files based on looping on output of ls command and having a space might create unneccessary problems.

Help is appreciated to modify the above code to abort if space is found in the file name.

Add this code before the copy:

if [[ "$file" =~ \ |\' ]]
then
   exit -15
fi

Your script is going to blow up on files with spaces in them because of the `ls` but it doesn't have to be that way. Backticks split upon spaces, not lines.

Try

for file in *

which avoids that problem completely. You will get complete, unsplit filenames. Just be sure to quote all your variables inside double-quotes when you use them and you'll be fine.

Could you please help me understand how this

* 

is doing same as

`ls`

Appreciate your help.

My point is they're not the same.

`ls` means "run the ls command, and split apart its output on all whitespace". You can get away with this when your filenames have no spaces in them, but if they do, that's a problem.

  • means 'generate a list of all files in the current folder'. It's not part of ls, it's part of the shell, meaning it works nearly everywhere. Type echo * into your shell and see what it does.

You can use it in more complicated ways. A* would be 'all files beginning with an uppercase letter A', .txt would be "all files ending in the extension .txt", and so forth. You can even do things like /path/to//file, to find a file named 'file' inside any folder inside /path/to/.

It won't split on spaces, only on filenames.