Count arguments

2020-03-30 07:52发布

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?

标签: shell unix awk
2条回答
男人必须洒脱
2楼-- · 2020-03-30 08:28

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
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-03-30 08:37

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
查看更多
登录 后发表回答