0

From a reddit thread I found this short snippet you can add to your .bashrc that automatically shows the list of contents of a dir you've cd'd into:

cd() {
    builtin cd "$@" && ls
}

Though this is great but I would like this to be effective only if the folder I've cd'd into is a sub-directory of $HOME. Is there any way to do it?

1 Answer 1

0

The following executes the ls only if the current directory (after successfully changing it) is the user's home directory, or a subdirectory thereof:

cd () {
    builtin cd "$@" || return

    case $PWD in
        "$HOME"|"$HOME"/*) ls
    esac
}

Alternatively, with a [ ... ] and [[ ... ]] test in bash:

cd () {
    builtin cd "$@" || return

    if [ "$PWD" = "$HOME" ] || [[ $PWD == "$HOME"/* ]]; then
        ls
    fi
}

Alternatively, with an extended globbing pattern in bash:

cd () {
    builtin cd "$@" || return

    if [[ $PWD == @("$HOME"|"$HOME"/*) ]]; then
        ls
    fi
}
4
  • Thank you, this works. I completely forgot I could use $PWD to get the full path, instead I used something like $(readlink -f $@) lol. Dec 7, 2022 at 8:24
  • Or [[ "$PWD" != "$OLDPWD" && "$PWD/" = "$HOME"/* ]] Dec 7, 2022 at 10:22
  • @StéphaneChazelas Yes, but that would not evaluate to true for cd ., i.e. when the current directory does not change (which I don't know matters to the user in the question).
    – Kusalananda
    Dec 7, 2022 at 10:46
  • I was not suggesting to use that in place of the || return. Just those two things: (1) avoid ls when the current working directory does not change (which I agree may or may not be desirable) (2) simpler way to check that $PWD is or is within $HOME. Ideally we'd also want to check using canonical paths (like using realpath/readlink -f) as it's not uncommon for home directory paths to have symlink components in enterprise environment at least. Dec 7, 2022 at 11:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .