Alex Rivera | Logout

How to split one string into multiple strings separated by at least one space in bash shell?

Asked 2009-09-24T05:07:37.200
365

I have a string containing many words with at least one space between each two. How can I split the string into individual words so I can loop through them?

The string is passed as an argument. E.g. ${2} == "cat cat file". How can I loop through it?

Also, how can I check if a string contains spaces?

Edit
Report

1 Answer

6

For checking spaces just with bash:

[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
answered 2009-09-25T03:14:12.833

Your Answer