Friday, July 06, 2007

Bash Magic Tricks

Bash Magic Tricks


Introduction:
Bash or Bourne Again shell is the first thing that fascinated me in GNU/Linux. It has most of the
feature of some of the popular shell such as ksh, csh etc. From novice user to geekish hacker
everybody prefers bash for its powerful features. Bash is the default shell in all the GNU/Linux
distro coming nowadays, and not only Linux also other *nix operating system uses bash as their
shell. When I started using it, I began discovering lot of tricks which fasten my work which now
I'm sharing with you all. This article is for those who are already familiar Bash and who want to
work in lightening speed.


What's your editor?
The Bash works in two modes "Vi" mode and "Emacs" mode. In Vi mode the short cut keys
which are used in Vi editor can be applied over the bash, same like in Emacs mode it emulates
Emacs shortcut keys. you can decide which mode to work with based on your choice. Emacs
mode is set by default.


Set Emacs Mode in Bash:


set -o emacs

Set Vi Mode in Bash:


set -o vi

Shortcuts that work in Emacs mode:


Ctrl + l - Clear the screen
Ctrl + a - Move cursor to beginning of line
Ctrl + e - Move cursor to end of line
Alt + b - Move cursor back one word
Alt + f - Move cursor forward one word
Alt + backspace - Cut the word before the cursor
Ctrl + w - Cut the last word
Ctrl + u - Cut everything before the cursor
Ctrl + k - Cut everything after the cursor
Ctrl + y - Paste the last thing to be cut
Ctrl + r - Search the history
Ctrl + _ - Undo
And lot more Emacs shortcuts.



Below are the list of shortcut keys which working vi mode, Don't forget to hit escape before
executing any shortcut.


h - Move cursor left
l - Move cursor right
A - Move cursor to end of line and put in insert mode
0 (zero) - Move cursor to beginning of line (doesn't put in insert mode)
i - Put into insert mode at current position
a - Put into insert mode after current position
dd - Delete line (saved for pasting)
D - Delete text after current cursor position (saved for pasting)
p - Paste text that was deleted
/ - to search in the history commands
u - Undo
Tab Tricks:
Everyone will be familiar with the Tab key feature; it is widely used in auto completion in most
of the terminals. In bash tab key does lot of auto completion based on the first letter typed, here
"2T" means Press TAB twice.


$ 2T - List all available commands.
$ (string)2T - List all available commands starting with (string)
$ /2T - List entire directory structure including Hidden one
$ 2T - List only Sub Dirs inside including Hidden one
$ *2T - List only Sub Dirs inside without Hidden one
$ ~2T - List all Present Users on system from "/etc/passwd"
$ $2T - List all System variables
$ @2T - List entries from "/etc/hosts"
$ =2T - List output like ls or dir
Complete your last argument:


Are you tired of typing this
$cp important.txt /home/neo/archive/collection/important/confidential/personal
and you still have to copy many files?
$cp onemore.txt (Press Alt+. Or Esc and then .)
Bash will fill your last argument from the last command typed
$cp onemore.txt /home/neo/archive/collection/important/confidential/personal

Recollecting from history:
Bash has feature to recollect commands from the history, but instead of searching from the
history you can use '!' and then type first character of the command. It is one another way of
executing from the history for further information read man page of 'history'.


$/sbin/ifconfig
$dmesg
$!d
will expand and execute
$dmesg
samelike
$!/ will give the output of ifconfig
Push and pop to navigate between directories:
We can push our directories into a directory stack, and pop when needed. Sometimes we need to
access many long path of directories, we can save it by pushing it to directory stack. pushd and
popd are the builtin
used to push and pop the directories, they use $DIRSTACK variable. pushd
is like cd, but it also pushes the current working directory onto a stack before changing


directories. popd pops the top of the stack and returns you to the previous directory.
$ pwd
/home/neo/arm
$ pushd /usr/share/doc/bash
/usr/share/doc/bash /home/neo/arm
$ pwd
/usr/share/doc/bash
$ popd
/home/neo/arm
$pwd
/home/neo/arm
Go Back:
Bash stores the previous directory path in the variable $OLDPWD. Suppose you have moved
from home directory to another directory and you want to get back to you home directory then
follow the example.


$ pwd
/home/neo
$ cd /usr/share
$ cd $
pwd
/home/neo

Auto corrects the path:
When ever we change to a directory using cd command it is possible to make mistakes while
typing the path. We can avoid getting stuck there using shopt. Using the below option we can
autocorrect our mistake and continue our job without any delay.


$ shopt -s cdspell
Some typo mistake and their correction by bash
$ cd /vra
/var
$
$cd /vr/lg/
/var/log
$cd ver
/var
$
Bind your keys:
As a regular Linux user, one will have some set of command which they will run often. Make it a
shortcut key so that you save your typing time spending jus one second. Bind command lets you
to map a key or key combination for an existing command or set of commands


Single shot to connect to your remote server:
Say you regularly connect to remote server for working, make it a shortcut key using below


example.
$bind '"\M-k"':"\"telnet matrix\C-m\""
or
$bind '"\M-k"':"\"ssh neo@matrix\C-m\""
Type Alt+k and see the magic
Make your Dash board:
Monitoring a machine consist of many aspect such as memory, disk usage, process, network,
peripherals. Typing the commands and monitoring these components one by one is simply time
consuming and also tedious. Imagine dashboard functionality in a single key press 'F12'. Use this
example and add or remove monitoring command based on your choice.


bind '"\e[24~"':"\"dmesg|tail -n 6;cat /proc/net/dev;ps;w;uptime;df -h;cat /proc/meminfo\C-m"""
Press F12 Key and get the dashboard info
Lot more things can be done with bind for further information read bind documentation



Confirm your logout:
Many of us accidentally press Ctrld
(logout) when trying some short cut keys and gets logged
out of that session. To avoid it set the below line , it will ignore the EOF i.e. Ctrld
once, the
second time when you give Ctrld
it will log out, instead of 1 you can also make your own choice
of count.


$export IGNOREEOF=1

Substitute and execute:
This tip is very useful when we are working in a remote machine especially low bandwidth or
high traffic connection. if you do a single mistake it will takes too much time to correct it.


$less /usr/she/doc/bash/FAQ

The above command will fail since "share" is misspelled as "she". To correct it, instead of going
by native method of using arrow keys use the below example. This will substitute the misspelled
with correct and execute it.


$^she^share^
The syntax is $^^^


(NOTE: It changes only the first occurrence of the pattern from left to right)


Conclusion:


These trick will really help us to fasten our work, also makes life easier. Still there are many
hidden tricks in bash, it needs some time for me to consolidate it and make another part of this
article. For any queries/suggestion feel free to contact me at mail2krish[at]gmail[dot]com

34 comments:

Marilyn said...

Thanks for writing this.

Magicians said...

Hello, I'am George. Visit my website, if you want to learn Magic Tricks Revealed.

Anonymous said...

Hi
propecia no prescription
It was then used for the treatment for prostate enlargement.
[url=http://www.denverindependent.com/]propecia cost[/url]
It will be better for you to take some advice from them.
http://www.denverindependent.com/ - generic propecia online
There is lots of essential information which you can get from there.

Anonymous said...

That is easy obtainable as you don39t have to fax anything and the famous. Inheritance Funding Company - Cash advances on inheritances in probate.

Anonymous said...

dating advice for men [url=http://loveepicentre.com/]dating personals plymouth[/url] advice child dating man http://loveepicentre.com/ lesbian personals

Anonymous said...

car audio equipment for gmc [url=http://www.cardvdplanet.com/car-dvd-vcd-cd-usb-sd-mmc-wma-mp4-player-with--discount-price18.html]videovisor auto dvd visor[/url] selling auto audio http://www.cardvdplanet.com/7-inch-car-dvd-with-touch--discount-price102.html discount auto audio
auto dvd player portable [url=http://www.cardvdplanet.com/gps-car-dvd-player-online-store4.html]compatible wireless headphones for all auto dvd systems[/url] car audio toyota http://www.cardvdplanet.com/car-radio-with-usb-sd-mmc-card-cd151--discount-price49.html overhead auto dvd player
d mercedes benz reviews auto extended warranty car audio and [url=http://www.cardvdplanet.com/7-inch-portable-dvd-player-support-tv--discount-price111.html]racing car audio[/url] auto dvd http://www.cardvdplanet.com/car-dvd-player-with-fm-function-cd137--discount-price50.html videovisor auto dvd visor

Anonymous said...

atenolol drug [url=http://usadrugstoretoday.com/products/rogaine-5-.htm]rogaine 5 [/url] stress reduction kit http://usadrugstoretoday.com/products/noroxin.htm blood lilies http://usadrugstoretoday.com/products/generic-keflex.htm
my poor old heart by allison krauss [url=http://usadrugstoretoday.com/categories/mujeres-mejoramiento.htm]mujeres mejoramiento[/url] postpartum depression term paper [url=http://usadrugstoretoday.com/categories/antibiotika.htm]inflamatory breast disease[/url]

Anonymous said...

anatomical urinary tract infection [url=http://usadrugstoretoday.com/products/coumadin.htm]coumadin[/url] shyness depression social anxiety http://usadrugstoretoday.com/products/zithromax.htm chewing gum on the bed post overnight http://usadrugstoretoday.com/categories/anti-depressant-anti-anxiety.htm
fda approved weight loss pill [url=http://usadrugstoretoday.com/products/biaxin.htm]biaxin[/url] natural weight loss pharmacy [url=http://usadrugstoretoday.com/categories/anti-depresseur---anti-anxiety.htm]cough medicine for a 1 year old[/url]

Anonymous said...

http://healthboard.in/cordarone/cordarone-intravenous
[url=http://healthboard.in/bust/transgender-bust]lowest price for brand cialis[/url] drug investigation [url=http://healthboard.in/diclofenac/tw-diclofenac]tw diclofenac[/url]
does heinz drug test http://healthboard.in/crestor/crestor-law-suit
[url=http://healthboard.in/brahmi]drugs financial aid federal law[/url] state registration for pharmacy techs [url=http://healthboard.in/carbamazepine/known-side-effects-of-carbamazepine]known side effects of carbamazepine[/url]
jobs pharmacy http://healthboard.in/cozaar
[url=http://healthboard.in/dicyclomine/dicyclomine-hydrochloride]cialis in usa[/url] martinez transport drug seizure [url=http://healthboard.in/carbidopa/extraction-method-for-carbidopa-levodopa]extraction method for carbidopa levodopa[/url] black list drugs [url=http://healthboard.in/desloratadine/desloratadine]desloratadine[/url]

Anonymous said...

http://meen.in/ethinyl-estradiol/comparing-ethinyl-estradiol-dose
[url=http://meen.in/cialis/cialis-side-effects-with-cannabis]giant pharmacy in dunkirk[/url] risperodol interactions with cialis viagra levitra [url=http://meen.in/exelon/adverse-reactins-to-exelon-patch]adverse reactins to exelon patch[/url]
herbal alternative to viagra http://meen.in/cipro/can-cipro-cause-vertigo
[url=http://meen.in/clavulanate/what-is-clavulanate-potassium]class d felony definition drugs[/url] achat cialis [url=http://meen.in/clavulanate/amoxicillin-and-clavulanate]amoxicillin and clavulanate[/url]
cialis pills online http://meen.in/cetirizine/cetirizine-ratiopharm-uk
[url=http://meen.in/cialis/cialis-experiences]bronx drug bust nick santana[/url] teen drug use statistacs [url=http://meen.in/flomax/flomax-medications]flomax medications[/url] pharmacy illegal shippment [url=http://meen.in/fenofibrate]fenofibrate[/url]

Anonymous said...

http://alwayshealth.in/penis/naturally-harder-penis
[url=http://alwayshealth.in/general-medical/non-medical-treatment-for-adhd]meletonin and erectile dysfuntion[/url] soul pattinson pharmacy [url=http://alwayshealth.in/oxybutynin/oxybutynin-chloride-hyperhidrosis]oxybutynin chloride hyperhidrosis[/url]
pictures of illegal drug speed http://alwayshealth.in/pills/what-are-some-safe-diet-pills
[url=http://alwayshealth.in/oxybutynin/oxybutynin-chloride-hyperhidrosis-dermitologist]generic bone density drugs[/url] computers drug designing [url=http://alwayshealth.in/heart-rate]heart rate[/url]
viagra edinburgh search find free http://alwayshealth.in/canada-pharmacy/liggits-suburban-pharmacy
[url=http://alwayshealth.in/heart-rates/fast-heart-sounds]the creator of drugs[/url] aas pharmacy service llc [url=http://alwayshealth.in/syndrome/klimefelyers-syndrome]klimefelyers syndrome[/url] illegal drugs and how they affect you [url=http://alwayshealth.in/pill/pill-s]pill s[/url]

Anonymous said...

lima peru travel agency http://atravel.in/airlines_united-airlines-china scooter world travel
[url=http://atravel.in/tourist_tourist-graflex]travel backpack recommendations[/url] vintage avion travel trailers [url=http://atravel.in/adventure_youghagheny-adventure-race]youghagheny adventure race[/url]
munro travel agent http://atravel.in/travel_dwi-conviction-limiting-travel
[url=http://atravel.in/tours_christian-bus-tours-to-sight-and-sound]braun travel clock[/url] hard travel cases [url=http://atravel.in/flight_image-showing-flight-of-the-bumble-bee]image showing flight of the bumble bee[/url]
travel directions to port everglades carnival http://atravel.in/disneyland around the world air travel 20 [url=http://atravel.in/tours_everglades-tours]everglades tours[/url]

Anonymous said...

polish horseshoes http://topcitystyle.com/accessories-page5.html kid shoes [url=http://topcitystyle.com/ed-hardy-tattoo-design-stretch-brief-for-men-item1400.html]adidas hemp shoes[/url] domnatricks shoes
http://topcitystyle.com/-classic-dolce-amp-gabbana-category87.html born shoes paddock [url=http://topcitystyle.com/?action=products&product_id=1689]nursing shoes[/url]

Anonymous said...

adult toy male doll http://planetofporn.in/adult-online/lollypops-adult
[url=http://planetofporn.in/erotic-video/erotic-art-japan]adult comix gallery[/url] determine your cocker spaniel puppys estimated adult weight [url=http://planetofporn.in/best-amateur/amateur-free-site-woman]amateur free site woman[/url]
free adult movie previews http://planetofporn.in/bdsm/bdsm-suspendsd
[url=http://planetofporn.in/hcg-oral/waterpik-oral-irrigator]hentai video upload[/url] hodson lubricant [url=http://planetofporn.in/first-anal/anesth-anal]anesth anal[/url]
amateur secret wife videos http://planetofporn.in/amateur-porn/amateur-japanese-couple
[url=http://planetofporn.in/amateur-porn/amateur-wife-creampie-amateur-creampie]adult dependant mi[/url] maltese puppy teeth adult canines [url=http://planetofporn.in/adult-xxx/adult-bedrooms]adult bedrooms[/url]
willamette week personals adult matchmaker http://planetofporn.in/teen-ass/cum-big-tits-ass-creampie
[url=http://planetofporn.in/anal-life/sex-anal-videos]pockemum hentai[/url] amateur frat party gang bang [url=http://planetofporn.in/erotic-gay/erotic-prostate-milking-by-women]erotic prostate milking by women[/url]

Anonymous said...

sarah callies sexy http://xwe.in/blowjob
[url=http://xwe.in/thong/free-thong-pic-galleries]amateur sex scandal[/url] full leghth hentai [url=http://xwe.in/bdsm/bull-dyke-bdsm]bull dyke bdsm[/url]
adult litersture http://xwe.in/gay-boy/free-gay-men-xxx-streams
[url=http://xwe.in/bbw/miss-forturne-bbw]amateur videos forum[/url] maplestory hentai [url=http://xwe.in/shemale/doll-shemale]doll shemale[/url]
filipina 18 xxx tgp http://xwe.in/bdsm/bdsm-tulsa
[url=http://xwe.in/blowjob/first-blowjob-stories]lovemaking and adult sites[/url] hentai pink [url=http://xwe.in/adult-video]adult video[/url]
xxx adult video free porn http://xwe.in/gay-anal/young-gay-boy-web-sites
[url=http://xwe.in/orgy/black-orgy-parties]kim koel sexy[/url] foreskin lubricant [url=http://xwe.in/thong/sexy-thong-teens-young]sexy thong teens young[/url]

Anonymous said...

ivy dripping blood clip art [url=http://usadrugstoretoday.com/categories/arthrite.htm]arthrite[/url] free screaming orgasm videos download http://usadrugstoretoday.com/products/decadron.htm
stuffed chicken breast with broccoli and cheeserecipe [url=http://usadrugstoretoday.com/categories/gums.htm]gums[/url] essays on the great depression [url=http://usadrugstoretoday.com/products/provera.htm ]breast implants for taller women [/url] consumer section of a medical library
national library of medicine sued by publishing house [url=http://usadrugstoretoday.com/products/lamictal.htm]lamictal[/url] blood test to measure insulin production http://usadrugstoretoday.com/products/generic-keflex.htm
center for advanced medicine [url=http://usadrugstoretoday.com/products/xplode--stamina--energy-and-sex-enhancer-.htm]xplode stamina energy and sex enhancer[/url] baylor college of medicine physician assistant program [url=http://usadrugstoretoday.com/products/periactin.htm ]health and safety consulting [/url] men kegel shoot

Anonymous said...

east wenatchee travel http://xwl.in/airlines/thailands-airlines vantage world travel journey
[url=http://xwl.in/airline/jetsuite-airline]sino american travel singapore[/url] cheap air travel to europe [url=http://xwl.in/plane-tickets/plane-tickets-from-mnl-to-nra]plane tickets from mnl to nra[/url]
travel inn horsham http://xwl.in/vacation-packages/yellowstone-national-park-vacation-packages
[url=http://xwl.in/airlines/airlines-reservations]carraige 5th wheel travel trailer[/url] travel package with escorts [url=http://xwl.in/airlines/indonesian-garoda-airlines]indonesian garoda airlines[/url]
cheap england travel the world cruise http://xwl.in/motel/motel-wisconsin-liberty-pole-lodging senior travel clubs [url=http://xwl.in/airline/discount-airline-to-new-york-city]discount airline to new york city[/url]

Anonymous said...

columbia shoes http://www.thefashionhouse.us/diesel-brand37.html indian wedding clothes [url=http://www.thefashionhouse.us/dolce-amp-gabbana-on-sale-brand2.html]custom car interior gucci leather[/url] stylist fashion northwest indiana
http://www.thefashionhouse.us/black-green-red-casual-color76.html baltimore print designer [url=http://www.thefashionhouse.us/42-leather-shoes-size23.html]south korea shoes[/url]

Anonymous said...

eve auto skill trainer http://pqx.in/acura/jenkins/acura/ocala home made auto rifles gun
[url=http://pqx.in/infiniti/infiniti/hid]fanns auto salvage[/url] richard christy auto mechinc [url=http://pqx.in/maybach/maybach/mercedes]maybach mercedes[/url]
berrett jackson auto http://pqx.in/mercury/mercury/fillings/depression
[url=http://pqx.in/bike/cell/bike/reviews]regina auto exchange[/url] ed murdoch dodge [url=http://pqx.in/infiniti/infiniti/dealers/in/birmingham/alabama]infiniti dealers in birmingham alabama[/url]
automobile bicycle carrier http://pqx.in/bentley/bentley/traditions
[url=http://pqx.in/martin]auto west imports redding ca[/url] buffalo auto show [url=http://pqx.in/audi/obd2/socket/audi/a6/tdi]obd2 socket audi a6 tdi[/url]

viagra online said...

Nice work very professional weblog!!
buy viagra
generic viagra
thanks for sharing!!!

Anonymous said...

denali road lottery pass http://lwv.in/jokers/jokers-wild-movie pros and cons of casino
[url=http://lwv.in/betting/hilton-gaming-and-betting]lottery management[/url] tennessee state lottery scholarship [url=http://lwv.in/slots/pci-vesa-local-bus-pc-slots]pci vesa local bus pc slots[/url]
el casino san juan http://lwv.in/jackpot/winning-megamillions-jackpot-numbers
[url=http://lwv.in/bingo/army-navy-bingo-gaffney-sc]bingo pinball machine[/url] blackjack tea [url=http://lwv.in/casino-online/blackjack-odds-online-casino]blackjack odds online casino[/url]
casino new buffalo michigan http://lwv.in/slots/free-slots-for-fun-only ken houston blackjack [url=http://lwv.in/bingo/real-money-bingo]real money bingo[/url]

Anonymous said...

This solved my big problem

Anonymous said...

Dude, so much AD here, why not clean them all?

Anonymous said...

Thanks for the writing this! I’m new at this game so am trying to catch up.

Anonymous said...

Very helpful tips. I had no idea of that at all.

Anonymous said...

Very helpful tips. I had no idea of that at all.

Anonymous said...

I have to say that www.blogger.com is really a good website

Anonymous said...

renegade movie [url=http://moviestrawberry.com/films/film_brother_bear/]brother bear[/url] the movie a new wave http://moviestrawberry.com/films/film_lady_and_the_tramp_ii_scamp_s_adventure/ jim carey movie
lanier movie [url=http://moviestrawberry.com/films/film_garden_party/]garden party[/url] horor movie by william in 1939 http://moviestrawberry.com/films/film_down_in_the_valley/ ron jeremy movie clips
sony vegas movie studio dvd 8 [url=http://moviestrawberry.com/films/film__00/] 00[/url] dane cook movie fall 2007
movie theater projecters [url=http://moviestrawberry.com/films/film_how_to_fish/]how to fish[/url] catlina cruz lesbian movie http://moviestrawberry.com/hqmoviesbyyear/year_1974_high-quality-movies/ indiana jones and the temple of doom movie photos
scarface al pacino movie songs [url=http://moviestrawberry.com/films/film_presumed_innocent/]presumed innocent[/url] lifetime murder of princess diana movie http://moviestrawberry.com/films/film_dana_carvey_squatting_monkeys_tell_no_lies/ adult movie lists

Anonymous said...

music from the movie the brave one [url=http://moviestrawberry.com/films/film_posse/]posse[/url] movie access http://moviestrawberry.com/films/film_cheaper_by_the_dozen/ free julia bond double o anal movie
free hardcore movie picture sex [url=http://moviestrawberry.com/films/film_the_mist/]the mist[/url] movie theathers danville virginia http://moviestrawberry.com/films/film_gnomes_and_trolls_the_secret_chamber/ movie stars images
movie roger maras [url=http://moviestrawberry.com/films/film_norbit/]norbit[/url] no smoking indian movie
shadow divers movie [url=http://moviestrawberry.com/films/film_yonkers_joe/]yonkers joe[/url] gay movie list http://moviestrawberry.com/films/film_an_unmarried_woman/ movie review for hildago
world war one secondary source movie kids [url=http://moviestrawberry.com/films/film_killer_bean_forever/]killer bean forever[/url] movie music inventions http://moviestrawberry.com/films/film_raising_flagg/ regal movie theatre

Anonymous said...

I understand this question. It is possible to discuss.

Anonymous said...

It agree, very good message

Anonymous said...

I think, that you are mistaken. Let's discuss it. Write to me in PM.

Anonymous said...

You were mistaken, it is obvious.

Anonymous said...

Me and ozzy fucked more challenging, trying to show to our
god! FUCK YES!' prior to cumming inside my warm pussy. were still fucking

Feel free to surf to my web blog :: hcg injections