(in pure bash)
Expecting Ruby-like syntax is asking too much, I know.. but I'm trying to do this equivalent:
Code:
duration="6.27"
if [ ${duration:-3:1} = "." ]; then
echo hey!
fi
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.
Code:
duration=${duration#*.}
if [ ! $? = 0 ]; then
echo hey!
fi
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.
Code:
string="1234567"
array=( )
for i in $(seq 0 $((${#string} - 1))); do
array=( "${array[@]}" "${string:$i:1}" )
done
# Now, since this is impossible:
# ${duration[-3]}
# Count the number of elements.
element_count=${#array[*]}
# 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?