Wednesday, November 16, 2011

Saving a root owned file as normal user from within Vi/Vim

This happens lot of times. I login as a normal user and start to edit root owned file in vim / vi text editor. However, I'm not able to save changes due to permission issue (all config files are owned by root). So to save file, i can do :w !sudo tee % where
:w - Write a file.
!sudo - Call shell sudo command.
tee - The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):

Sunday, June 5, 2011

Effective usage of watch

Sometimes is useful to run over and over again the same command until something happen,
Sure you can use bash history and use up arrow and return over and over again, or perhaps write some line of bash to get an infinite loop that run the same command, but there is a smarter approach to this : watch

watch -d "ls -alrt /tmp/


The most common options for watch are:

-n set the interval in seconds.
-d flag will highlight the differences between successive updates.
-b option causes the command to beep if it has a non-zero exit.
-e cause watch to exit on an error from the program running.

watch -n 1 "mysqladmin --user=root --password=mypassword processlist"

watch 'ps -eo pcpu,pid,user,args | sort -k 1 -n -r | head -10'