在Bash中展开〜

时间:2015-06-02 15:17:03

标签: bash shell scripting

我倾向于在工作日期间访问相同的目录。使用dirs -v命令我可以在文件中保留一个列表

dirs -v>最后lines.txt

我希望能够在新终端中重新读取此文件并推送到该行的每个目录。我拥有的是

cat ~/last-list.txt | while read line; do pushd $line; done

我遇到的问题是'〜'没有扩展,因此推送失败

-bash: pushd: ~/director-name: No such file or directory

无论如何强迫'〜'扩展到完整路径,或者更聪明的方式来实现上述目标?

由于

1 个答案:

答案 0 :(得分:1)

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 <<<"$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%:}"
}

用法:

pushd "$(expandPath "$line")"

"$(expandPath "$line")"是展开的路径