0

Here I have the simple code in which I am trying to store the value of program output to a variable in bash.

#!/bin/bash
i=0
for value in {1..10}
do 
    variable=`$value | ./unpackme`
    str="What's my favorite number? Sorry, that's not it!"
    if [[ "$variable" == "$str" ]]
    then
        echo "hello"
    fi
done

The output I am getting is as follows: Output screenshot Please help me fix this. Thanks in advance.

1 Answers1

0

You may try :

#!/bin/bash

str="What's my favorite number? Sorry, that's not it!"
for value in {1..10}; do
    variable=$(./unpackme <<< "$value")
    if [ "$variable" = "$str" ]; then
        echo "hello"
    fi
done

Some notes :

  • New style $(command) is preferred to `command`.
  • string in command <<< string is what is called a here string : command standard input is fed with string (think of it as : echo string | command).
  • [ "$variable" = "$str" ]: Take care of [[ "$a" == "$b" ]]/[[ "$a" = "$b" ]], they will consider the right part of ==/= as a pattern, and may not do what you want.
Bruno
  • 580
  • 5
  • 14