Search code examples
linuxbashshellgnome-terminal

Running a bash function in gnome-terminal -x


I have a bash function and I want to execute that function in a new window using gnome terminal. How do I do it? I want to do something like this in my blah.sh script:

    my_func() {
        // Do cool stuff
    }

    gnome-terminal -x my_func

What I am doing right now is putting my_func() into a script and calling gnome-terminal -x ./my_func


Solution

  • You can get it to work with export -f, as @kojiro's points out in a comment above.

    # Define function.
    my_func() {
        // Do cool stuff
    }
    
    # Export it, so that all child `bash` processes see it.
    export -f my_func
    
    # Invoke gnome-terminal with `bash -c` and the function name, *plus*
    # another bash instance to keep the window open.
    # NOTE: This is required, because `-c` invariably exits after 
    #       running the specified command.
    #       CAVEAT: The bash instance that stays open will be a *child* process of the
    #       one that executed the function - and will thus not have access to any 
    #       non-exported definitions from it.
    gnome-terminal -x bash -c 'my_func; bash'
    

    I borrowed the technique from https://stackoverflow.com/a/18756584/45375


    With some trickery, you can make do without export -f, assuming that the bash instance that stays open after running the function doesn't itself need to inherit my_func.

    declare -f returns the definition (source code) of my_func and so simply redefines it in the new bash instance:

    gnome-terminal -x bash -c "$(declare -f my_func); my_func; bash"
    

    Then again, you could even squeeze the export -f command in there, if you wanted:

    gnome-terminal -x bash -c "$(declare -f my_func); 
      export -f my_func; my_func; bash"