0

I am trying to store output of command to variable in below bash script but the output is displayed on screen instead of storing in the variable

#!/bin/bash

check=$(ip link show dev mylink)

echo "$check"
MrDev
  • 11
  • 2
  • What is "bva" and why do you expect `echo` to do something else than display its arguments as text on standard output? – tripleee Mar 14 '16 at 05:39
  • @tripleee this is not entire script i am using this script to do some work if link doesn't exists. I need the output to variable to perform the check. – MrDev Mar 14 '16 at 05:52
  • @MrDev: If that is all, then you may want to simply check whether `/sys/class/net/mylink` exists, instead. – Dolda2000 Mar 14 '16 at 05:53
  • @triplee I tried everything & searched a lot but variable is empty. – MrDev Mar 14 '16 at 05:56
  • 1
    You mean `ip link` displays to the screen and `echo "$check"` displays nothing? I think you are probably mistaken, but if you can add a transcript with `bash -x` to the question to demonstrate this, I'll be happy to remove the duplicate. – tripleee Mar 14 '16 at 06:03
  • Note that it would be sensible to use something like `echo "[$check]"` so that you can spot the difference between echoing the value captured in `$check` (because of the square brackets) and the raw output of the `ip` command. If the output of the command is appearing despite the command substitution, it is most likely writing to stderr. You could demonstrate by using `check=$(ip link show dev mylink 2>&1); echo "[$check]"` which would then show nothing except the material in square brackets. – Jonathan Leffler Mar 14 '16 at 06:31
  • 2
    @JonathanLeffler Yes, you are right its writing to stderr using 2>&1 worked. Thanks a lot :) – MrDev Mar 14 '16 at 06:35
  • That's pretty nasty behaviour by the `ip` program. Requested output should go to standard output; only error messages should go to standard error (but they should go to standard error and not standard output). – Jonathan Leffler Mar 14 '16 at 06:37
  • http://stackoverflow.com/questions/962255/how-to-store-standard-error-in-a-variable-in-a-bash-script looks like a good canonical. – tripleee Mar 14 '16 at 06:56
  • The best duplicate I can find is surprisingly recent — but very directly the same problem. The one you reference is also interesting, and a lot older. I've selected the recent one - but SO 962255 [How to store standard error in a variable in a `bash` script](https://stackoverflow.com/questions/962255/how-to-store-standard-error-in-a-variable-in-a-bash-script) is also good. (Full disclosure: I have the accepted answer on the older one, though there's another answer with a few more up-votes.) – Jonathan Leffler Mar 14 '16 at 07:28

0 Answers0