Bash的路径变量使用〜造成“没有这样的文件或目录” [英] Bash path variable using ~ resulting in 'No such file or directory'

查看:229
本文介绍了Bash的路径变量使用〜造成“没有这样的文件或目录”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

ls ~/Dev/Project/Assets/_Core/

我得到一个超级骗子目录列表!好极了!但是,如果我这样做:

I get a super duper directory listing! Yay! But if I do this:

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} 但没有任何工作?

推荐答案

作为部分的解决方案:

assetsPath=${assetsPath//'~'/$HOME}

这是什么的的地址是〜用户名扩张;如果你的 assetsPath 使用这个,那么你需要多一点的逻辑(我想我已经在一个单独的StackOverflow的答案补充;找问题)

What this doesn't address is ~username expansion; if your assetsPath uses this, then you need a bit more logic (which I think I've added in a separate StackOverflow answer; looking for the question).

它也没有解决非领先地位,它的不应的扩展。为了处理这两种极端情况,我要去自plagarize有点

It also doesn't address ~ in non-leading position, where it shouldn't be expanded. To handle both corner cases, I'm going to 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")

这篇关于Bash的路径变量使用〜造成“没有这样的文件或目录”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆