-1

When I execute a specific command I obtain as output 2 values, like this:

2.056000 640.640015

I want to extract only the second value, and assign it to a variable, to use later.

Can anyone help me?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Paula
  • 21
  • 1
  • 4

2 Answers2

1

If you want a variable to contain the result of a command, var=$(command) is the solution.

In your case,

your_var=$(your_command | awk '{print $2}')

You have to perform the command and then pipe it to awk, that will get the second parameter.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
-1

Fedorqui's approach is good, but for the sake of providing an alternative:

your_command | read DONT_CARE YOUR_VAR IGNORE_ANYTHING_TRAILING

This has the benefit of not needing to run up a subshell and awk. Tested and working for zsh. You don't have to bother with the IGNORE_ANYTHING_TRAILING, but then say your_command spat out 1 2 3 4, YOUR_VAR would end up with "2 3 4".

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
  • Good idea. Have to say that a basic `$ ls -l a | read p` did not work to me in bash. `$p` is not set. – fedorqui May 01 '13 at 10:11
  • Yeah... my old bash shell in cygwin is weird too: `echo 1 | read x` doesn't set x, `read -u 0 x` (descriptor for stdin) doesn't help, `cat | read x` doesn't work, but if I do just `read x` and type values it work's fine. Pipe's screwing it somehow. Some discussion at http://stackoverflow.com/questions/2746553/bash-script-read-values-from-stdin-pipe - what a stupid shell! ;-P – Tony Delroy May 01 '13 at 10:15
  • Some shells (notably `bash`) will execute the `read` in a subshell, and so the variable is not available after the pipeline exits. The POSIX standard simply says that any or all commands in a pipeline may execute in a subshell; it does not require any specific behavior. – chepner May 01 '13 at 12:34