Wednesday, October 26, 2022

[SOLVED] Bash script to output files NOT being currently used, then use result as a variable

Issue

Currently in the process of thinking of ways to output files being used, but what I really need is to get the current folders/files in a specific location that are not being used and use the output as an environmental variable.

Example:

USED_FILES=$(lsof +D /home/folder| grep -e gradle) echo $USED_FILES

Trying to find and thinking how would I get the folders/files not being in use. Perhaps a while loop?


Solution

Try the following:

find /home/folder -type f | while read file;
do 
    lsof -w | awk -v fil="$file" 'BEGIN { found=0} { if ($NF==fil) {found=1} } END { if (found==1) { exit 0 } else { exit 1 }}' || echo "$file";
done;

Process each file found in the /home/folder and then read the file as variable "file". Using lsof with errors suppressed (-w) use awk to check to see of the last field ($NF) is equal to the file (variable fil in awk). If it is set the found variable to 1. At the end of the awk script, if found is set to 1, exit with a status code of 0, otherwise exit with 1.

If the exit code of lsof piped through to awk is 1 (file is not being used) then, print the file



Answered By - Raman Sailopal
Answer Checked By - Cary Denson (WPSolving Admin)