Search code examples
bashshellterminalshgnu

Files read from source folder not being recognized as files or directories


Here is my code:

#!/bin/bash

if [ $# -ne 2 ]
then
    echo "USAGE: `basename $0` ./dir_from ./dir_to"
    exit -1
fi

source=$1
destination=$2

if [ ! -d $source ]
then
    echo "ERROR: Source directory doesn't exist."
    exit -1
fi

if [ ! -d $destination ]
then
    mkdir $destination
fi

allFiles=`ls $source`
total=0

for file in $allFiles
do
    echo $file
    fileName="${file%%.*}"
    extension="${file##*.}"
    size=`ls -l $file | awk '{print $6}'`
    echo $size

    if [ -f $file ] && [ "$extension" == "txt" ] && [[ "$fileName" =~ "^[a-z]*$" ]]
    then
        mv "${source}/${file}" "${destination}/${file}.moved_txt"
    fi
done

Here are the contents of the source folder:

total 8
-rw-r--r-- 1 191128 domain users 32 May 22 15:01 afile.txt
-rw-r--r-- 1 191128 domain users  0 May 22 15:01 pleaseeeee.txt
-rw-r--r-- 1 191128 domain users 17 May 22 15:01 pls.txt

The problem I'm facing is the test to see if a file is actually a file, [ -f $file ], doesn't work. It says that they are not files.

Everything except that condition works. Yes, the correct folder is in the source variable and yes, the for loop spits out all the files from the folder.

If I try the test -d to see if they are directories, that also fails. Only when I negate -f do they appear, which is really strange.

They clearly are files (indicated by the -). I created them with the command touch, and I have also tried creating them with the command nano and typing something. I have also tried creating the files from the home directory and moving them to my source folder from to see if that would change anything and it didn't. Now here is something interesting: if the files are in the same directory as the script, it works (they are recognized as files).

Any ideas and comments are appreciated.


Solution

  • I am answering my own question because I figured out my mistake. I don't know if this is allowed on stack-overflow but I would appreciate if this question stayed here if anyone else faces the same mistake.

    In my variable allFiles I only have the file names. I need to concatenate the actual path to the files.

    if [ -f "$source/$file" ]