Reputation: 71
I am accepting user input and want the script to work for below cases. I have tried using '==' and '=~'. However my script works well for the second case when I use '==' but first one fails. When I use the '=~' instead the script accepts arguments like ./script john harryyy smith.. which I don't want it to accept. Any best way to get both cases working?
./script john harry smith
./script john
if [[ "${args[@]}" == "john" ]]; then
....
else
....
Upvotes: 0
Views: 80
Reputation: 71
I think i would use case statement something like this .. this is not exact code. This seems to work as i am particularly looking for a string like 'john'
case ${args[i]} in 'harry'|'smith'|.....) ..... ...... ;;
'john')
.....
.......
;;
*)
Upvotes: 0
Reputation: 124
You could use grep
, and then wc
to count the grep matches.
if [[ "$(echo ${args[@]} | grep "john" | wc -l) -ge 0 ]]; then ...; else...; fi
For user input, I'd recommend using grep -i
, to make the grep search case insensitive.
Edit:
Didn't fully read the whole question, so my bad there. The above will still match harry to harryyy. For matching multiple arguments to multiple variables, I would probably use for loops.
for ((i=0;i<${#args[@]};i++)); do
if [ ${args[$i]} = "john" ]; then
...
break #optional, prevents the code from executing twice if the user has typed two "john"s.
fi
done
Of couse, you'd have to have a loop for each name you wanted to check. If you put the names into an array as well, you could double-loop instead;
#array names contains the names to check against.
for ((i=0;i<${#names[@]};i++)); do
for ((ii=0;ii<${#args[@]};ii++)); do
if [ ${args[$ii]} = ${names[$i]} ]; then
...
continue 2 #again, optional, continues the first loop for the same reason as above
fi
done
done
Upvotes: 1