Home > Back-end >  Parse multiple echo values in bash script
Parse multiple echo values in bash script

Time:09-18

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

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related