获取文件属性

文件操作 / 基本操作

filePath="data/file.txt"

#the file to look at
mkdir data
printf 'Line 1\nLine 2\n' > "$filePath"

#stat -c takes a format (GNU coreutils): %s is the size in bytes
fileSize1=$(stat -c %s "$filePath")
#fileSize1 is 14

#the second method: wc -c counts the bytes;
#< keeps the file name out of the output
fileSize2=$(wc -c < "$filePath")
#fileSize2 is 14

#%Y is the modification time in seconds since 1970
timeChanges=$(stat -c %Y "$filePath")
(( $(date +%s) - timeChanges < 60 )) && isFresh=true || isFresh=false
#isFresh is true: the file was written a moment ago

#%W is the creation time, but many file systems give 0 (unknown);
#%Z is the time of the last change of the rights, not the creation

#%a and %A are the rights as a number and as text
chmod 640 "$filePath"
rights=$(stat -c '%a %A' "$filePath")
#rights is "640 -rw-r-----"

#is readable and writable file
[[ -r "$filePath" ]] && isReadable=true || isReadable=false
[[ -w "$filePath" ]] && isWritable=true || isWritable=false
#isReadable is true, isWritable is true

#the parts of the path: ## cuts the longest match from the left,
#% the shortest from the right
fileName=${filePath##*/}
#fileName is "file.txt"
extension=${filePath##*.}
#extension is "txt"
nameOnly=${fileName%.*}
#nameOnly is "file"
fileDir=${filePath%/*}
#fileDir is "data"

#basename and dirname do the same; for a name without "/"
#dirname gives ".", while ${filePath%/*} gives the name itself
fileDir2=$(dirname "file.txt")
#fileDir2 is "."

echo "fileSize1 is $fileSize1"
echo "fileSize2 is $fileSize2"
echo "isFresh is $isFresh"
echo "rights is $rights"
echo "isReadable is $isReadable"
echo "isWritable is $isWritable"
echo "fileName is $fileName"
echo "extension is $extension"
echo "nameOnly is $nameOnly"
echo "fileDir is $fileDir"
echo "fileDir2 is $fileDir2"
rm -r data