1

I want a command that opens a terminal and executes a function that is defined in my aliases.zsh. The function is defined like so:

my-function() {
  wget some stuff
  do some other stuff
}

I tried gnome-terminal -- my-function, but the new terminal reports that it Failed to execute child process “my-function” (No such file or directory). Something similar happens if I do gnome-terminal -- /bin/zsh -c 'my-function; sleep 1; exec zsh': in the new terminal, zsh reports zsh:1: command not found: my-function.

Any help greatly appreciated.

1 Answer 1

1

~/.zshrc is the customisation file for interactive invocations of zsh.

zsh -c 'some code' is an inline script. Like for scripts starting with a #! /bin/zsh - shebang, thankfully, the ~/.zshrc is not sourced on startup. If it were, and you had aliases / functions that change the behaviour of standard commands (it's not uncommon to have alias 'ls=ls --color -F' 'grep=grep --color;...), that could break zsh scripts.

If you want a script to load ~/.zshrc or ~/.zprofile or /etc/zsh/zshrc, you need to request it explicitly. But best would be to put those functions in some ~/.zsh/some-library.zsh and source that instead in the scripts that need it as well as your ~/.zshrc, or use the autoload framework.

gnome-terminal -- zsh -c '. ~/.zsh/some-library.zsh; myfunction'

If you wanted an interactive zsh to be started in gnome-terminal but that first runs your function before issuing the first prompt, you could add a:

eval -- $ZSH_INIT_COMMAND
unset ZSH_INIT_COMMAND

To the end of your ~/.zshrc, and run gnome-terminal as:

gnome-terminal -- env ZSH_INIT_COMMAND='myfunction; echo and whatever else' zsh

Or if you wanted to start it as if it had been written at the prompt, so you could handle it the same way, change it to:

if (( $+ZLE_INIT )); then
  seed-zle() {
    BUFFER=$ZLE_INIT
    unset ZLE_INIT
    zle -D zle-line-init
    unset -f seed-zle
    zle accept-line
  }
  zle -N zle-line-init seed-zle
fi

And start gnome-terminal as:

gnome-terminal -- env ZLE_INIT='myfunction; echo and whatever else' zsh

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .