bms9nmh bms9nmh - 4 months ago 9
Linux Question

while loop read command is printing location rather than just file name- why is this?

Can someone explain to me why when I print the $file_name variable in the below script, does it show the location and not just the file name? It's not necessarily a bad thing because I'm working towards trying to print the location, the md5sum and the file name separately, but I'm confused at this point why this is printing the location.

here is the text file:

day19-pgm-am_0946-23_p1_13.mov
day19-pgm-am_0951-23_p1_14.mov
day19-pgm-am_1016-23_p1_19.mov
day19-pgm-am_1021-23_p1_20.mov
day19-pgm-am_1111-23_p1_30.mov


.

#!/bin/bash


file=/location/md5sum.txt


while IFS=, read -ra arr; do
while IFS= read -r -d '' file_name; do
md5=($(md5sum "$file_name"))
printf '%s\n' "$file_name $md5"
done < <(find . -name "${arr[0]}" -print0)
done<"$file"


here is the current output, as you can see the data shows the files releative location:

./level1/level2/day19-pgm-am_0946-23_p1_13.mov d41d8cd98f00b204e9800998ecf8427e
./level1/day19-pgm-am_0946-23_p1_13.mov d41d8cd98f00b204e9800998ecf8427e
./level1/level2/day19-pgm-am_0951-23_p1_14.mov d41d8cd98f00b204e9800998ecf8427e
./level1/day19-pgm-am_0951-23_p1_14.mov d41d8cd98f00b204e9800998ecf8427e
./level1/level2/day19-pgm-am_1016-23_p1_19.mov d41d8cd98f00b204e9800998ecf8427e
./level1/day19-pgm-am_1016-23_p1_19.mov d41d8cd98f00b204e9800998ecf8427e
./level1/level2/day19-pgm-am_1021-23_p1_20.mov d41d8cd98f00b204e9800998ecf8427e
./level1/day19-pgm-am_1021-23_p1_20.mov d41d8cd98f00b204e9800998ecf8427e
./level1/level2/day19-pgm-am_1111-23_p1_30.mov d41d8cd98f00b204e9800998ecf8427e
./level1/day19-pgm-am_1111-23_p1_30.mov d41d8cd98f00b204e9800998ecf8427e

Answer

$file_name you're getting from find is the relative path to the file found by find from the directory supplied to find.

You can get the directory and the filename like this:

directory=`dirname $file_name`
just_filename=`basename $file_name`

And print these.

Comments