0

My script

#!/bin/bash

set -eu

usrFile="${1}"

while read -r usrCMD
do exec -e "${usrCMD}" || echo_fun "${usrCMD}"
done < "$usrFile"

echo_fun is a function that prints the message.

In the echo_fun, I want to pass the error message of command exec -e "${usrCMD}"

Is this possible?

JDev
  • 1,662
  • 4
  • 25
  • 55
  • What is the `-e` option to `exec`? Or is that the error message you're trying to catch? – Barmar Oct 07 '21 at 20:31
  • 2
    Why are you using `exec`? That will end the loop because it replaces the shell process with the command it's executing. Did you mean to use `eval`? – Barmar Oct 07 '21 at 20:32

1 Answers1

1

Assign stdout to a variable, as explained in How to store standard error in a variable

Then pass that variable to echo_fun

while read -r usrCMD; do
    error=$(exec -e "$usrCMD" 2>&1 >/dev/null) || echo_fun "$usrCMD $error"
done < "$usrFile"
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Putting `exec` inside `$( )` runs it in a subshell, which rather defeats the usual purpose of `exec`. (Although I'm not sure that usual purpose is what's actually intended here...) – Gordon Davisson Oct 07 '21 at 22:07
  • @GordonDavisson I made the point that `exec` is probably not what he wants in a comment above. – Barmar Oct 07 '21 at 22:41
  • Unless he wants to loop until one of the `exec`s succeeds, printing the errors from the non-succeeding ones. – Barmar Oct 07 '21 at 22:42