0

I am constructing a wrapper function for bash 5.1 that would wake a command, and indent its output. If the command fails, then I want the wrapper to pass the command return code to the caller

indent() {
    local com_out=$($* 2>&1)
    local exit_code=$?
    echo -e "$com_out" | awk  '{ print "   │" $0 }'
    return $exit_code
}

However, I don't understand why it always return 0:

$ indent cp a b  
    │cp: cannot stat 'a': No such file or directory
$ echo $?
0

If I run the commands one at the time in my shell (zsh), replacing $* with an actual command, I get that $exit_command is indeed 1.

onlycparra
  • 607
  • 4
  • 22
  • 3
    [Shellcheck](https://www.shellcheck.net/) identifies two problems with the code. One of them is the cause of the lost exit code. – pjh Feb 27 '22 at 02:55
  • @pjh I came for a fish, I found a fishing pole, a fishing course, and a private river... Thanks a lot. With Shellcheck I was able to solve the issue – onlycparra Feb 27 '22 at 03:00
  • btw, it recommends me to use "$@" instead of $*. Would it be relevant in this context? – onlycparra Feb 27 '22 at 03:02
  • 2
    @onlycparra Yes, definitely. If you use `$*` then `indent ls "My File With Spaces.txt"` will fail. With `"$@"` it will work as expected. – that other guy Feb 27 '22 at 03:17
  • You tagged this [tag:bash] but claim that you are actually using [tag:zsh]. Fixing that is moot now, but they hre two distinct shells with entirely different codebases and somewhat different behaviors out of the box. – tripleee Feb 27 '22 at 07:33
  • @onlycparra, `"$@"` is necessary here. It's almost always the correct way to access the list of positional parameters. See [Accessing bash command line args $@ vs $*](https://stackoverflow.com/q/12314451/4154375). – pjh Feb 27 '22 at 23:30
  • 1
    @onlycparra, BTW, if you use the Bash [PIPESTATUS](https://www.gnu.org/software/bash/manual/bash.html#index-PIPESTATUS) array you can avoid using a local variable to hold the command exit status: `function indent { "$@" |& sed 's/^/ ¦/'; return "${PIPESTATUS[0]}"; }`. – pjh Feb 27 '22 at 23:38

0 Answers0