I am trying to write a function in bash that takes a space delimited string and outputs the 1st word in that string. I tried
function myFunc { a=$1; b=($a); echo ${b[0]};}
but with
myStr="hello world"
myFunc myStr
I get no output.
if I replace a=$1 in the function definition above with a="hello world", then I get the expected result on applying
myFunc
result: hello
Also if instead of passing myStr as an argument I pass in "hello world" directly, it also works:
myFunc "hello world"
result: hello
I tried all kinds of indirections with the exclamation points, as well as the expr constructions but to no avail. Finally the following seems to work:
function el_index { alias a=$1; b=($a); echo ${b[2]};}
I would like to gather here all other possible ways to accomplish the same thing as above. In particular, is there a way to bypass the intermediate variable a completely, and do something like b=(${$a}) in the second statement within the function body above? By the way, the construction
b=($a)
splits the string stored in a into words using the default delimiter, which is a single white space.
Thanks!