获取文件属性

文件操作 / 基本操作

filePath="data/file.txt"

#要查看的文件
mkdir data
printf 'Line 1\nLine 2\n' > "$filePath"

#stat -c 接受格式(GNU coreutils):%s 是以字节为单位的大小
fileSize1=$(stat -c %s "$filePath")
#fileSize1 is 14

#第二种方法:wc -c 统计字节数;
#< 让输出中不带文件名
fileSize2=$(wc -c < "$filePath")
#fileSize2 is 14

#%Y 是修改时间,以自 1970 年起的秒数表示
timeChanges=$(stat -c %Y "$filePath")
(( $(date +%s) - timeChanges < 60 )) && isFresh=true || isFresh=false
#isFresh 为 true:文件刚刚被写入

#%W 是创建时间,但许多文件系统给出 0(未知);
#%Z 是权限最后一次变更的时间,而不是创建时间

#%a 和 %A 分别是数字和文本形式的权限
chmod 640 "$filePath"
rights=$(stat -c '%a %A' "$filePath")
#rights is "640 -rw-r-----"

#文件是否可读可写
[[ -r "$filePath" ]] && isReadable=true || isReadable=false
[[ -w "$filePath" ]] && isWritable=true || isWritable=false
#isReadable is true, isWritable is true

#路径的各个部分:## 从左侧截去最长的匹配,
#% 从右侧截去最短的匹配
fileName=${filePath##*/}
#fileName is "file.txt"
extension=${filePath##*.}
#extension is "txt"
nameOnly=${fileName%.*}
#nameOnly is "file"
fileDir=${filePath%/*}
#fileDir is "data"

#basename 和 dirname 能做同样的事;对不含 "/" 的名称,
#dirname 给出 ".",而 ${filePath%/*} 给出名称本身
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