0

I tried to run this script:

my_cmd="echo -n 0"

if [ $($(my_cmd)) == 0 ]; then
    echo "Yes"
else
    echo "No"
fi

but i got the following erros:

main.bash: line 7: my_cmd: command not found
main.bash: line 7: [: ==: unary operator expected
No

I don't sure how can i fix this issue by using the command via string variable. I know that in this way it's working: if [ $(echo -n 0) == 0 ]; but I want to do it with variable the save the command.

  • `[ "$($my_cmd)" = 0 ]`. But, do not put commands inside variables; complex cases will fail (see [BashFAQ/50](http://mywiki.wooledge.org/BashFAQ/050)). Variables are to hold data. – M. Nejat Aydin Mar 19 '23 at 09:17
  • Storing commands in variables doesn't always work. Variables are really intended for storing data, not executable code. Functions are what's intended for storing executable code, and they're much better at it. See [BashFAQ #50: "I'm trying to put a command in a variable, but the complex cases always fail!"](http://mywiki.wooledge.org/BashFAQ/050) – Gordon Davisson Mar 19 '23 at 17:29
  • The immediate problem is the doubled `$($(...))` but as the duplicate explains, basically don't do this. – tripleee Mar 20 '23 at 13:01

1 Answers1

2

The correct way is to use arrays if storing a command in a parameter is really needed.

my_cmd=(echo -n 0)

if [[ $("${my_cmd[@]}") == 0 ]]; then

But it will fail in some cases like when the command has globs. It's recommended to store them in functions instead.

my_cmd() {
    echo -n 0
}

if [[ $(my_cmd) == 0 ]]; then

Also avoid the practice where values are "returned" through command substitution. Use temporary variables instead.

my_cmd() {
    __=0
}

my_cmd

if [[ $__ == 0 ]]; then

Or

my_cmd() {
    __=0
}

my_cmd
my_cmd_result=$__ # For long-term use. Variable name of course can be simpler.

if [[ $my_cmd_result == 0 ]]; then

And if 0 is meant to be an exit status (not as a general integer), just use return and $?.

konsolebox
  • 72,135
  • 12
  • 99
  • 105
  • Following this progression, try not to rely on the *output* of a function at all, but rather an exit status it produces. – chepner Mar 19 '23 at 15:22