João Fernandes
João Fernandes

Reputation: 558

Linux bash script: share variable among terminal windows

If I do this:

#!/bin/bash

gnome-terminal --window-with-profile=KGDB -x bash -c 'VAR1=$(tty); 
echo $VAR1; bash'
echo $VAR1

How can I get the last line from this script to work? I.e., be able to access the value of $VAR1 (stored on the new terminal window) from the original one? Currently, while the first echo is working, the last one only outputs an empty line.

Upvotes: 1

Views: 1308

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 81012

The short version is that you can't share the variable. There's no shared channel for that.

You can write it to a file/pipe/etc. and then read from it though.

Something like the following should do what you want:

#!/bin/bash

if _file=$(mktemp -q); then
    gnome-terminal --window-with-profile=KGDB -x bash -c 'VAR1=$(tty); echo "$VAR1"; declare -p VAR1 > '\'"$_file"\''; bash'
    cat "$_file"
    . "$_file"
    echo "$VAR1"
fi

Upvotes: 3

Related Questions