Search code examples
linuxbashfunctionxterm

How to open xterm -e 'command', preserving already declared functions?


I would like to run the following command:

$ testfunction (){ echo 123;}
$ xterm -hold -e "testfunction"

returns: testfunction command not found (in the new xterm window).

but when I call the function in main terminal, it returns 123

$ testfunction
123

Tried

In declare -F | grep testfunction I can see that the function is declared.

Tried to declare just a variable:

$ variable='123'
$ xterm -hold -e "echo $variable"

returns: 123 (in new xterm).

Why new oppened xterm doesn't found declared functions, but found declared variables?


Solution

  • You need to export functions/variables to let child processes access them.

    testfunction() { echo 123; }
    export -f testfunction
    xterm -hold -e "testfunction"
    

    result

    And, xterm -hold -e "echo $variable" doesn't work actually, it just looks like so. $variable is in double quotes and thus expanded before calling xterm, i.e its value is passed to xterm, xterm -hold -e 'echo $variable' wouldn't work since variable is not exported.