1

For example is it possible if I could something like below.

alias sd='sudo su - <parameter>'

if I write like below in command prompt.

$sd parameter

It would sudo me to given ID as parameter.

Also,

alias chdr='cd /dir1/dir2/dir3/<parameter>'
$chdr parameter
Ahmad
  • 587

2 Answers2

3

Simply define

alias sd='sudo su -'

and write

sd username

You can't pass parameters to an alias, but once the alias has been expanded, the words after it become arguments to the command.

Instead of sudo su - username, you could use sudo -u username -i (unless your sudo configuration is restricted to running su, which doesn't bring any security benefits whatsoever).

If you want anything more complicated, use a function instead of an alias.

chdr () {
  cd "/dir1/dir2/dir3/$1"
}

You can pass arguments to a function. In the function definition, "$1" is replaced by the first parameter, "$2" by the second parameter, etc. Don't forget to put double quotes around variable expansions.

For this specific case, you may like CDPATH, if your shell supports this feature (check your shell's manual).

Any for the sudo use case, you may prefer this function which runs a login shell if it isn't passed any arguments except the user name, or runs the specified command if passed more arguments. $# is replaced by the number of arguments, and "$@" passes all arguments through unchanged.

sd () {
  if [ $# -eq 1 ]; then
    sudo -i -u "$1"
  else
    sudo -u "$@"
  fi
}

(I assume you use a Bourne-style shell, such as sh, ksh (any variant), bash, zsh, etc. (T)csh works differently.)

0

try this: alias sd='sudo su - $1'

  • 1
    This won't work for the cd command due to a stray space: alias ep='echo "/$1"'; ep -> /, ep gg -> / gg – Murphy Feb 26 '16 at 15:33
  • Tried and tested with sudo, works. Murphy, can you please elaborate – Ahmad Feb 26 '16 at 15:39
  • 1
    @Ahmad I'm sure it will work with sudo, but you asked for a second construct to append the parameter to a dir list of the cd command. I don't think that works due to the space that's inserted before the parameter. Perhaps you should use a script for that one. – Murphy Feb 26 '16 at 15:56
  • 2
    This works only by coincidence, because two mistakes happens to cancel out. It does not pass parameters to the alias. With this definition, sd foo expands to sudo su - $1 foo. Then, since $1 is usually empty at an interactive prompt, you get sudo su - foo. – Gilles 'SO- stop being evil' Feb 26 '16 at 22:43