2

I have the following script which prints various file stats, which was kindly supplied by another user (choroba) (link).

Is there a way that this can be amended to report just the directory name of each file and not the full file path with the file name? I have tried changing filepath with dirname and I get a series of errors saying No such file or directory. Thanks for any advice.

#!/bin/bash
set -eu

filepath=$1
qfilepath=${filepath//\\/\\\\}   # Quote backslashes.
qfilepath=${qfilepath//\"/\\\"}  # Quote doublequotes.

file=${qfilepath##*/}            # Remove the path.

stats=($(stat -c "%s %W %Y" "$filepath"))
size=${stats[0]}
ctime=$(date --date @"${stats[1]}" +'%d/%m/%Y %H:%M:%S')
mtime=$(date --date @"${stats[2]}" +'%d/%m/%Y %H:%M:%S')

md5=$(md5sum < "$filepath")
md5=${md5%% *}                   # Remove the dash.

printf '"%s","%s",%s,%s,%s,%s\n' \
        "$file" "$qfilepath" "$size" "$ctime" "$mtime" $md5
1
  • I have tried changing filepath with dirname : Where in the code posted is the invocation of dirname? Commented Aug 19, 2021 at 10:11

2 Answers 2

0

You can use a combination of dirname and basename, where:

dirname will strip the last component from the full path;

basename will get the last component from the path.

So to summarize: $(basename $(dirname $qfilepath)) will give you the name of the last directory in the path. Or, for the full path without the file name - just $(dirname $qfilepath).

0

Although I do not see anything in the script snippet which would produce a recursive list, you can get the directory name output with adding dir=$(dirname $filepath) and modifying your printf output to use $dir instead of $file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.