Peter Butkovic
Peter Butkovic

Reputation: 12149

bash: propagating exit code of command executed in alias

In bash, I'd like to propagate exit code of the particular command executed in alias, so that alias call itself would return it (exit with it).

Imagine the following example (Please note: command makes no sense, just demonstrates problem I face):

alias cda='cd \/a; exit_code=$?; echo "STATUS: $exit_code"; alias cdb='cd \/b'
cda && cdb

for me there are no such dirs as: /a and /b to make sure commands fail. I'd like to execute cdb alias only in case cda alias execution succeeded. However, as echo was the last command and it ended with exit status 0 => both are executed

What I've tried is:

alias cda='cd \/a; exit_code=$?; echo "STATUS: $exit_code"; exit $exit_code'; alias cdb='cd \/b'
cda && cdb

however this exits the shell completely => not feasible for me.

Any idea how to propagate the exit status (in my case $exit_code) as the alias exit status?

Upvotes: 3

Views: 2787

Answers (2)

anishsane
anishsane

Reputation: 20980

I have this a function in my .bashrc:

return_exitcode(){
    return $1
}

to simulate any required exit code (input checking is not done.).

With this, the alias would be:

alias cda='cd /a; exit_code=$?; echo "STATUS: $exit_code"; return_exitcode $exit_code'
alias cdb='cd /b; exit_code=$?; echo "STATUS: $exit_code"; return_exitcode $exit_code'

NOTEs:

  1. Using functions is ALWAYS preferred over aliases. Hence konsolebox's answer is the correct answer.
  2. This answer was added just because this small function is sometimes handy, while writing commands after one another with ;...

Upvotes: 1

konsolebox
konsolebox

Reputation: 75488

It's better that you just use functions over aliases:

cda() {
    cd /a
    exit_code=$?
    echo "STATUS: $exit_code"
    return "$exit_code" # optional
}

cdb() {
    cd /b
    exit_code=$?
    echo "STATUS: $exit_code"
    return "$exit_code" # optional
}

As for the alias you could try adding a test in the end:

alias cda='cd \/a; exit_code=$?; echo "STATUS: $exit_code"; [[ exit_code -eq 0 ]]'; alias cdb='cd \/b'

Upvotes: 8

Related Questions