Home > Software design >  How to launch a terminal with a function defined in the same script?
How to launch a terminal with a function defined in the same script?

Time:10-10

Have a look at the script below. I want to run the function fopen when urxvt is launched. The only way I can do it now is to move fopen into a separate file and then call urxvt -e sh -c "path_to_script". I don't want to have two separate files. I want to be able to launch urxvt with a function instead of a script name. How can I do that?

#!/usr/bin/env bash

# function that I want to run when terminal opens
fopen() {
    ls
}

# I want to be able to call `urxvt` with a function
# This doesn't work
urxvt -e fopen

# This works, but this requires me to move `fopen` to another file
urxvt -e sh -c "path_to_script"

CodePudding user response:

So the function has to get into another child process.

You can serialize the function using declare -f to the child process.

... bash -c "$(declare -f fopen); fopen"

You can export the function into the environment, which is shared with the child process.

expport -f fopen
... bash -c 'fopen'
  • Related