Can I modify a terminal command to do additional stuff?

Solution 1:

You can put these lines in your .zsrhc or .bashrc

[ -z "$PS1" ] && return
function cd {
builtin cd "$@" && ls -F
}

Result ->

enter image description here

Explanation from this answer:

Earlier in my .bashrc I have: [ -z "$PS1" ] && return, and everything after that line only applies to interactive sessions, so this doesn't affect how cd behaves in scripts.

Further info from this comment:

[ -z "$PS1" ] checks if the $PS (interactive prompt variable) is "zero length" (-z). If it is zero length, this means it has not been set, so Bash must not be running in interactive mode. The && return part exits from sourcing .bashrc at this point, under these conditions.

Btw, thanks for the question, it's really cool :)

Edit :

Another solution would be to integrate your ls to your prompt; I'm sure that you can do that with OhMyZsh ;)

Solution 2:

I'd tend to make a new command for this. I think it would even be logical to combine them into a single one.

go() {
    if [ -d "$1" ]; then
        cd "$1" && ls
    else
        mkdir -p "$1" && echo "Created directory $1" && cd "$1"
    fi
}

Solution 3:

I have tried adding things like these to my .bashrc:

cd() {
    command cd "$@"
    command ls
}

mkdir() {
    command mkdir "$@"
    command cd "$@"
}

However, I've found that this can mess up scripts that use the overridden commands, and the option handling can be fragile (for example, if you want to pass -p to the above mkdir command, it's also passed to cd). Better would be just to define aliases with different names (say, c or mcd).

Solution 4:

I think functions are the way to go. Something like

chglist() {
    cd "$1" && ls
}

as an example.