开发者

last n elements of an array

I'm trying to write a function that will print out the last 3 elements of $PWD, with a '...' beforehand if there are more than 3 elements.

e.g.

/home/nornagon/src             --> ~/src
/home/nornagon/src/foo/bar/baz --> ...foo/bar/baz

This is my code so far, but $foo[-3,-1] doesn't work if the array has too few elements in it.

function custom_pwd() {
  d=${PWD/#$HOME/\~}
  d=(${(s:/:)d})开发者_如何学运维
  echo $d[-4,-1]
}


The zsh already has some nifty prompt processing available with print's -P option. This should do the trick:

custom_pwd() {
   d=$(print -P '%3~')
   case $d in
      ('~'*|/*) echo "$d";;
      (*)       echo "...$d"
   esac
}

See man zshmisc, section "EXPANSION OF PROMPT SEQUENCES" for the gory details.


Here's what I came up with, though it's not terribly elegant:

function custom_pwd() {
  local d slash
  d=${PWD/#$HOME/\~}
  case $d in
    /*) slash=/ ;;
    *) slash= ;;
  esac
  d=(${(s:/:)d})
  d[1]=$slash$d[1]
  num=$#d
  ellipsis=
  if (( num > 3 )); then num=3; ellipsis='…'; fi
  echo $ellipsis${(j./.)d[-$num,-1]}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜