Rerun Command as Root

Sometimes, I invoke a command in the bash shell, just to understand it requires root privileges.

Run command - root privileges required error
$ apt install mariadb
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?

A simple solution is prepend sudo to the command:

Fix root privileges required - Prepend sudo and Rerun
$ sudo apt install mariadb
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?

However, It is too much typing for me and error-prone, I have already typed this command :-)

Solution

The !! expansion of the bash shell expands to the preceding command command issued. Let’s see it in action:

!! Expansion of the bash shell
$ apt install mariadb
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
$ echo !!
echo apt install mariadb
...

As we can see, with the help !! expansion of the bash shell, we can rerun the command with minimum effort.

Fix root privileges required - using the !! expansion
$ apt install mariadb
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
$ sudo !!
sudo apt install mariadb
....
Kobi
Kobi
Software Developer

Kobi helps entrepreneurs to translate their wishes to a working product.