我有一段脚本基本上可以计算当前目录中目录使用的空间量,但我需要帮助理解一些语法和语言礼节。
这是脚本:
#!/bin/bash
# This script prints a little histogram of how much space
# the directories in the current working directory use
error () {
echo "Error: $1"
exit $2
} >&2
# Create a tempfile (in a BSD- and Linux-friendly way)
my_mktemp () {
mktemp || mktemp -t hist
} 2> /dev/null
# check we are using bash 4
(( BASH_VERSINFO[0] < 4 )) && error "This script can only be run by bash 4 or higher" 1
# An array to keep all the file sizes
declare -A file_sizes
declare -r tempfile=$(my_mktemp) || error "Cannot create tempfile" 2
# How wide is the terminal?
declare -ir term_cols=$(tput cols)
# Longest file name, Largest file, total file size
declare -i max_name_len=0 max_size=0 total_size=0
# A function to draw a line
drawline () {
declare line=""
declare char="-"
for (( i=0; i<$1; ++i )); do
line="${line}${char}"
done
printf "%s" "$line"
}
# This reads the output from du into an array
# And calculates total size and maximum size, max filename length
read_filesizes () {
while read -r size name; do
file_sizes["$name"]="$size"
(( total_size += size ))
(( max_size < size )) && (( max_size=size ))
(( max_file_len < ${#name} )) && (( max_file_len=${#name} ))
done
}
# run du to get filesizes
# Using a temporary file for output from du
{ du -d 0 */ || du --max-depth 0 *; } 2>/dev/null > "$tempfile"
read_filesizes < "$tempfile"
# The length for each line and percentage for each file
declare -i length percentage
# How many columns may the lines take up?
declare -i cols="term_cols - max_file_len - 10"
for k in "${!file_sizes[@]}"; do
(( length=cols * file_sizes[$k] / max_size ))
(( percentage=100 * file_sizes[$k] / total_size ))
printf "%-${max_file_len}s | %3d%% | %s\n" "$k" "$percentage" $(drawline $length)
done
printf "%d Directories\n" "${#file_sizes[@]}"
printf "Total size: %d blocks\n" "$total_size"
# clean up
rm "$tempfile"
exit 0
在read_filesizes()
的第一行和第二行我用粗体突出显示的函数,为什么两个变量 (size name)
如果 name
正在创建正在分配给 size
在数组中?
在同一个函数中,(( max_size < size )) && (( max_size=size ))
这条线对我来说似乎很奇怪,因为这两个表达式怎么可能都是真的?
然后在for循环的第一行,(( **length=cols** * file_sizes[$k] / max_size ))
我不明白为什么变量 length
分配给 cols
..为什么一开始就分别定义它们?
最佳答案
虽然我不是 100% 确定语法,但它似乎足以回答您的问题:
第一个问题
why are two variables (size name) being created if the name is being assigned to size in the array?
看起来像name
保存文件名和size
保存文件大小。然后赋值file_sizes["$name"]="$size"
存储由文件名索引的文件大小。
第二个问题
(( max_size < size )) && (( max_size=size ))
我相信这一行指定了 size
至 max_size
如果以前的值为 max_size
小于 size
.目标是最后 max_size
将容纳最大文件的大小。
第三个问题
(( length=cols * file_sizes[$k] / max_size ))
这将计算为每个文件显示的行的长度(其目标可能是说明文件与最大文件相比的相对大小)。行的长度与文件的大小有关。 cols
是为最大文件(大小为 max_size
的文件)显示的行的长度。 cols
= 终端的长度 - 最长文件名的长度 - 10.
关于linux - 多变量定义和赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24479490/