0

I have a simple task to do from within a shell script - redirect command output to a variable as well as stdout. I already went through redirect command output into variable and standard output in ksh, and came up with:

VAR1=$(ps -u "${USER}" | awk 'NR>1 {print $NF}' | tee > /proc/$$/fd/1)

However the above doesn't work for me. The output displays on STDOUT fine, but its not saved in VAR1. What am I missing here ?

agc
  • 7,973
  • 2
  • 29
  • 50
dig_123
  • 2,240
  • 6
  • 35
  • 59

2 Answers2

3

You have an unnecessary redirect on that tee command. Use:

VAR1=$(ps -u "${USER}" | awk 'NR>1 {print $NF}' | tee /proc/$$/fd/1)

They tee works is that it copies its input to its output, and also to any files whose names you give as arguments. The redirection just messages up with its pass-through behavior.

Something else you could do - since we're not talking about some long-running command here - is first set the variable, then print its value:

VAR1=$(ps -u "${USER}" | awk 'NR>1 {print $NF}' )
echo "$VAR1"

... much simpler :-)

einpoklum
  • 118,144
  • 57
  • 340
  • 684
1

Redirecting command output to variable as well as console in bash:

You can use this trick:

var1=$(ps -u "${USER}" | awk 'NR>1 {print $NF}' | tee /dev/tty)

or

var1=$(ps -u "${USER}" | awk 'NR>1 {print $NF}' | tee /dev/stderr)

tee command will write output to /dev/tty which is your current terminal.

Also suggest you to avoid using all caps variable names to avoid chance of overriding an env var.

PS: Both commands work for me on OSX and Ubuntu.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Have you checked if the output is working. MY original problem still remains. var1 is not saving the output – dig_123 Jun 03 '19 at 11:29
  • Sending output directly to `/dev/tty` makes it impossible to pipe or redirect stdout. – John Kugelman Jun 03 '19 at 11:32
  • @anubhava No it doesn't work for me. I'm on KSH. The output just shows on `STDOUT`, but is not saved in `VAR1` variable – dig_123 Jun 03 '19 at 11:41
  • @anubhava Even for bash, it doesn't work for me. When I say KSH I mean, only when I run the above line from my shell (default shell). – dig_123 Jun 03 '19 at 11:43
  • @anubhava But even from within bash script doesn't work – dig_123 Jun 03 '19 at 11:44
  • `Kernel 2.6.32-754.14.2.e16`, `OS: RHEL-6.10` – dig_123 Jun 03 '19 at 11:50
  • @anubhava `$ var1=$(ps -u smnd | awk 'NR>1 {print $NF}' | tee > /dev/stderr);echo $var1 ksh ps awk tee $ var1=$(ps -u smnd | awk 'NR>1 {print $NF}' | tee > /dev/tty);echo $var1 ksh ps awk tee $` As you can clearly see, there is nothing saved in the variable – dig_123 Jun 03 '19 at 12:07
  • Why do you have `>` after `tee` in your command, I suggested `tee /dev/tty` or `tee /dev/stderr` without `>` after `tee`. Just run this in `bash`: **`var1=$(ps -u smnd | awk''NR>1 {print $NF}' | tee /dev/stderr); declare -p var1`** – anubhava Jun 03 '19 at 13:50