7

I do have a Bash list (space separated string) and I just want to extract the first string from it.

Example:

 VAR="aaa bbb ccc" -> I need "aaa"
 VAR="xxx" -> I need "xxx"

Is there another trick than using a for with break?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
sorin
  • 149,293
  • 163
  • 498
  • 754
  • Possible canonical question (3 years prior, 13 answers, and 135 upvotes) : *[How can I retrieve the first word of the output of a command in Bash?](https://stackoverflow.com/questions/2440414)* – Peter Mortensen Apr 25 '21 at 19:22

5 Answers5

8

Use cut:

echo $VAR | cut --delimiter " " --fields 1  # Number after fields is the 
                                            # index of pattern you are retrieving
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Juto
  • 1,156
  • 1
  • 12
  • 23
7

Try this format:

echo "${VAR%% *}"

Another way is:

read FIRST __ <<< "$VAR"
echo "$FIRST"
konsolebox
  • 66,700
  • 11
  • 93
  • 101
6

If you want arrays, use arrays. ;)

VAR=(aaa bbb ccc)
echo ${VAR[0]} # -> aaa
echo ${VAR[1]} # -> bbb
michas
  • 24,015
  • 14
  • 69
  • 112
5

I'm not sure how standard this is, but this works in Bash 4.1.11

NewVAR=($VAR)
echo $NewVAR
IanM_Matrix1
  • 1,509
  • 9
  • 8
  • It does indeed work. And it is much simpler (and faster, especially compared to invoking external processes like [cut](https://en.wikipedia.org/wiki/Cut_(Unix)), [AWK](https://en.wikipedia.org/wiki/AWK), or [Perl](https://en.wikipedia.org/wiki/Perl)). – Peter Mortensen Apr 25 '21 at 17:21
  • But it will fail if the first "word" is "*" (an [asterisk](https://en.wiktionary.org/wiki/asterisk#Noun)) - it expands to the list of all files and all directories in the current directory... – Peter Mortensen Apr 25 '21 at 19:27
1

At this moment the only solution that worked, on both Linux and OS X was:

 IP="1 2 3"
 for IP in $IP:
 do
   break
 done
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
sorin
  • 149,293
  • 163
  • 498
  • 754