0

I have a script at the moment that reads in variables and then operates on them like the following;

#!bin/bash
a=10
b=15
c=20

d=a*b+c
echo $d

However I would like to split this up into an input file containing:

a=10
b=15
c=20

and a script which does the operation

#!/bin/bash
d=a*b+c
echo $d

And will be called up something like this.

./script.sh < input.in

Now I have done a bit of digging and I have tried doing a simple.

./script.sh < input.in

such that it returns the answer 170

but this doesn't work. After further digging, it seems that in the script in need to use the command "source" But I am unsure how to do it in this case.

Can it be done? What is the best way to do this?

2 Answers 2

3

From help source:

source: source filename [arguments]
    Execute commands from a file in the current shell.

    Read and execute commands from FILENAME in the current shell.  The
    entries in $PATH are used to find the directory containing FILENAME.
    If any ARGUMENTS are supplied, they become the positional parameters
    when FILENAME is executed.

    Exit Status:
    Returns the status of the last command executed in FILENAME; fails if
    FILENAME cannot be read.

So, in the script, you only need to add this line:

source input.in

or this one (the POSIX version):

. input.in

To pass the input file at runtime, you use positional parameters:

source "$1"
. "$1"

Also note that d=a*b+c won't work unless d has the "integer" attribute:

declare -i d
d=a*b+c

or you use arithmetic expansion to perform the operation:

d=$((a*b+c))

Example:

#!/bin/bash
source "$1"
d=$((a*b+c))
echo "$d"
$ ./script.sh input.in
170
1
  • 1
    Another idea would be to read the values of the variables in the script, and then to pass (on standard input) a file containing only those values. Commented Dec 5, 2018 at 17:56
0

This is a very basic operation. Just source or . a file name, and the result is as if those lines were included in your primary script.

The syntax is simply this:

source file_name

or

. file_name

There are some nuances, but that's more advanced. See man bash | grep source for more details.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.