In: Computer Science
Write a bash script to find all the files ending with .c recursively for every directory in your current working directory, then copy each one to a folder called programs, need handle duplicates by appending the number to the end of the file (ex main.c main-1.c ) compile them and generate a report
report should look like:
main.c compiles
prog2.c failed
main-2.c compiles
etc.
#!/bin/bash
#Defining/Creating Program Directory
Programs="./programs"
if [ ! -d $Programs ]; then
mkdir $Programs
fi
for srcpath in $(find . -type f)
# if it is reading from this program directory, then don't process it
do srcdirname=$(dirname $srcpath)
if [[ "$srcdirname" == "$Programs" ]]; then
continue
fi
# check for file name. If it is not c, then don't process it
fileext="${srcpath##*.}"
if [[ $fileext == "c" ]]; then
#Check the src filename
dstFile=$(basename $srcpath)
dstPath="$Programs/$dstFile"
((count=0))
#If the file is already present in dest. path then rename file and retry
while [[ -f $dstPath ]]
do ((count++))
dstPath="$Programs/$(basename $srcpath .c)-$count.c"
done
#Copy the source file to final dest file
cp $srcpath $dstPath
#This line will help you to see what all files are copied from which directory to programs
#Uncomment the below and check by yourself after the end of the script
#Remove this line from final code.
#echo "cp $srcpath $dstPath" >> filelist.sh
#gcc will return 0 on success. Redirect all error and output to null
gcc $dstPath > /dev/null 2>&1
#Check for return value of gcc compilation
if [ $? -eq 0 ]
then echo "$(basename $dstPath) compiles"
else
echo "$(basename $dstPath) failed";
fi
fi
done
#Remove a.out generated in compilation process
if [ -f "a.out" ]; then
rm a.out
#If you want to remove programs folder also, uncomment the below line
#rm -rf $Programs
fi