How to use xdotool to open a new tab, switch to it and run commands in it

4.7k views Asked by At

I am trying to write a bash script to automate running some commands. However some of these commands should be running in their own terminal tab. So I use the following in my bash script to open a new tab:

xdotool key ctrl+shift+t

this does the job, but the next commands in my bash script are still executed in the previous terminal tab. How can I make the new opened terminal tab active and run the next commands in this tab?

3

There are 3 answers

0
Thomas Maier On

What Terminal Emulator are you using? It strongly depends on this.

In general, you could write the commands you want to execute in a shell script and tell your terminal emulator to execute the script once it has started.

Example with xterm:

echo '#!/bin/bash' > /tmp/thescript 
echo 'ls -la' >> /tmp/thescript
chmod +x /tmp/thescript
xterm -hold -e /tmp/thescript

EDIT: I just saw that u asked for a way to achieve this with xdotool. So this answer might be invalid. Please tell me if so - then i'll delete it.

0
Fernando On

How are you using xdotool? It can be done with a chain, for example:

$ xdotool key "ctrl+shift+t"; xdotool type "ls"; xdotool key Return
0
pkfm On

If all you want is to run the commands in the background / in parallel, without synchronously waiting for each command to complete before the next begins, terminate them with an ampersand & to instruct the shell to do so.

Alternatively, you can execute the commands in their own subshells by surrounding each with parentheses ( ). If they are long running processes or you do not wish to pollute the original shell with their output, you can fork them off and capture their output to file with something like (setsid command 1>/path/to/log &).

If separate tabs is necessary requirement, you can use xdotool to key the switch-to-the-next-tab binding or similar, and then key the commands you must run in that tab.

Instead of sorting out that mess yourself, you could use a script from this answer by Jacob Vlijm, which wraps a windowed approach that uses xdotool and wmctrl to 'send' commands to different terminal windows. The script is written in python 3 but it can easily be rewritten for a shell environment of choice.

A more direct approach involves use of a TIOCSTI ioctl to inject characters into another terminal. According to the tty_ioctl manual page:

NAME
       ioctl_tty - ioctls for terminals and serial lines

...

DESCRIPTION

       The  ioctl(2) call for terminals and serial ports accepts many possible
       command arguments.  

   ...

   Faking input

       TIOCSTI   const char *argp
              Insert the given byte in the input queue

   ...

Here are c and perl wrappers, and an example in python as referenced by this answer.