Here is a LIST:

List = "abcd 1234 jvm something"

How to get the second element "1234" without looping all the list?

2 Answers 2


no spaces between equal sign

$ List="abcd 1234 jvm something"
$ set -- $List
$ echo $2

Some other ways, although not as efficient as using shell's internals

$ echo $List | cut -d" " -f2
$  echo $List | awk '{print $2}'
$ echo $List | sed 's/^.[^ \t]* //;s/ .*//'
$ echo $List | tr " " "\n"|sed -n '2p'
  • 1
    Thanks.would you give some comments in the code please?
    – SpawnST
    Mar 19, 2010 at 3:32
  • 2
    I mean the second line.
    – SpawnST
    Mar 19, 2010 at 3:32
  • 18
    @Spawn set -- $something splits $something at the $IFS character (by default space) and assigns the split parts to the positional variables $1,$2,... Mar 19, 2010 at 3:44
  • As @BenjaminBannier says in his answer: using set this way may pollute the environment. I.e. by overwriting positional parameters. To suggest it as an answer without explaining what it does is irresponsible.
    – markling
    May 24 at 10:34

Just to supplement ghostdog's answer: you could also put $List's elements into an array and access the specific list element from there

List="abcd 1234 jvm something"
echo ${arr[1]}

Note that the array indices are counted 0,1,2,... .

This has the advantage of not polluting the shell environment with too many new variables.

  • @BenjaminBannier, how can you select multiple elements. Is there some syntax like ${arr[1,2,3]}$ (not this, since I tried, but like this) or do I need to use a for loop.
    – Kvothe
    Apr 4, 2019 at 12:51
  • @Kvothe, you can take a slice from the list and loop over them. E.g. for v in "${arr[@]:1}"; do echo "$v"; done ... (i) takes all array elements "${arr[@]}", (ii) gets a slice of them, consisting of 2nd through last elements "${arr[@]:1}", and (iii) loops each into $v.
    – markling
    May 24 at 10:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .