Search code examples
bashcygwin

find statement in cygwin bash script


for i in `find . -type f -name "VF-Outlet*.edi" -exec basename \{} \;` ; do
 if [ -n "${i}" ];
 then
 echo file "VF-Outlet found";
 sed -e 's/\*UK\*00/\*UP\*/g;s/XQ.*$/XQ\*H\*20150104\*20150110/g' $i > ${i}_fix
else
 echo file "VF-Outlet" not found;
fi
done

The above code works if the file is found. The 'echo' statement prints file found. If the file is not found however, nothing prints. I tried all the various tests for empty string, and unset variables, nothing works. Also if I try:

i=`find . -type f -name "VF-Outlet*.edi" -exec basename \{} \;`;

Then do the test:

if [ -n "${i}" ];
 then
 echo file ${i} found;
else
 echo file "VF-Outlet" not found;
fi
done

It works correctly if the file is found or not.

Need help in figuring this out. I need the for loop to test multiple files.


Solution

  • The reason it is not working is due to the fact that "for" does not take null value as input for the variable "i"

    For ex:

    for i in echo > /dev/null; do echo hi; done

    The above command wont give any result, because no value has been assigned to value $i for running the loop.

    In the case mentioned here if we check the script in debug mode, we can see that the script dies at initial variable assignment.

    # sh -x script.sh + find . -type f -name VF-Outlet*.edi -exec basename {} ;

    here, script.sh file contains the script you have provided.

    If there is a file present in the directory, the script will successfully execute.

    # sh -x tet
    + find . -type f -name VF-Outlet*.edi -exec basename {} ;
    + [ -n VF-Outlet1.edi ]
    + echo file VF-Outlet found
    file VF-Outlet found
    

    As @shellter mentioned, this not how I would have done. You can use -f instead of -n to check if a file exists.

    Hope this helps!