1

I have a shell script (main.sh) in which first few lines read some data through user's input.

    echo   "Enter the model  !!"
    read model
    echo "Enter the Weight !!"
    read wgt
    echo  "enter the data file  !!"
    read datafile
    echo  "Enter the two column names  !!"
    read coll1 coll2

these variables $model, $wgt, $datafile, $coll1, $coll2 are being used in the rest of the programs. When I run this by ./main.sh and give inputs respectively MODEL, WGT, DATA, COL1 COL2, everything is running fine. But I want to give these inputs through a file. So I created another script file which contains

    echo "COL1 COL2" | echo "DATA" | echo "WGT" | echo "MODEL" | ./main.sh

its only taking the first input i.e. MODEL. Is there any way to do this correctly?

3 Answers 3

3

Don't pipe echo to echo. echo doesn't read standard input and so you are losing everything but the last one. Also if that worked as written it would likely be backwards.

You want something more like this:

{
    echo "MODEL"
    echo "WGT"
    echo "DATA"
    echo "COL1 COL2"
} | ./main.sh

Which, of course, could also just be:

printf 'MODEL
WGT
DATA
COL1 COL2
' | ./main.sh
Sign up to request clarification or add additional context in comments.

8 Comments

Or printf "%s\n" MODEL WGT DATA 'COL1 COL2' on a single line of code.
@JonathanLeffler Indeed. I almost write printf 'X\nX\nX\nX\n' but figured that was excessive and slightly hard to read. But that version is much easier to read.
This is working. But if I want to give some number (say my WGT is actually 1.5) then what should I do?
Replace the values with whatever you want. The idea was the point not the content. If you need variables to expand there use double quotes instead of single quotes.
I tried to do echo "1.5" within the curly braces and its not taken.
|
1

Change your main.sh to recieve these various parameters as arguments rather than on the standard input and then invoke it like so

./main.sh $COL1 $COL2 $DATA ....

2 Comments

The recommendation to use arguments rather than prompting for input is good, but doesn't answer the question. I suggest answering the question too.
Fair enough. My feeling was that the approach he was using is not a common shell idiom and it's best avoided.
1

You can do it like this:

In main script:

coll1=$1
coll2=$2
datafile=$3
wgt=$4
model=$5

Then run your main script like this:

./main col1 col2 data wgt model

You have to maintain the sequence...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.