result=${PWD##*/} # to assign to a variableresult=${result:-/} # to correct for the case where PWD=/
printf '%s\n' "${PWD##*/}" # to print to stdout# ...more robust than echo for unusual names# (consider a directory named -e or -n)
printf '%q\n' "${PWD##*/}" # to print to stdout, quoted for use as shell input# ...useful to make hidden characters readable.
dirname=/path/to/somewhere//shopt -s extglob # enable +(...) glob syntaxresult=${dirname%%+(/)} # trim however many trailing slashes existresult=${result##*/} # remove everything before the last / that still remainsresult=${result:-/} # correct for dirname=/ caseprintf '%s\n' "$result"
或者,没有extglob:
dirname="/path/to/somewhere//"result="${dirname%"${dirname##*[!/]}"}" # extglob-free multi-trailing-/ trimresult="${result##*/}" # remove everything before the last /result=${result:-/} # correct for dirname=/ case