8

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,738
  • 21
  • 105
  • 131
sorin
  • 161,544
  • 178
  • 535
  • 806
  • 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

11

Use cut:

echo $VAR | cut --delimiter " " --fields 1  # Number after fields is the 
                                            # index of pattern you are retrieving
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Juto
  • 1,246
  • 1
  • 13
  • 24
7

Try this format:

echo "${VAR%% *}"

Another way is:

read FIRST __ <<< "$VAR"
echo "$FIRST"
konsolebox
  • 72,135
  • 12
  • 99
  • 105
7

If you want arrays, use arrays. ;)

VAR=(aaa bbb ccc)
echo ${VAR[0]} # -> aaa
echo ${VAR[1]} # -> bbb
michas
  • 25,361
  • 15
  • 76
  • 121
6

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

NewVAR=($VAR)
echo $NewVAR
IanM_Matrix1
  • 1,564
  • 10
  • 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
2

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,738
  • 21
  • 105
  • 131
sorin
  • 161,544
  • 178
  • 535
  • 806