If you don't want to use the array for any reason, and you want to do it in bash, and not by creating an external tool like this sed, you can just count the lines:
[ghoti@pc ~]$ x=$'one\ntwo\nthree\nfour\nfive\n'
[ghoti@pc ~]$ n=3
[ghoti@pc ~]$ for (( c=0; c<n; c++ )); do read line; done <<< "$x"
[ghoti@pc ~]$ echo $line
three
[ghoti@pc ~]$
Or using one smaller variable:
[ghoti@pc ~]$ n=2
[ghoti@pc ~]$ for (( ; n>0; n-- )); do read line; done <<< "$x"
[ghoti@pc ~]$ echo $line
two
These methods use what are sometimes called "three expressions for a loop." This is a construct that is common in many languages, from bash to awk to perl from PHP to C (but not Python!). Familiarity with them will help your programming as a whole.
Although ... you probably don't want to use bash to learn "real" programming. :-)
source
share