0

It is my understanding that when writing a Unix shell program you can iterate through a string like a list with a for loop. Does this mean you can access elements of the string by their index as well?

For example:

foo="fruit vegetable bread"

How could I access the first word of this sentence? I've tried using brackets like the C-based languages to no avail, and solutions I've read online require regular expressions, which I would like to avoid for now.

Orca Ninja
  • 823
  • 1
  • 15
  • 29

2 Answers2

2

Pass $foo as argument to a function. Than you can use $1, $2 and so on to access the corresponding word in the function.

function try {
 echo $1
}

a="one two three"

try $a

EDIT: another better version is:

a="one two three"
b=( $a )
echo ${b[0]}

EDIT(2): have a look at this thread.

Community
  • 1
  • 1
Ivaylo Strandjev
  • 69,226
  • 18
  • 123
  • 176
0

Using arrays is the best solution.

Here's a tricky way using indirect variables

get() { local idx=${!#}; echo "${!idx}"; }

foo="one two three"

get $foo 1  # one
get $foo 2  # two
get $foo 3  # three

Notes:

  • $# is the number of parameters given to the function (4 in all these cases)
  • ${!#} is the value of the last parameter
  • ${!idx} is the value of the idx'th parameter
  • You must not quote $foo so the shell can split the string into words.

With a bit of error checking:

get() {
  local idx=${!#}
  if (( $idx < 1 || $idx >= $# )); then
    echo "index out of bounds" >&2
    return 1
  fi
  echo "${!idx}"
}

Please don't actually use this function. Use an array.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352