[cdiff] Update license to GPLv3+
[tinyapps.git] / tpwd
blob7bd9df4bd5826e907fdb0e6b6ec6352a72805ca2
1 #!/bin/sh
2 ##
3 ## Truncates pwd to specified number of characters
4 ## Copyright (c) 2005-2014 by Michal Nazareicz (mina86/AT/mina86.com)
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ## This is part of Tiny Applications Collection
20 ## -> http://tinyapps.sourceforge.net/
24 case "${1-}" in --function|--bash|--zsh)
25 echo "tpwd: $1 option is deprecated" >&2
26 echo "tpwd: simply \". '$0'\" instead" >&2
27 echo ". '$0'"
28 exit
29 esac
32 tpwd() {
33 case "${1-}" in
34 -[LP]) __tpwd="$(pwd $1)"; shift ;;
35 *) __tpwd="$PWD"
36 esac
38 case "${1-}" in
39 -n) shift; set -- '%s' "$@" ;;
40 *) set -- '%s\n' "$@"
41 esac
43 if [ $# -gt 4 ] || ( [ $# -gt 1 ] && [ X"${2#-}" != X"$2" ] ); then
44 cat >&2 <<EOF
45 usage: tpwd [ -L | -P ] [ -n ] [<len> [<trunc> [<tlen>]]]
46 source /path/to/tpwd in interactive shell, define tpwd function
47 -L or -P use 'pwd -L' or 'pwd -P' instead of \$PWD
48 -n don't print new line character at the end
49 <len> maximum length of printed string [30]
50 <trunc> string to print at the beginning if pwd was trunced [...]
51 <tlen> length of <trunc> (useful if using ANSI codes)
53 It may be used in PS1 varaible to truncate very long PWD's which
54 normaly would took a whole line (or more), eg:
55 PS1='[\\u@\\h \$(tpwd -n 30 {)]\\$ ' # works in bash
57 EOF
58 unset __tpwd
59 [ X"${2-}" = X"--help" ] || [ X"${2-}" = X"-h" ]
60 set -u
61 return $?
64 case $__tpwd in //*)
65 __tpwd="${__tpwd#/}"
66 esac
68 if [ -n "${HOME-}" ] && [ -n "${HOME%/}" ]; then
69 case "$__tpwd" in
70 "${HOME%/}") __tpwd='~' ;;
71 "${HOME%/}"/*) __tpwd='~'/${__tpwd#"${HOME%/}/"}
72 esac
75 set -- "$1" "${2-30}" "${3-...}" "${4-}"
76 if [ ${#__tpwd} -le "$2" ]; then
77 set -- "$1" '' ''
78 else
79 set -- "$1" $(( $2 - ${4:-${#3}} )) "$3"
80 if [ $2 -le 0 ]; then
81 __tpwd=$
82 elif [ -n "${BASH_VERSION-}${ZSH_VERSION-}" ]; then
83 __tpwd=${__tpwd:$(( ${#__tpwd} - $2 ))}
84 else
85 __tpwd=$(expr "$__tpwd" : '.*\(.\{'$2'\}\)')
89 set -- "$1" "$3$__tpwd"
90 unset __tpwd
91 printf "$@"
94 [ -n "${__tpwd_sourcing-}" ] || [ -z "${-##*i*}" ] || tpwd "$@"