如果我这样做:
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},但这也不起作用?
作为部分解决方案:
原文链接:https://www.f2er.com/bash/387061.htmlassetsPath=${assetsPath//'~'/$HOME}
这没有解决的是〜用户名扩展;如果你的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")