iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
👋

Shell command to get the parent directory name

に公開

Get the parent directory name

~/.ghq/github.com/elzup/anozonbiyori
$ basename ${PWD%/*}
elzup

Get the current directory name

~/.ghq/github.com/elzup/anozonbiyori
$ basename $PWD
anozonbiyori

Get names of two directories

$
~/.ghq/github.com/elzup/anozonbiyori
echo `basename ${PWD%/*}`/`basename $PWD`
elzup/anozonbiyori

Note

The part ${PWD%/*} involves string substitution.

Reference: Summary of string substitution in bash variables - Qiita

$ pwd
/Users/hiro/.ghq/github.com/elzup/anozonbiyori

$ echo ${PWD%/*} # Deletes the shortest match from the end up to /
/Users/hiro/.ghq/github.com/elzup

$ basename ${PWD%/*}
elzup

$ echo ${${PWD%/*}##*/}
elzup

Bonus: Creating aliases

I don't recommend this!

title=.zshrc
alias basename-current='basename ${PWD}'
alias basename-parent='echo `basename ${PWD%/*}`/`basename $PWD`'
alias reponame=basename-parent
GitHubで編集を提案

Discussion