0

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
3
  • $[…] is deprecated; use $((…)) (part of the POSIX standard) instead. Example fib=$(($a+$b)). Commented Oct 28, 2013 at 15:45
  • @chepner you don't even need the $ inside: $((a+b)). Commented Oct 28, 2013 at 16:00
  • True; I was just trying to move the code off the deprecated syntax first; using it to its full capabilities can come later. Commented Oct 28, 2013 at 16:21

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

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.