IntelliJ Idea - Run sudo bash script as external tool
How to run a bash script that requires elevated permissions as external tool in Jetbrains IntelliJ Idea.
Running a bash script that requires root privileges as an external tool in IntelliJ Idea could be tricky. The execution might run into errors or displays a password prompt without hiding the entered characters. That's not nice.
The following test script shows how one might write a bash script that requires root privileges. What it does first is printing the username on the console using whoami
. Running whoami
will display the username of the user logged in for the current session.
It then tests whether the user is already root
or not. If not, then the absolute path of the script is determined and the script is called again using sudo "$script_path" "$@"
with the arguments previously provided.
After making the script executable with chmod
, we're able to run it:
First, whoami
writes the current username to the console. Then you will be asked for the root password.
After entering the password, the script is called again. whoami
will now write root
to the console.
Problem
IntelliJ Idea allows users to Configure third-party command-line applications as external tools to run them from IntelliJ IDEA [1]. To create a new external tool follow the instructions described on Jetbrains "External tool settings" page [2].
For this demonstration the settings are as follows:
To run the new tool, right click on the editor area and choose Bash scripts | Testscript
. This leads to some ugly error messages:
Another solution that uses a wrapper bash script to run sudo first results in an unsatisfactory password prompt that doesn't hide the password:
Solution
The solution for me was to write a python wrapper script (my_sudo_bash_script_wrapper.py
) and use it to execute the bash script. In the example given below, the bash script name is hardwired. This can of course be changed so that the wrapper is able to run arbitrary bash scripts whose names/locations are then passed to the wrapper as arguments.
The gnome-terminal is a terminal emulator used by default on GNOME-based Linux desktop environments such as Ubuntu, Fedora, and Debian. This means that the solution may not work for you if the above requirements are not met.
The settings in "External tool settings" must now be changed as follows:
If the external tool is now executed, a terminal window opens and the bash script is executed there.
References
- Jetbrains, External tools, Accessed on Sep 01, 2023. [Online]. Available: https://www.jetbrains.com/help/idea/2023.2/settings-tools-external-tools.html
- Jetbrains, External tools settings, Accessed on Sep 01, 2023. [Online]. Available: https://www.jetbrains.com/help/idea/2023.2/settings-tools-external-tools.html