Reputation: 65
I wanted to run a maven command and store the console output to a variable and in turn, store the real
time of the mentioned operation in another variable. I wrote the following command -
x1=`( time t1=$( mvn test -Drat.skip)) 2>&1 | grep real`
When I echo
variable x1
I get 0m17.430s
which is the desired output but when I echo
variable t1
it prints nothing! How can I store the console output of mvn test -Drat.skip
in t1
?
Upvotes: 1
Views: 147
Reputation: 7253
As @choroba said t1
is created in different subshell and can't be exported back.
You cat test it like this:
t1=test
x1=`(time t1=$(echo ok); echo $t1) 2>&1`
echo $t1
echo $x1
The output will be:
$ echo $t1
test
$ echo $x1
real 0m0,001s user 0m0,001s sys 0m0,001s ok
But this litle hack may help
fun () { t1=$(mvn test -Drat.skip); }
x1=$((time fun) 2>&1 | grep real)
Upvotes: 1
Reputation: 241758
Everything inside of ()
or backticks happens in a subshell. Variable values aren't exported from a subshell back to the parent shell.
You can assign both the output of the command and output of time
into a variable and then extract it from there:
#!/bin/bash
all=$((time mvn test -Drat.skip )2>&1)
time=$(tail -n3 <<< "$all" | grep real)
output=$(head -n-3 <<< "$all")
Upvotes: 3