Using the nice command with an alias

How can I use the nice command with an alias?

As an example:

alias list=ls list # works nice -10 list # doesn't work 

How can I do this last job?

+4
source share
4 answers

An alias is a shell function, and nice is an external program:

 $ type nice nice is hashed (/usr/bin/nice) 

This is a nice program that runs the command passed as an argument by calling the C execve function, so all arguments for it must be evaluated before being called.

So, it would be better not to use an alias and just put the whole command needed there, but if you really want it, you can try something like this:

 $ nice -10 `alias list | sed "s/^\(alias \)\?[^=]\+='//; s/'$//;"` 

alias list prints the alias list definition in the format alias list='ls' (or list='ls' if it is /bin/sh ), so I did some sed replacements there to get only the command that it extends.

If you are sure that you are using only bash , you can use ${BASH_ALIASES[list]} instead, as noted in the comments:

 $ nice -10 ${BASH_ALIASES[list]} 
+3
source

Although perhaps not as exotic as the nice -10 $UserVar1; or nice -10 ${BASH_ALIASES[list]} , you can also request nice -10 list , although through a script wrapper instead of an alias:

 # one-time setup mkdir -p ~/.local/aliases echo 'PATH=$HOME/.local/aliases:$PATH' >> ~/.bashrc # open new terminal window, or source ~/.bashrc # create the wrapper. $@ to passthrough args. echo 'ls $@ ' > ~/.local/aliases/list chmod +x ~/.local/aliases/list nice -10 list # works :) nice -10 list --color=always -lathr # args passthrough also works :) 
+1
source

It is a bad idea. You define a command alias, but don't even use it as an alias extension. Bad coding practice here. Is this what you want.

 declare -x UserVar1='ls'; nice -10 $UserVar1; 

And if you do not change the definition of UserVar1 later in your code. There are zero reasons why you can justify using a variable instead of the actual command name.

You are heading for disaster. Plain and simple . Use a variable or command name, it is much safer and a bit more efficient and easier to read.

0
source

For Zsh, BASH_ALIASES will not work. Therefore, you can use it as follows:

 nice -10 `list` 
0
source

Source: https://habr.com/ru/post/1411902/


All Articles