0

This is my script , even after using the export command not able to use variable outside of the block. Below is the code that i have tried. I also tried other option like declare -x var, but that is also not working.

Can someone please please comment on this , am i doing right ?

 #!/bin/bash
 {
      var="123"

      export var   # exporting the variable so that i can access from anywhere

      echo "var is "$var     # able to get the value of this variable

 } | tee log.txt

 echo "var is "$var   # not able to get the value of this variable
jww
  • 97,681
  • 90
  • 411
  • 885
  • 1
    This is addressed in https://stackoverflow.com/questions/30727590/grouping-commands-in-curly-braces-and-piping-does-not-preserve-variable – Korthrun Jul 02 '17 at 07:43
  • still solution is not clear for me , so what the changes i have to done in code to access that variable . and thanks for ur reply and for ur valuable time . – brajkishore dubey Jul 02 '17 at 08:47
  • wrt `exporting the variable so that i can access from anywhere` - that's not what exporting a variable means, it means you can access it from the current shell and sub-shells, not "anywhere". You're exporting `var` in a subshell and then trying to access it in the higher level shell that the subshell was spawned from. The right solution depends on what you're really trying to do and your subject suggests you're trying to write a function (`...outside the function...`) - are you? [edit] your question to include a [mcve] of what you're really trying to do. – Ed Morton Jul 02 '17 at 12:21

1 Answers1

0

Because the pipe is causing the code between the braces to execute in a sub-shell you need to find a way to capture that data as opposed to storing it in a variable that is not accessible from the rest of the code. An example would be to store the output of a function in a variable, or to access it via command substitution. If you have script.sh as such:

#!/bin/bash

function get_pizza() {
    echo "Pizza"
}

myvar=$(get_pizza)
printf "myvar is '%s'\n" $myvar

echo "Plain echo follows:"
echo $(get_pizza)

and then run bash script.sh you will get output as such:

[user@host]$ bash ./script.sh
myvar is 'Pizza'
Plain echo follows:
Pizza

Then if you still want to write to a file via tee, you can pipe your whole script to tee: bash ./script.sh | tee foo.log If you only want parts of the script to goto a file, you'll can also handle that with I/O redirection within the script: echo pizza > foo.log

Korthrun
  • 141
  • 5