Programmatically open tab in gnome-terminal, execute command, and have tab stay open

Solution 1:

Gnome-terminal can either execute a command or open a shell, but not both.

There is a workaround to do both by encapsulating the command and subsequent invocation of the shell into one command.

$ gnome-terminal -e "bash -c \"echo foo; echo bar; exec bash\""

For more alternatives read my answer to a similar question on stack overflow: https://stackoverflow.com/questions/3512055/avoid-gnome-terminal-close-after-script-execution/3531426#3531426

Solution 2:

If you have xdotool and wmctrl installed, then the following shell script might work:

#!/usr/bin/env bash

window="$(xdotool search --class gnome-terminal | head -1)"
xdotool windowfocus $window
xdotool key ctrl+shift+t
xdotool type "$*"
xdotool key Return

I use it like this:

$ run-in-new-tab 'ls -l'

I found this idea on Trustin Lee's blog.