-   Linux - Newbie (
-   -   Best way to do ${variable:-3:1} ? (

anonguy9 03-26-2009 09:45 PM

Best way to do ${variable:-3:1} ?
(in pure bash)

Expecting Ruby-like syntax is asking too much, I know.. but I'm trying to do this equivalent:


if [ ${duration:-3:1} = "." ]; then
  echo hey!

This fails because "-3" is not valid.

I don't know how to be sneaky and get the exit code of a substitution. This can't work since the setting of duration is a success and returns 0.


if [ ! $? = 0 ]; then
  echo hey!

My solution:

I could research iterating through the string in some other way, but converting it into an array seems sensible to me.

Props to this post for the hint.


array=( )
for i in $(seq 0 $((${#string} - 1))); do
  array=( "${array[@]}" "${string:$i:1}" )

# Now, since this is impossible:
# ${duration[-3]}

# Count the number of elements.

# Third from the last would be:
my_element_number=$(( $element_count - 3 ))

# And that element in the array would be:
echo ${array[my_element_number]}

So.. My questions are..

- Is my solution sensible?

- Is there a better way to do this (in pure bash) ?
-- Regular expressions are possible, and I think that working with them on my variable would be best. But I couldn't wrap my brain around that. I'm positive this could all be wrapped into a oneliner. There are some great examples in tldp but none seem quite like what I want (third from the right).

- Has anyone already built a nicer function to work with strings as though they were arrays?

Kenhelm 03-27-2009 06:44 AM

A negative position parameter needs to be escaped with parentheses or a space.
The escaping avoids it being mistaken for this other type of substitution
${var:-value} Use 'var' if set; otherwise, use 'value'.

echo ${string:(-3):1}
echo ${string: -3:1}

anonguy9 03-27-2009 11:03 AM

Haha! So simple!

Well, I guess I learned more about arrays and iteration with my other solution. Hehe.

Thanks for the help.

All times are GMT -5. The time now is 07:34 AM.