Parse multiple echo values in bash script

Viewed 53

I am trying to return a value from one script to another. However, in the child script there are multiple echos, so am not sure how to retrieve a specific one in the parent scrip as if I try to do return_val = $(./script.sh) then return_val will have multiple arguments. Any solution here?

script 1:

status=$(script2.sh)
if [ $status == "hi" ]; then
echo "success"
fi

script 2:

echo "blah"
status="hi"
echo $status
3 Answers

Solution 1) for this specific case, you could get the last line that was printed by the script 2, using the tail -1 command. Like this:

script1.sh

#!/bin/bash

status=$( ./script2.sh | tail -1 )
if [ $status == "hi" ]; then
  echo "success"
fi

script2.sh

#!/bin/bash

echo "blah"
status="hi"
echo $status

The restriction is that it will only work for the cases where you need to check the last string printed by the called script.

Solution 2) If the previous solution doesn't apply for your case, you could also use an identifier and prefix the specific string that you want to check with that. Like you can see below:

script1.sh

#!/bin/bash

status=$( ./script2.sh | grep "^IDENTIFIER: " | cut -d':' -f 2 )
if [ $status == "hi" ]; then
  echo "success"
fi

script2.sh

#!/bin/bash

echo "blah"
status="hi"
echo "IDENTIFIER: $status"

The grep "^IDENTIFIER: " command will filter the strings from the called script, and the cut -d':' -f 2 will split the "IDENTIFIER: hi" string and get the second field, separated by the ':' character.

You might capture the output of script2 into a bash array and access the element in the array you are interested in. Contents of script2:

#!/bin/bash

echo "blah" 
status="hi" 
echo $status

Contents of script1:

#!/bin/bash

output_arr=( $(./script2) ) 
if [[ "${output_arr[1]}" == "hi" ]]; then 
    echo "success" 
fi

Output:

$ ./script1 
success

Script1:-

#!/bin/sh

cat > ed1 <<EOF
1p
q
EOF

next () {
[[ -z $(ed -s status < ed1 | grep "hi") ]] && main
[[ -n $(ed -s status < ed1 | grep "hi") ]] && end
}

main () {
sleep 1
next
}

end () {
echo $(ed -s status < ed1)
exit 0
} 

Script2:-

#!/bin/sh 

echo "blah"
echo "hi" >> status
Related