Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the first string from a Bash list? [duplicate]

Tags:

bash

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?

like image 777
sorin Avatar asked Aug 28 '13 11:08

sorin


People also ask

How do I get the first letter of a string in bash?

To access the first character of a string, we can use the (substring) parameter expansion syntax ${str:position:length} in the Bash shell. position: The starting position of a string extraction.

What is $() called in bash?

It turns out, $() is called a command substitution. The command in between $() or backticks (“) is run and the output replaces $() . It can also be described as executing a command inside of another command.

What does \r do in bash?

The -r tests if the file exists and if you have read permission on the file. Bash scripting tutorial - if statement. The meaning of -r depends on what program/command it is given as an argument for. In this case it is for [ , and means to check whether the file named by the next argument is readable.


1 Answers

Use cut:

echo $VAR | cut --delimiter " " --fields 1  # Number after fields is the 
                                            # index of pattern you are retrieving
like image 51
Juto Avatar answered Oct 22 '22 20:10

Juto