0

This is the bash script I am writing. You can see the expected output. But I am getting something else. Where could I be making a mistake?

#!/bin/bash
    #Demostrate how read actually works
    echo What cars do you like?

    read car1 car2 car3

    echo Your first car was: $car1
    echo Your second car was: $car2
    echo Your third car was: $car3

Expected output

./cars.sh
What cars do you like?
Jaguar Maserati Bentley Lotus
Your first car was: Jaguar
Your second car was: Maserati
Your third car was: Bentley Lotus

Actual Output

[root@localhost ~]# ./cars.sh
What cars do you like?
Jaguar
Your first car was: Jaguar
Your second car was:
Your third car was:
[root@localhost ~]#
  • This looks like what I'd expect from the defined behavior of the read command. If you input too many words, the extra collects in the last variable (thus car3 is "Bentley Lotus" in your first example). If you don't input enough words, it leaves the later variables empty (thus, car2 and car3 are blank in your second example). – Gordon Davisson Feb 27 '19 at 5:48
  • Btw for scripting questions the sister site Unix & Linux SE might be the better place. – Freddy Feb 27 '19 at 6:37
0

In second case you are not providing all the variable values. There is nothing wrong in your script.

# bash -x cars.sh
# What cars do you like?
# Jaguar Maserati Bentley Lotus

Try to debug with -x if you still face an issue.

  • Thanks for your answer. It is working now. I had failed to give all the inputs when the first line popped up. Its working now. [root@localhost ~]# ./cars.sh What cars do you like? Jaguar Ferrari Maseratti Suzuki Your first car was: Jaguar Your second car was: Ferrari Your third car was: Maseratti Suzuki – truthtriumphs Feb 27 '19 at 7:20
0

If you have a variable number of input arguments you could use an array variable by using read -a variable_name like in this example.

Example: cars.sh

#!/bin/bash

read -a cars -p "What cars do you like? "

echo "You have entered ${#cars[@]} cars"

declare -i count=0
for car in "${cars[@]}"; do
        echo "Car number $(( ++count )) was: $car"
done

Output:

$ ./cars.sh
What cars do you like? bmw audi mercedes
You have entered 3 cars
Car number 1 was: bmw
Car number 2 was: audi
Car number 3 was: mercedes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.