dk1
dk1

Reputation: 97

Reading user-input in the same line as the script execution

I have a BASH script named fib.sh. The script reads a user input (number) and performs a calculation. I want to be able to type

$ ./fib.sh 8

where 8 is the input

Currently, I have to wait for the next line to enter the input.

$ ./fib.sh 
$ 8

Script

#!/bin/bash

read n

a=0
b=1
count=1
fib=$a

while [ $count -lt $n ]; 
do
    fib=$[$a+$b]
    a=$b
    b=$fib
    count=$[$count+1]
done

echo "fib $n = $fib"

exit 0

Upvotes: 0

Views: 1551

Answers (1)

fedorqui
fedorqui

Reputation: 290415

So you want to pass a parameter to the script instead of reading it. In this case, use $1 as shown here:

#!/bin/bash

n=$1 <---- this will take from the call of the script
echo "I have been given the parameter $n"

a=0
b=1
count=1
fib=$a

while [ $count -lt $n ]; 
do
    fib=$[$a+$b]
    a=$b
    b=$fib
    count=$[$count+1]
done

echo "fib $n = $fib"

exit 0

Upvotes: 2

Related Questions