Professional Documents
Culture Documents
Linux Basic Commands
Linux Basic Commands
by
B.Prathibha
prathibhab@cdac.in
15thSeptember,2010
9/15/10
BasicLinuxCommands
calCommandtoseecalenderforanyspecificmonthoracompleteyear
usage:cal[month][year]
eg:calsep2010
dateprintsthedateandtime
date+"%D%H:%M:%S"
09/14/1014:19:43
Options:
dThedateofthemonth(131)
yThelasttwodigitsoftheyear
H,M,SHourMinuteandsecondrespectively
Dthedateinmm/dd/yy
9/15/10
BasicLinuxCommands
echo:Printmessageontheterminal
usage:echo<message>
eg:echo"Welcometotheworkshop"
o/p:Welcometotheworkshop
passwdallowsyoutochangeyourpassword
mandisplaysthedocumentationforacommand
usage:man<commandname>
eg:manmkdir
9/15/10
LinuxFileSystem
9/15/10
Standarddirectorystructure
Standarddirectorystructure
/thetopmost
/devallthedevicesareaccessibleasfiles
/varvariabledatasuchasmails,logfiles,databases
/usralmostallthepackagesinstalled
/etcconfigurationfiles
/homehomedirectoriesforalltheusers
/roothomedirectoryoftheprivilegeduserroot
/mntusedtomountotherdirectories/partitions.
9/15/10
ShellMetacharacters
MetacharactersThesearespecialcharactersthatarerecognisedbytheshell.
*matches0ormorecharacters.
eg:ls*.c
?matchesanysinglecharacter
eg:lsab?.c
[]Thiswillmatchanysinglecharacterintherange.
eg:lstut[09].m
Thiswillfindfilessuchastut0.m,tut9.metc.,
>Redirectstandardoutputtoafile.
echohelloworld>hello.txt
9/15/10
ShellMetacharacters
>>Appendsstandardoutputtoafile.
eg:echoHelloAgain>>hello.txt
9/15/10
<Takesstandardinputfromafile
|Thisispipecharacter.Sendstheoutputoffirstcommandasinputforthe
secondcommand.
FileSystemCommands
mkdirmakedirectory
usage:mkdir<dirname>
eg:mkdirppath/test/test1
p>noerrorifexisting,makeparentdirectoriesasneeded
cdchangedirectories
Usecdtochangedirectories.Typecdfollowedbythenameofadirectoryto
accessthatdirectory.
mvchangethenameofadirectory
Typemvfollowedbythecurrentnameofadirectoryandthenewnameof
thedirectory.
Ex:mvtestdirnewnamedir
9/15/10
FileSystemCommands
cpcopyfilesanddirectories
usage:cpsourcedestination
cpimyfileyourfile
Withthe"i"option,ifthefile"yourfile"exists,youwillbepromptedbeforeitis
overwritten.
cprsrcdirdestdir
Copyallfilesfromthedirectory"srcdir"tothedirectory"destdir"recursively.
rmdirRemoveanexistingdirectory
rmremovefilesordirectories
Usage:rmrname
Removesdirectoriesandfileswithinthedirectoriesrecursively.
9/15/10
FileHandlingCommands
9/15/10
10
FileHandlingCommands
catusedtodisplaythecontentsofasmallfileonterminal
usage:cat<filename>
catwhensuppliedwithmorethanonefilewillconcatenatethefileswithout
anyheaderinformation
moreandlesscommandsareusedtoviewlargefilesonepageatatime
usage:more<filename>
usage:less<filename>
9/15/10
11
FileHandlingCommands
wccommandisusedtocountlines,wordsandcharacters,dependingonthe
optionused.
usage:wc[options][filename]
Youcanjustprintnumberoflines,numberofwordsornumberofcharcters
byusingfollowingoptions:
l:Numberoflines
w:Numberofwords
c:Numberofcharacters
9/15/10
12
SimpleFilters
9/15/10
13
Filters
Filtersarecommandswhichacceptdatafromstandardinput,manupulateit
andwritetheresultstostandardoutput.
Headdisplaysthelinesatthetopofthefile
whenusedwithoutanyoptionitwilldisplayfirst10linesofthefile
usage:headfilename
n>printthefirstNlinesinsteadofthefirst10
taildisplaysthelinesattheendofthefile.Bydefaultitwilldisplaylast10
linesofthefile
usage:tailfilename
9/15/10
14
cut&paste
cutcommandcanbeusedtocutthecolumnsfromafilewithcoption.
eg:cutc1,35/etc/passwd
Withfoptionyoucancutthefeildsdelemitedbysomecharacter
eg:cutd:f2/etc/passwd
doptionisusedtospecifythedelimiterandfoptionusedtospecifythe
feildnumber
pastecommandwillpastethecontentsofthefilesidebyside
eg:pastea.txtb.txt
9/15/10
15
Orderingafile
sortreorderslinesinthefile
whitespacesfirst,thennumerals,uppercaseandfinallylowercase
youcansortthefilebasedonafieldbyusingtandkoption.
Eg:sortt""k2students.txt
sortsthefilebasedonthesecondfieldusingthedelimiterasspace
r>reversestheresult
9/15/10
16
Searchingforapattern
grepscansitsinputforapattern,displaysthelinecontainingthatpattern
usage:grepoptionspatternfilename(s)
searchingforatextstringinone
grep'boss'/etc/passwd
searchesforthepatternbossinthe/etc/passwdfile
searchingforatextstringinmultiplefiles
greproot*.txt
CaseinsensitivefilesearchingwiththeUnixgrepcommand
grepihellohello.txt
Reversingthemeaningofagrepsearch
grepvboss/etc/passwd
Displaysallthelinesthatdonotcontainthespecifiedpattern
9/15/10
17
Searchingforapattern
UsinggrepinaUnix/Linuxcommandpipeline
lsal|grep^d
printthelinesthatstartswithd
Linuxgrepcommandtosearchformultiplepatternsatonetime
egrepboss|root/etc/passwd
greppatternmatchingandregularexpressions(regexpatterns)
grep'[FG]oo'*
grep'[09][09][09]'*
grep'^fred'/etc/passwd
9/15/10
18
sed
sededitorforfilteringandtransformingtext
i>editthefilesinplace
sedi'1,10d'hello.txt
deletedthefirst10linesfromhello.txt
sedi2ihaihello.txt
Insertsthetexthaiinthesecondline
sedi'/hello/d'hello.txt
Deletedthelinecontainingthepatternhello.
sed's/hello/world/'hello.txt
Replacesthefirstoccurrenceofhellooneachlinetoworld.
sed's/hello/world/g'hello.txt
Replacesalltheoccurrencesofhellooneachlinetoworld.
9/15/10
19
LinuxCommands
pwdprintworkingdirectory
willshowyouthefullpathtothedirectoryyouarecurrentlyin.
shredoverwriteafiletohideitscontents
Theresultisthatyourfileissothoroughlydeleteditisveryunlikelytoeverbe
retrievedagain.
lnstestsymlink
Createsasymboliclinknamedsymlinkthatpointstothefiletest
freeDisplaystheamountofusedandfreesystemmemory.
9/15/10
20
LinuxCommands
wshowwhoisloggedonandwhattheyaredoing
usage:w
whoshowwhoisloggedin
usage:who
whob>lastsystemboottime
whoamiprintstheeffectiveuserid.
whereisls Locatesbinariesandmanualpagesforthelscommand.
catdisplaysthecontentsofthefileonthescreen.
9/15/10
21
LinuxCommands
dfreportfilesystemdiskspaceusage
Usage:dfh
h>printsizesinhumanreadableformat
dusummarizediskusageofeachfile,recursivelyfordirectories.
Usage:duh
findFindlocationsoffiles/directoriesquicklyacrossentirefilesystem
Usage:find/nameappnametypedxdev
typedsearchforthedirectorynamedappname
xdevDon'tdescenddirectoriesonotherfilesystems.
searchagainstalldirectoriesbelow/fortheappnamefoundindirectoriesbutonly
ontheexistingfilesystem.
9/15/10
22
LinuxCommands
Commandtofindandremovefiles
find.name"FILETOFIND"execrmrf{}\;
lspciautilityfordisplayinginformationaboutPCIbusesinthe
systemanddevicesconnectedtothem.
vdisplaysadetailedinformation.
lsusbautilityfordisplayinginformationaboutUSBbusesinthe
systemandthedevicesconnectedtothem.
vdisplaysadetailedinformation.
9/15/10
23
LinuxCommands
lshwlistthehardware
hwinfoprobsforthehardware
cat/proc/cpuinfogivesinformationaboutcpu
cat/proc/meminfogivesinformationaboutmemory
9/15/10
24
pscommand
ps(i.e.,processstatus)commandisusedtoprovideinformationaboutthe
currentlyrunningprocesses,includingtheirprocessidentificationnumbers
(PIDs).
pslistsalltheprocesses
usage:psaux
killtokillaprocess
psismostoftenusedtoobtainthePIDofamalfunctioningprocessinorder
toterminateitwiththekillcommand
usage:kill9pid
wherepidprocessidoftheprocesstobekilled.
9/15/10
25
TaskAutomation
Cronisthenameofprogramthatenableslinuxuserstoexecutecommands
orscripts(groupsofcommands)automaticallyataspecifiedtime/date.
Youcansetupsetupcommandsorscripts,whichwillrepeatedlyrunataset
time.
Thecronservice(daemon)runsinthebackgroundandconstantlychecksthe
/etc/crontabfile,/etc/cron.*/directories.
Italsochecksthe/var/spool/cron/directory.
Toeditthecrontabfile,typethefollowingcommandattheLinuxshell
prompt:
crontabe
Syntaxofcrontab(FieldDescription)
mhdommondow/path/to/commandarg1arg2
where
9/15/10
26
TaskAutomation
m:Minute(059)
h:Hours(023)
dom:Date(031)
mon:Month(012[12==December])
dow:weekdays(07[0or7sunday])
/path/to/commandScriptorcommandnametoschedule
Ifyouwishedtohaveascriptnamed/root/backup.shruneverydayat3am,
yourcrontabentrywouldlooklikeasfollows:
03***/root/backup.sh
Executeeveryminute
*****/bin/script.sh
Thisscriptisbeingexecutedeveryminute.
9/15/10
27
TaskAutomation
ExecuteeveryFriday1AM
Toschedulethescripttorunat1AMeveryFriday,wewouldneedthefollowing
cronjob:
01**5/bin/execute/this/script.sh
Thescriptisnowbeingexecutedwhenthesystemclockhits:
1.minute:0
2.ofhour:1
3.ofdayofmonth:*(everydayofmonth)
4.ofmonth:*(everymonth)
5.andweekday:5(=Friday)
9/15/10
28
TaskAutomation
Executeonworkdays1AM
ToschedulethescripttorunfromMondaytoFridayat1AM,wewouldneed
thefollowingcronjob:
01**15/bin/script.sh
Thescriptisnowbeingexecutedwhenthesystemclockhits:
1.minute:0
2.ofhour:1
3.ofdayofmonth:*(everydayofmonth)
4.ofmonth:*(everymonth)
5.andweekday:15(=MondaytillFriday)
9/15/10
29
TaskAutomation
Execute10pastaftereveryhouronthe1stofeverymonth
10*1**/bin/script.sh
ifyouwanttorunsomethingevery10minutes:
0,10,20,30,40,50****/bin/script.sh
or
*/10****/bin/script.sh
SpecialWords
Ifyouusethefirst(minute)field,youcanalsoputinakeywordinsteadofa
number:
@rebootRunonce,atstartup
@yearlyRunonceayear"0011*"
@annually(sameas@yearly)
9/15/10
30
TaskAutomation
@monthlyRunonceamonth"001**"
@weeklyRunonceaweek"00**0"
@dailyRunonceaday"00***"
@midnight(sameas@daily)
@hourlyRunonceanhour"0****
Eg:@daily/bin/script.sh
Storingthecrontaboutput
Tostoretheoutputinaseparatelogfile.Here'show:
*/10****/bin/script.sh2>&1>>/var/log/script_output.log
9/15/10
31
Howtousevieditor
Startingvi
Youmayusevitoopenanalreadyexistingfilebytyping
vifilename
viModes
vihastwomodes:
*commandmode
*insertmode
Incommandmode,thelettersofthekeyboardperformeditingfunctions
(likemovingthecursor,deletingtext,etc.).Toentercommandmode,press
theescape<Esc>key.
Ininsertmode,thelettersyoutypeformwordsandsentences.Unlikemany
wordprocessors,vistartsupincommandmode.
9/15/10
32
Howtousevieditor
EnteringText
Inordertobeginenteringtextinthisemptyfile,youmustchangefrom
commandmodetoinsertmode.Todothis,type
I
DeletingWords
Todeleteaword,movethecursortothefirstletteroftheword,andtype
dw
Thiscommanddeletesthewordandthespacefollowingit.
Todeletethreewordstype
3dw
9/15/10
33
Howtousevieditor
DeletingLines
Todeleteawholeline,type
dd
Thecursordoesnothavetobeatthebeginningoftheline.Typingdddeletes
theentirelinecontainingthecursorandplacesthecursoratthestartofthe
nextline.Todeletetwolines,type
2dd
Todeletefromthecursorpositiontotheendoftheline,type
D(uppercase)
9/15/10
34
Howtousevieditor
ReplacingCharacters
Toreplaceonecharacterwithanother:
1.Movethecursortothecharactertobereplaced.
2.Typer
3.Typethereplacementcharacter.
Thenewcharacterwillappear,andyouwillstillbeincommandmode.
ReplacingWords
Toreplaceonewordwithanother,movetothestartoftheincorrectwordand
type
cw
9/15/10
35
Howtousevieditor
Youarenowininsertmodeandmaytypethereplacement.Thenewtextdoes
notneedtobethesamelengthastheoriginal.Press<Esc>togetbackto
commandmode.Toreplacethreewords,type
3cw
ReplacingLines
Tochangetextfromthecursorpositiontotheendoftheline:
1.TypeC(uppercase).
2.Typethereplacementtext.
3.Press<Esc>.
9/15/10
36
Howtousevieditor
Movingaroundinafile
Htotoplineofscreen
Mtomiddlelineofscreen
Ltolastlineofscreen
Gtolastlineoffile
1Gtofirstlineoffile
9/15/10
37
Howtousevieditor
MovingbySearching
Tomovequicklybysearchingfortext,whileincommandmode:
1.Type/(slash).
2.Enterthetexttosearchfor.
3.Press<Return>.
Thecursormovestothefirstoccurrenceofthattext.
Torepeatthesearchinaforwarddirection,type
n
Torepeatthesearchinabackwarddirection,type
N
9/15/10
38
Howtousevieditor
Tosavetheeditsyouhavemade,butleavevirunningandyourfileopen:
1.Press<Esc>.
2.Type:w
3.Press<Return>.
Toquitvi,anddiscardanychangesyourhavemadesincelastsaving:
1.Press<Esc>.
2.Type:q!
3.Press<Return>.
9/15/10
39
ThankYou
9/15/10
40