I write this commands:
#!/bin/bash
echo "Enter values a and b (separate with space)"
read a b
echo $#
And I want to count how many arguments the user has entered. I try to count with $#
, but the output is 0
.
What's the problem? What I am doing wrong?
You may use an array to read complete line and count # of words:
read -p "Enter values (separate with space): " -ra arr
Enter values (separate with space): abc foo bar baz 123
Then print no of words:
echo "No of words: ${#arr[@]}"
No of words: 5
Here's how I'd probably do it, without thinking too much about it. It's hacky to use the dummy c
variable, but I find bash array's even more awkward.
read -r a b c
if [[ $c ]]
then
echo "To much arguments"
elif [[ $a && $b ]]
echo "Correct - 2 arguments"
else
echo "Not enough arguments"
fi