这是我正在编写的 bash 脚本。您可以看到预期的输出。但我得到了其他的东西。我可能在哪里犯了错误?
#!/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
预期输出
./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
实际产量
[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 ~]#
答案1
第二种情况是,您没有提供所有变量值。您的脚本没有任何问题。
# bash -x cars.sh
# What cars do you like?
# Jaguar Maserati Bentley Lotus
如果仍然遇到问题,请尝试使用 -x 进行调试。
答案2
read -a variable_name
如果您有可变数量的输入参数,则可以像本例中那样使用数组变量。
例如: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
输出:
$ ./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