user1176607
user1176607

Reputation: 53

How to accommodate spaces in a variable in a bash and iterate in directory tree in linux

I am writing a bash script to iterate in directory and sub-directories, check if a file opened by a process, if yes move it to another location if no skip it My issue is that the Source folders have Spaces is their names such as "FTP SYNC LOCAL" my script is able so far to iterate in the folders and subfolders and test if a file is opened by another process.

It only does this if the file name doesn't contain a SPACE in its name, if it does, nothing happened

print_folder_recurse() {
for i in "$1"/* ;do
    if [ -d "$i" ];then
        echo $i
        #lsof "$i" | grep Serv-U | wc -l
        print_folder_recurse "$i"
    elif [ -f "$i" ]; then
        echo $i
        flag=$(lsof "$i" | grep Serv-U | wc -l)
            if [ $flag == 0 ];then
       echo "Done"
            elif [ $flag != 0 ];then
               echo "Skip Next"
            fi
    fi
done
}


path=""
if [ -d "$1" ]; then
    path=$1;
else
    direct="/Source/FTP Sync"
    echo $direct
    path="$direct"
fi

#echo "base path: $path"
print_folder_recurse $path

The problem is at the bottom of the code with the variable "direct". If I write it

direct="/Source"
echo $direct
path="$direct"
fi

#echo "base path: $path"
print_folder_recurse $path

The file execute.

I can prevent the issue by writing the folder Source/FTP_Sync but I can do this since it will affect a major workflow.

Any help will be apprecaited

Upvotes: 2

Views: 134

Answers (1)

0.sh
0.sh

Reputation: 2762

the print_folder_recurse functions reads the $path variable as 2 seperate arguments because of the space in between the variable i.e $1 = /Source/Ftp while $2 = Sync. The solution is to wrap the $path variable in double quote like this print_folder_recurse "$path"so that print_folder_recurse can read it as a single argument

Upvotes: 1

Related Questions