Reputation: 12149
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
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:
;
...Upvotes: 1
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