Advertisement
markuspeloquin

the best u()

Dec 7th, 2017
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.96 KB | None | 0 0
  1. # in ~/.zshrc
  2.  
  3. alias uu='u 2'
  4. alias uuu='u 3'
  5.  
  6. # u
  7. # u CMD [ARG...]
  8. # u INTEGER
  9. # u INTEGER CMD [ARG...]
  10. # u DOTS                 e.g. `u ....` goes up four directories
  11. # u DOTS CMD [ARG...]
  12. function u {
  13.   local count where
  14.   if [[ $# = 0 ]]; then
  15.     # `u`
  16.     cd ..; return 0
  17.   fi
  18.   if [[ $1 =~ /^[1-9][0-9]*$/ ]]; then
  19.     # `u INTEGER [CMD [ARG...]]`
  20.     where=$(_u_cds $1); shift 1
  21.   else if [[ $1 =~ /^\.+$/ ]]; then
  22.     # `u DOTS [CMD [ARG...]]`
  23.     where=$(_u_cds ${#1}; shift 1
  24.   else
  25.     # `u CMD [ARG...]`
  26.     where=.
  27.   fi
  28.   if [[ $# = 0 ]]; then
  29.     # `u [INTEGER | DOTS]`
  30.     # change cwd and return
  31.     cd $where; return $?
  32.   fi
  33.   # `u [INTEGER | DOTS] CMD [ARG...]
  34.   # run $@ from the directory; don't change our cwd
  35.   (cd $where && $@); return $?
  36. }
  37.  
  38. function _u_cds {
  39.   local count=$1 where=.
  40.   for ((i = 0; i < $count; i++)); do where=$where/..; done
  41.   # strip leading ./
  42.   [[ $where != . ]] && where=${where:2}
  43.   echo $where
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement