Issue
I'm new to Bash scripting, and been writing a script to check different log files if they exist or not, and I'm a bit stuck here.
clientlist=/path/to/logfile/which/consists/of/client/names
# I grepped only the client name from the logfile,
# and piped into awk to add ".log" to each client name
clients=$(grep -i 'list of client assets:' $clientlist | cut -d":" -f1 | awk '{print $NF".log"}')
echo "Clients : $clients"
#For example "Clients: Apple.log
# Samsung.log
# Nokia.log
# ...."
export alertfiles="*_$clients" #path/to/each/client/logfiles
for file in $alertfiles
do
# I will test each ".log" file of each client, if it exists or not
test -f "$file" && echo $file exists || { echo Error: $file does not exist && exit; }
done
The code above greps the client name from the log file, and using awk
, added .log
at the end of each client field. From the output, I'm trying to pass eachclientname.log
from each field into one variable, i.e. alertfiles
, and construct a path to be tested for the file existence.
The number of clients is indefinite and may vary from time to time.
The code I have returns the client name as a whole:
"Clients: Apple.log
Samsung.log
Nokia.log
....."
I'm unsure of how to pass each client name one by one into the loop, so that each client name log file will be tested if it exists or not. How can I do this?
export alertfiles="*_$clients" #path/to/each/client/logfiles
I want to have $clients
output listed here one by one, so that it returns all client name one by one, and not as a whole thing, and I can pass that into the loop, so the client log filename gets checked one by one.
Solution
Use bash arrays.
(BTW: I can't test this as you have not supplied an example of the input data)
clientlist=/path/to/logfile/which/consists/of/client/names
logfilebase=/path/to/where/the/logfiles/should/exist
declare -a clients=($(grep -i 'list of client assets:' $clientlist | cut -d":" -f1))
for item in "${clients[@]}"; do
if [ -e ${logfilebase}/${item}.log ]; then
echo "$item exists"
else
echo "$item does not exist - quit"
exit 1
fi
done
Answered By - Jay M Answer Checked By - Willingham (WPSolving Volunteer)