0

How can run a bash script and its inputs in one line instead of separate commands?

my code

#!/bin/bash
read input1 input2
...

In terminal:

bash file.sh input1 input2

instead of:

bash file.sh
input1 input2
Sam
  • 3
  • 2

2 Answers2

0

You can either echo the input and pipe to the script e.g.

cat 1.sh
read input1 input2

echo $input1
echo $input2

echo 'val1 val2' | bash 1.sh

or just refer to the positional arguments instead of using read:

cat 2.sh
echo $1
echo $2

bash 1.sh myval1 myval2
bob dylan
  • 1,458
  • 1
  • 14
  • 32
  • Duplicates should be flagged, not answered. See the "Answer Well-Asked Questions" section of https://stackoverflow.com/help/how-to-answer – Charles Duffy Feb 25 '20 at 12:57
  • Also, `echo $foo` is buggy. See [BashPitfalls #14](https://mywiki.wooledge.org/BashPitfalls#echo_.24foo). – Charles Duffy Feb 25 '20 at 13:02
0

Yes, don't use the read but use arguments. The shell (Bash) will read through all of the arguments of a command and apply the needed rules where needed. So, arguments can be any string i.e. "|", , or value "3" or .

BashSript arg1 arg2 ..

$0 is the name of the script $1 and $2 are the following arguments

So.

#!/bin/bash
echo "BashScript name: $0"
echo "Arg1: $1"
echo "Arg2: $2"
echo "All Arguments $@"

There is a lot of control you can apply to argument manipulation and input. Far more then a simple question can cover.

Richard E
  • 334
  • 1
  • 4
  • 14