When you use xdotool commands in a script, they might not work as expected. Even though they’re fine when you type them in the terminal, they don’t do what you want in a script. Here’s why:
- Subshell Trouble: If you use
. (dot)
instead of./ (slash)
to run the script, it runs in a subshell. This makes the script act differently from running it directly in the main shell. - Parent Process ID (PPID) Problem: When you exit the script using exit, it just stops the subshell, not the main shell. To stop the whole shell where the script was launched, you have to find the parent process ID (PPID) and end it.
How To Fix Xdotools Not Working In Shell Script
Here are some methods advised by StackOverFllow users that will help you to resolve this problem. and Here are some solutions to tackle this error and get your app running smoothly.
1. Correctly Sourcing the Script
When you use “.” to run a script, it runs within the current shell. To verify it acts right, use “./” to run the script as its own thing. For example:
# Incorrect (subshell execution)
. myscript.sh
# Correct (separate process)
./myscript.sh
2. Killing the Parent Shell
To close the main shell from your script, you can do this:
#!/bin/bash
echo "Closing main shell in 3 seconds..."
sleep 3
kill ${PPID}
Just be careful not to close important things like your window manager by error. You can change what the script says by editing the “echo” line.
3. Background Execution
Running commands in the background means letting them do their position without waiting for them to finish before moving on to the next task. For instance, if you’re launching an application, you can add ‘&‘ at the end of the command to run it in the background.
#!/bin/bash
mupdf example.pdf & # Launch mupdf in the background
sleep 1
xdotool search --class mupdf windowactivate --sync type 'f'
Also Read: Why is My Pinterest Search Not Working?