简体   繁体   中英

Understanding bashrc alias command

What does this particular alias command do?

alias hello='sudo $(history -p \!\!)' 

I want to understand what history and -p do!

Bash keeps track of the commands you run. This is called your command history . The history command lets you access and manipulate your command history.

The -p flag tells the history command to perform history substitution on its argument and print the result on standard output. When performing history substitution, history replaces !! with the previous command. In your case, each ! is escaped as \\! , presumably because bash lets you set the ! to be extra-magical and the author of this alias wanted to suppress the extra magic.

When bash sees $(...) , it performs command substitution . This means it runs the command between the parentheses, and replaces $(...) with the standard output of the command,

The sudo command runs its arguments as root.

Thus this alias lets you type hello to run your previous command as root. You will run into trouble if the previous command has quoted whitespace (I think), but usually it should work.

You can get the same effect with (in my opinion) a little less magic by using fc :

alias hello='sudo $(fc -ln -1)'

The fc command also performs history access and manipulation. The -l flag means “print some history entries”. The -n flag means don't print history entry numbers (just print the commands). The -1 (negative one) means print just the most recent history entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM