0

I have this bash script that runs calculus operations for me. It starts off with "read"...

How can I make Script A enter a value into Script B, read the output and dismiss Script B again?

Example:

#ScriptA.sh
a=12
b=4
[open Script B, enter $a and $b and read the result]
echo "The result is [the result of Script B]."

#ScriptB.sh
read x y
echo $(($x+$y))

Desired Output:

bash ScriptA.sh
The result is 16.

Of course it's about more complex maths but you get the idea. Note that, for convenience purposes, I don't want to change the structure of Script B (read x y). But I hope that there are some guys here that can solve this problem.

Thanks in advance.

1
  • It's not about just running script, it's about passing data to read command inside another script Commented Mar 19, 2018 at 22:57

2 Answers 2

2

You should do something like this:

#!/bin/bash

a=12
b=4

result=$(echo $a $b | ./script_b.sh)
echo "the result is $result"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It works for me in the form echo $(echo $a $b | bash script_b.sh). But now I have another problem mentioned in the comment below.
0

Script B should work like -bc does.

Example:

echo `echo "4^3.5" | -scriptb.sh`
[result]

Edit: I just came up with a part of the solution by myself and thought I'd share it:

# ScriptA.sh

echo `echo "44 33" | bash ScriptB.sh`

# ScriptB.sh

read x y
echo $(($x+$y))

Output:

bash ScriptA.sh
77

The next problem is my ScriptB.sh looks a little more like this:

# ScriptB.sh

until [[ 1 = 2 ]]; do
echo Enter x and y
read x y
    if [[ x = q ]]; then
    break 1
    fi
echo $(($x+$y))
done

This is in order to allow multiple inputs, if I want to use ScriptB manually. If I let ScriptA use ScriptB in the above mentioned way the output looks like this:

bash ScriptA.sh
b.sh: line 9: +: syntax error: operand expected (error token is "+")
Enter x and y 77 Enter x and y

It seems to be the case that after ScriptA inputs 44 and 33 and hits enter, like it should, but it hits enter right away a second time triggering the syntax error message and ending ScriptB. This is suboptimal, because in the case of the real ScriptB it will enter a "(standard_in) 1: parse error"-chain, resulting in no result at all. The solution to this problem would be by teaching ScriptA to read what ScriptB promts as result and ending it right after this. Or making it enter "q" as a second input instead of just hitting enter.

Edit 2:

Ok. Got it. Script A should look like this in order to work as desired:

e=2.7182818285
pi=3.141
a=$(printf "$e $pi \n q \n" | bash ScriptB.sh)
a=${a:14:20}
echo $a

2 Comments

@CharlesDuffy Sorry, but I couldn't find or understand the answers in the 2 links you suggested

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.