我正在尝试在 Bash 中编写 dirname 函数,以便它不使用任何外部命令。
function dirname() {
local path=$1
[[ $path =~ ^[^/]+$ ]] && dir=. || { # if path has no slashes, set dir to .
[[ $path =~ ^/+$ ]] && dir=/ || { # if path has only slashes, set dir to /
local IFS=/ dir_a i
read -ra dir_a <<< "$path" # read the components of path into an array
dir="${dir_a[0]}"
for ((i=1; i < ${#dir_a[@]}; i++)); do # strip out any repeating slashes
[[ ${dir_a[i]} ]] && dir="$dir/${dir_a[i]}" # append unless it is an empty element
done
}
}
[[ $dir ]] && printf '%s\n' "$dir" # print only if not empty
}
为了/
从路径中删除任何重复,我不得不使用数组逻辑。有没有更简单的方法来做同样的Bash 参数扩展?我试过了,但我似乎没有做对。
基本上,我想用一个斜杠替换所有出现的多个连续斜杠。