Ubuntu – How to execute scripts as root without pointing to its location


I tend to use sudo arp-scan --localnet --interface wlan0 a lot, but I find it cumbersome to type this each time. To speed things up, I've created a script, called arp-lw-scan, which should do this for me.

Contents of ~/Scripts/arp-lw-scan:

arp-scan --localnet --interface wlan0

I've added ~/Scripts to my $PATH in ~/.profile, so each script in that folder can get executed from any location by just typing its name in the terminal.

However, I'm having trouble executing arp-lw-scan in an easy way, because it requires root access. Just typing arp-lw-scan while being in my home directory gives an error about not having root rights. I can type sudo ~/Scripts/arp-lw-scan, and that works, but that's still pretty much to type. I want to be able to just type sudo arp-lw-scan to execute the given script.

How can I achieve this?

Best Answer

Bash aliases

Aliases are the shortcuts in the command line. The regular shell, Bash, allows you to create your own aliases.

To try it out (without saving them permanently), try this:

alias myalias='gksudo gparted'

To save them permanently, create a file ~/.bash_aliases like this:

alias myalias='gksudo gparted'
alias edsources='gksudo gedit /etc/apt/sources.list'

The default ~/.bashrc file installed for users in Ubuntu will source the ~/.bash_aliases file by default.

Aliases allow you to append more arguments and 'overrule' current commands too. A common use case of this is

alias rm='rm -i'

To get a confirmation message for everything you try to delete with rm.

In case you want to 'escape' an alias by running the original command, prepend it with a backslash. So, with the rm example, just do

\rm myfile

to remove the file without the -i option forced by the alias.

Current script

About your current approach, you should just be able to prepend the command in the one-line script with sudo (or gksudo).

Related Question