如果我这样做:
ls ~/Dev/Project/Assets/_Core/
我得到一个超级duper目录列表!好极了!但如果我这样做:
assetsPath=$(head -n 1 .config | perl -ne 'print if s/^assets=(.*)/\1/g')
echo $assetsPath
ls $assetsPath
我明白了:
~/Dev/Project/Assets/_Core/ # this was the variable value from the echo
ls: ~/Dev/Project/Assets/_Core/: No such file or directory
我甚至尝试使用${assetsPath}
,但这也不起作用?
答案 0 :(得分:2)
作为部分解决方案:
assetsPath=${assetsPath//'~'/$HOME}
此无地址是~username
扩展;如果你的assetsPath
使用了这个,那么你需要更多逻辑(我认为我已经在单独的StackOverflow答案中添加了它;寻找问题)。
它也没有在非领先位置处理~
,而不应该扩展。要处理两个极端情况,我要转到self-plagarize a bit:
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\n' "${result%:}"
}
...然后:
assetsPath=$(expandPath "$assetsPath")