Shell – Store specific output to a shell variable

command-substitutionshelltext processingvariable

I am looking to store the output of the svn info command, more precisely the revision number into a variable for further processing. I just need the 4 stored.

$ svn info
[...]
Revision: 4
[...]

Best Answer

Using awk

awk works well for this:

rev=$(svn info | awk '/Revision:/{print $2}')

The code above uses command substitution, $(...), to capture the output of a command and assign it to a variable.

In the code above, awk reads the output of svn info and waits for a line that contains the string Revision:. When that line is found, it prints the second field on that line, which is be the revision number.

Using sed

It is also possible to do this using sed:

rev=$(svn info | sed -n '/Revision:/ s/.* //p')

With the -n option, sed will only print when we explicitly ask it to. /Revision:/ selects lines that contain the string Revision:. For those lines, a substitution command is performed that removes all characters up to the last blank on the line and then, due to the p option, the line is printed.

Using shell

while read -r name value
do 
    [ "$name" = Revision: ] && var="$value"
done < <(svn info)

The above uses redirection from process substition, < <(...), to supply the output of svn info to a while loop. For each iteration of the loop, the first word on the line is assigned to name and the rest of the line is assigned to value. If name is Revision:, then the shell variable var is assigned to value, which is the revision number.

Many, but not all, shells support process substitution. When, as above, redirection is combined with process substitution, the space between the two < is essential.

Related Question