2

When I execute a command that has been alias to a series of commands, what value gets returned back to the shell? Also, assuming I have an alias defined like this:

alias doit 'cd ~/some/dir; ./my_app; cd -'

How can I make the return value that ./my_app returns the return value of the entire aliased command?

3 Answers 3

4

An alias is almost a textual substitution. So after your alias definition, typing doit is equivalent to typing cd ~/some/dir; ./my_app; cd -. This is a syntactically correct list of commands, and its return value is the return value of the last command in the sequence, here cd -.

Other answers show a general way of saving the status of an intermediate command and returning it. However, in this specific case, there is a better way to express this sequence of actions: instead of changing to another directory and then changing back, execute the action that requires a different current directory inside a subshell, so that the current directory of the shell doesn't change at all.

doit () {
  (cd ~/some/dir && ./my_app "$@")
}

I've made two additional improvements:

  • Use && rather than ; between the commands, so as not to try to execute my_app if the cd command failed.
  • Allow arguments to be passed to my_app: if you run doit foo bar, my_app is invoked with the two arguments foo and bar.
2
  • Excelent answer, thanks! One question: What is it that cause this to be run in a sub-shell? Is it the wrapping of the commands in parenthesis or just the fact that they are being run in a shell function?
    – heavyd
    Sep 23, 2010 at 23:10
  • @heavyd: The parentheses are the syntax for subshells. The code in a shell function is not isolated from its context, so that you can e.g. run cd in a function and have it affect the caller. Sep 24, 2010 at 7:16
1

The value returned is the exit status of the last command executed.

Maybe you should use a function instead:

function doit
{
    cd ~/some/dir
    ./my_app
    local X=$?
    cd -
    return $X
}

From man Bash:

$? Expands to the status of the most recently executed foreground pipeline.

Note: The local command ensures that no global variable (with same name) is modified.

0

Code blocks in the shell generally return the return value of the last command in the block. In your case, that would be cd -, which is unlikely to ever fail.

I think you can get what you want by turning that alias into a shell function:

doit () {  
    cd ~/some/dir  
    ./my_app  
    RETVAL=$?  
    cd -  
    return $RETVAL  
}

You must log in to answer this question.

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