-1

I'm trying to write a simple function to debug my script easily and making my code simpler. (Still stuck after 3 hours)

I want to pass to this function 3 arguments

  1. A command
  2. A success string
  3. And an error string

The function is supposed to execute the command and print the proper string whether it's a success or not. What I mean by successful is when the command prints something in the output.

Here is what I've tried (On CentOS7) :

#!/bin/bash
CMD=$(yum list installed | egrep "yum.utils.\w+" | cut -d " " -f1)
SUCCESS="YES"
ERROR="NO"
foo() {
if ["$1" != ""]; then
    echo -e "$2"
else
    echo -e "$3"
fi
}
foo $CMD $SUCCESS $ERROR

Unfortunately, I'm encountering 2 problems :

  • Firstly, when the $CMD is empty, the first parameter will be $SUCCESS instead of an empty string (the behaviour I want)
  • Secondly, I want to remove the console output (> /dev/null 2>&1 ???).

Do you think it's possible? Do you have any idea how to do it? Otherwise, is there an easier way with the eval command?

Thanks for reading and have a nice day,

Valentin M.

------------------ Correction ------------------

#!/bin/bash
CMD=$(yum list installed | grep -E "yum.utils.\w+" | cut -d " " -f1)
SUCCESS="YES"
ERROR="NO"
foo() {
if [ "$1" != "" ]; then
    echo -e "$2"
else
    echo -e "$3"
fi
}
foo "$CMD" "$SUCCESS" "$ERROR"

I found out a similar topic here: Stack overflow : How to write a Bash function that can generically test the output of executed commands?

1 Answers1

0

Unfortunately, I'm encountering 2 problems :

  • Firstly, when the $CMD is empty, the first parameter will be $SUCCESS instead of an empty string (the behaviour I want)

If you follow the suggestion in William Pursell's comment above, this problem is solved, since an empty first parameter is then passed.

  • Secondly, I want to remove the console output (> /dev/null 2>&1 ???).

I assume by console output you mean the output to STDERR, since STDOUT is assigned to CMD. Your > /dev/null 2>&1 is unsuitable, as it redirects also STDOUT to /dev/null; just do this with STDERR:

CMD=$(yum list installed 2>/dev/null | egrep "yum.utils.\w+" | cut -d " " -f1)
Armali
  • 18,255
  • 14
  • 57
  • 171
  • Yes, that's what i needed for my first problem. But for the second I don't want the command to write to STDOUT and STDERR either. I just want to store the result of the command in a variable. – Valentin Magnan Mar 17 '21 at 08:38
  • Edit : Finally it seems to work the way I want. It's not prompting the result of the command to my console. – Valentin Magnan Mar 17 '21 at 08:50
  • You do _want the command to write to STDOUT_, because that's exactly what gets stored in `CMD`. – Armali Mar 17 '21 at 09:44