Get current directory name (without full path) in a Bash script
How would I get just the current working directory name in a bash script, or even better, just a terminal command.
pwd
gives the full path of the current working directory, eg /opt/local/bin
but I only want bin
No need for basename, and especially no need for a subshell running pwd (which adds an extra, and expensive, fork operation); the shell can do this internally using parameter expansion:
result=${PWD##*/} # to assign to a variable
printf '%sn' "${PWD##*/}" # to print to stdout
# ...more robust than echo for unusual names
# (consider a directory named -e or -n)
printf '%qn' "${PWD##*/}" # to print to stdout, quoted for use as shell input
# ...useful to make hidden characters readable.
Use the basename
program. For your case:
% basename "$PWD"
bin
$ echo "${PWD##*/}"
链接地址: http://www.djcxy.com/p/1682.html
上一篇: 如何将变量设置为Bash中命令的输出?