6

I need to run a program in the background. I know that using '&' after a command runs the command in the background.

In the following script:

#!/bin/bash
echo amt of time delay nsec
read nano
echo amt of time delay in sec
read sec
echo no.of times
read i
while [ $i -ne 0 ]
do
./nanosleep $sec $nano
./schello
i=$[i-1]
done

I have a few data that I get from the user. Is there a way I can run the program in background and while calling the program can I also specify the data required (like nano, sec,i) as arguments or through some other way?

2 Answers 2

9

If your script is called, let say test.sh, then you can for example:

  • pipe your input:

    echo -e "1\n2\n3\n" | test.sh &
    

    where 1, 2, and 3 are the values for $nano, $sec and, respectively $i.

  • take the input from a file:

    test.sh < arguments.txt &
    
  • use a here string:

    test.sh <<< $'1\n2\n3\n' &
    
1
  • The 1st one was more than enough though had to use ./test.sh
    – Bas
    Mar 27, 2014 at 3:51
1

Another possibility is to pass those variables as arguments to your script. In your script, instead of

read nano
read sec
read i

...you may use:

nano=$1
sec=$2
i=$3

The variables $1, $2, $3, etc. correspond to the first, second, third, etc. arguments on the command line. Thus you can call your script as:

test.sh foo bar buz &

Inside the script, $1 will contain foo, $2 will contain bar, $3 will contain buz, etc.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .