It's not a problem with relative paths -- this happens because the shell evaluation model does tilde expansion BEFORE parameter expansion. Skipping back up to the very beginning of the evaluation process, with eval, introduces security bugs -- so if one REALLY needs to support this (and I argue, strongly, that it's a bad idea), a safe implementation (targeting platforms with the getent
command available) would look like the following:
expandPath() {
local path
local -a pathElements resultPathElements
IFS=':' read -r -a pathElements <<<"$1"
: "${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
' "${result%:}"
}
...to use this for a path read from a file safely:
printf '%s
' "$(expandPath "$(<file)")"
Alternately, a simpler approach that uses eval
carefully:
expandPath() {
case $1 in
~[+-]*)
local content content_q
printf -v content_q '%q' "${1:2}"
eval "content=${1:0:2}${content_q}"
printf '%s
' "$content"
;;
~*)
local content content_q
printf -v content_q '%q' "${1:1}"
eval "content=~${content_q}"
printf '%s
' "$content"
;;
*)
printf '%s
' "$1"
;;
esac
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…