invoke zsh, having it run a command, and then enter interactive mode instead of exiting

34

15

i'd like to start zsh similar to

zsh -c 'my_prog option1 option2'

but instead of exiting after running that command, leaving me at the propt of the invoked zsh (not wherever it is being called from). one particular use-case for this is in screenrc files, you could do something like:

screen -t my_prog 0 zsh -c 'my_prog opt1 opt2'

and after running that command you're left with a shell there instead of it closing.

Autoplectic

Posted 2010-01-05T22:48:49.203

Reputation: 938

Answers

26

Not that I would advise doing this.

(sirius)~: zsh -c 'print hello; zsh -i'
hello
(sirius)~: echo $SHLVL
2

There are other tricks you can play with screen and using the $STY variable.

If you want something run from zsh with individual screens, you can check the $STY variable within your .zshrc or .zlogin. It is in the format <PID>.<TTY>.<HOSTNAME>.

if [[ -n $STY ]] then
  if [[ -f ~/.zsh-$STY[(ws:.:)2] ]] then
    . ~/.zsh-$STY[(ws:.:)2]
  fi
fi

If in screen, and if ~/.zsh-<TTY> (from the $STY variable) exists, source that, then continue on your merry way. You can also set an environment variable before calling the interactive shell.

> FOO=bar zsh -i
> env | grep FOO
FOO=bar

> RUNTHISCOMMAND=/path/to/script zsh -i
.zshrc:
if [[ -n $RUNTHISCOMMAND ]] then
   $RUNTHISCOMMAND
fi

Add those checks into your .zshrc/.zlogin.

Darren Hall

Posted 2010-01-05T22:48:49.203

Reputation: 6 354

kudos for teaching me about SHLVL – Nicolas Dumazet – 2010-01-06T05:00:56.983

i was hoping to avoid the nested shell, but oh well. – Autoplectic – 2010-01-06T09:24:10.650

14

I found a solution that works without an extra shell here. Add:

if [[ $1 == eval ]]
then
    "$@"
set --
fi

to .zshrc, then call zsh with

zsh -is eval 'your shell command here'

Really great for starting up lots of shells at once.

gravitation

Posted 2010-01-05T22:48:49.203

Reputation: 257

6

What about appending ; exec zsh to the command? That way there's only one shell left at the end.

TRS-80

Posted 2010-01-05T22:48:49.203

Reputation: 2 923

5You actually don't need the exec if you ; zsh -i, it does that for you already. – Darren Hall – 2010-01-06T17:47:31.433

5

I have eval "$RUN" at the end of my .zshrc. I can now run commands without the extra shell, with:

RUN='my_prog opt1 opt2' zsh

Zaz

Posted 2010-01-05T22:48:49.203

Reputation: 1 843

This seems a weird kludge - but it works so well! – zaTricky – 2017-02-28T05:32:51.880