在 Bash 中展开 ~
Expand ~ in Bash
我倾向于在工作日访问相同的目录。使用 dirs -v 命令我可以在文件中保存一个列表
dirs -v > last-lines.txt
我希望能够在新的终端中重新读取这个文件并推送到该行的每个目录。我有的是
cat ~/last-list.txt | while read line; do pushd $line; done
我遇到的问题是“~”没有展开,因此 pushd 失败并显示
-bash: pushd: ~/director-name: No such file or directory
有没有强制'~'扩展到完整路径,或者更聪明的方法来完成上述任务?
谢谢
将pushd $line;
更改为:
pushd "${line/#\~/$HOME}";
~
将扩展为 $HOME
注意:使用双引号处理路径中的空格
您在无用地使用 cat
。这里根本不需要。
从文件中读取行:
while IFS= read -r line;do
#do something
done < filepath
来自 Charles Duffys' answer to this question
的完整但更复杂的解决方案
expandPath() {
local path
local -a pathElements resultPathElements
IFS=':' read -r -a pathElements <<<""
: "${pathElements[@]}"
for path in "${pathElements[@]}"; do
: "$path"
case $path in
"~+"/*)
path=$PWD/${path#"~+/"}
;;
"~-"/*)
path=$OLDPWD/${path#"~-/"}
;;
"~"/*)
path=$HOME/${path#"~/"}
;;
"~"*)
username=${path%%/*}
username=${username#"~"}
IFS=: read _ _ _ _ _ homedir _ < <(getent passwd "$username")
if [[ $path = */* ]]; then
path=${homedir}/${path#*/}
else
path=$homedir
fi
;;
esac
resultPathElements+=( "$path" )
done
local result
printf -v result '%s:' "${resultPathElements[@]}"
printf '%s\n' "${result%:}"
}
用法:
pushd "$(expandPath "$line")"
"$(expandPath "$line")"
为扩展路径
我倾向于在工作日访问相同的目录。使用 dirs -v 命令我可以在文件中保存一个列表
dirs -v > last-lines.txt
我希望能够在新的终端中重新读取这个文件并推送到该行的每个目录。我有的是
cat ~/last-list.txt | while read line; do pushd $line; done
我遇到的问题是“~”没有展开,因此 pushd 失败并显示
-bash: pushd: ~/director-name: No such file or directory
有没有强制'~'扩展到完整路径,或者更聪明的方法来完成上述任务?
谢谢
将pushd $line;
更改为:
pushd "${line/#\~/$HOME}";
~
将扩展为 $HOME
注意:使用双引号处理路径中的空格
您在无用地使用 cat
。这里根本不需要。
从文件中读取行:
while IFS= read -r line;do
#do something
done < filepath
来自 Charles Duffys' answer to this question
的完整但更复杂的解决方案expandPath() {
local path
local -a pathElements resultPathElements
IFS=':' read -r -a pathElements <<<""
: "${pathElements[@]}"
for path in "${pathElements[@]}"; do
: "$path"
case $path in
"~+"/*)
path=$PWD/${path#"~+/"}
;;
"~-"/*)
path=$OLDPWD/${path#"~-/"}
;;
"~"/*)
path=$HOME/${path#"~/"}
;;
"~"*)
username=${path%%/*}
username=${username#"~"}
IFS=: read _ _ _ _ _ homedir _ < <(getent passwd "$username")
if [[ $path = */* ]]; then
path=${homedir}/${path#*/}
else
path=$homedir
fi
;;
esac
resultPathElements+=( "$path" )
done
local result
printf -v result '%s:' "${resultPathElements[@]}"
printf '%s\n' "${result%:}"
}
用法:
pushd "$(expandPath "$line")"
"$(expandPath "$line")"
为扩展路径