How can I pass an alias to sudo?

38

7

I have tried putting my aliases in ~/.bash_profile, ~/.bashrc, /etc/profile, and /etc/bashrc.

I am still unable to execute the following:

alias zf2="php public/index.php"

and then execute:

sudo zf2 orm:info

The issue seems to be that I am unable to specify an alias as a command using visudo-- which causes a syntax error.

So I am unable to call:

sudo zf2 orm:info

However, I was able to create a script at /usr/share/scripts/zf2 which contains:

#!/bin/bash

alias zf2="php public/index.php"
zf2 $1

and add this script as the command in visudo. When this script is in the end user's PATH I am able to execute

zf2 orm:info

I have different aliases like zf2 that I need to expose to the end user. I would prefer to maintain alias instead of a collection of scripts.

Michael Niño

Posted 2017-06-19T21:33:04.413

Reputation: 555

1Unfortunately I want to use aliases in visudo and I am unable. – Michael Niño – 2017-06-21T02:57:50.150

2That is not possible. Aliases are handled by the shell (in your case bash) and expanded before being sent to the application. sudo itself knows nothing about aliases. – Steven – 2017-06-21T03:49:40.947

2Because @Steven is technically correct, you should clarify whether you simply want to expand aliases prior to sudo being passed the line, or whether you want the aliases expanded in the elevated environment. Pedantry isn't merely a way to elicit eye-rolls. (Wow, but that last sentence doesn't look kosher at all.) – can-ned_food – 2017-06-21T06:44:25.250

3

Possible duplicate of How can I alias a command for sudo?

– Gilles 'SO- stop being evil' – 2017-06-21T09:26:02.867

1Try it with sudo -E – Denis de Bernardy – 2017-06-21T10:33:14.180

Answers

66

Ironically, the solution is to call sudo from an alias.

alias sd="sudo "

Note: While not recommended, you could name the alias sudo: alias sudo="sudo "

Bash Reference Manual (Aliases)

If the last character of the alias value is a blank, then the next command word following the alias is also checked for alias expansion.

Steven

Posted 2017-06-19T21:33:04.413

Reputation: 24 804

7I can maybe see reasons why someone would and would not want this done as the default for any system. The convenience and expectation as asked, versus being more careful with elevated privileges. – Pysis – 2017-06-20T02:13:43.980

5alias sd="sudo " maychance? – The Nate – 2017-06-20T03:00:04.577

After reviewing my aliases I noticed that I did not have alias sudo="sudo " in the end users environment. This is the answer – Michael Niño – 2017-06-21T22:55:25.803