Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

bash - Change directory to a path specified in a file with tilde

I have a file, say: ~/cwd. The content of this file is a single line:

~/tmp

I want fo cd to this (~/tmp) dir. I'm trying:

> cd `cat ~/cwd`

And got:

-bash: cd: ~/tmp: No such file or directory

Why the RELATIVE paths failed? When the content of the ~/cwd is absolute path - it works.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...