- 1 BASIC COMMANDS
- 1.1 Where stuff is located
- 2 PERMISSIONS
- 2.1 Commands
- 3 FILES AND FOLDERS MANIPULATION
- 3.1 Wildcards
- 3.2 Commands
- 4 REDIRECTIONS
- 5 THE SHELL
- 5.1 Expressions
- 5.2 Keyboard tricks
- 6 PROCESSES AND MEMORY
- 7 CONFIGURATION AND ENVIRONMENT
- 7.1 Customize the prompt
- 7.1.1 Colors
- 8 PACKAGE MANAGEMENT
- 9 MEDIA STORAGE
- 9.1 Commands
- 10 NETWORKS
- 11 SEARCHING FOR FILES
- 12 ARCHIVING AND BACKUP
- 13 REGULAR EXPRESSIONS
- 13.1 Ranges
- 13.2 Counters
- 14 TEXT PROCESSING
- 15 FORMATTING OUTPUT
- 16 BASH SCRIPTING BASICS
- 16.1 Flow control
- 16.1.1 Strings Expressions evaluation
- 16.1.2 Integers Expressions evaluation
- 16.1.3 Logical operators
- 16.2 Reading inputs
- 16.2.1 Positionals params
- 16.3 Flow control
- 16.4 Variables
- 16.5 Strings
- 16.6 Numbers
- 16.7 Arrays
To chain more than one command use ; or &&
caldatedfshow free space of each partition-hshow sizes in human readable format
freeshow free space on disk-hshow sizes in human readable format
filefilename shows the MIMEtype of a filels-ashow hiddens-dshow only directories-Fclassify (if it ends with a/is a directory)lalone does the same-hshow sizes in human readable format-llong format-rreverse order-Ssort by size-tsort by timetypedisplay the command typewhichdisplay executable locationmancommand display help for the commandaproposcommand list of man pages for given commandwhatiscommand display short command descriptioninfocommand the same ofmanaliaslist all the aliasesalias alias_name='command chain'There are not spaces around=unalias alias_namedestroy aliashistoryshows the list of the most recent commands with an history number,!history_numberexecutes that commandalt+>show the first command in historyalt+<show the last command in history
/ The system root
/bin System binaries
/boot Linux kernel
/dev List of connected devices
/etc System configuration files and scripts
/home Each users has his folder here
/lib System shared libraries
/lost +found recovery files when crash happens
/media Mounting point of external devices
/opt Optional software installed by users
/proc Kernel stuff
/sbin System binaries
/tmp Temporary files
/usr Users stuff
/usr/bin, /usr/lib, /usr/local, /usr/sbin Stuff belonging to user's programs
/usr/share, /usr/share/doc Shared user datas and user programs libs
/var Databases and logs are all here
There are 10 symbols. The first one is for the type the number (d/L/c/b). The number 2,3 and 4 are the owner's permissions, the 5, 6 and 7 are for the group, 8, 9 and 10 are the permissions of the rest of the world. r means read, w write, x execute.
| Value | Symbols |
|---|---|
| 0 | --- |
| 1 | --x |
| 2 | -w- |
| 3 | -wx |
| 4 | r-- |
| 5 | r-x |
| 6 | rw- |
| 7 | rwx |
Another way to change permission is the symbolic notation:
uuserggroupoworldaall (u+g+o)+add permission-remove permission=set permission
idshow the user identity and his groupschmodchange modeumaskset default permissionssurun as another user (for that session of the shell)su -ccommand execute a single command as another user (the same ofsudo)sudorun as another user (for single command)chgrpchange groupchownchange owner.chown ownername [:[array of groups]] argumentspermits to set user and groups in one shotpasswd
* means any char
? one char
[expression] set of chars [!expression] the ! means exclude
Expression can be ranges or classes of chars. Classes are:
[:alnum:]a-z A-Z 0-9[:alpha:]a-z A-Z[:digit:]0-9[:lower:]a-z[:upper:]A-Z
mkdir create directory
ln create symbolic link
cp copy
-acopy owner and permissions too-iinteractive copy (otherwise it s overwrites silently)-rrecursive copy-uupdate (copy or overwrite only new or younger)-vverbose
mv move or rename
-iinteractive (otherwise it s overwrites silently)-rrecursive-uupdate (only new or younger)
rm remove files or directories
-iinteractive (otherwise it removes without confirmation)-rrecursive-fforce-vverbose
Remember! There is no UNDO for rm!
catconcats params in output destinationsortsort lines in outputuniqremove duplicates from output-donly duplicatesgrepany string or regexp apply that as filter-iignore case-vreverse matchingwccount words, lines and bytes of the outputheadprint from the beginning of the output-nspecify number of lines (default 10)
tailprint from the end of the output-nspecify number of lines (default 10)
teeget from specified input and write into specified output>write from the beginning>>append here2>write to standar error output&>destination Redirects file (STDERR) and (STDOUT) to destination&>/dev/nullRedirects file (STDERR) and (STDOUT) to `/dev/null´. This basically means to ignore output.
$((expression)) where expression is any arithmetic calculation
{range_start..range_end} prints all the combinations (it works with reversed ranges too)
An uppercased name preceded by $ is a system variable
Is possible to use double quotes in a command to ignore whitespaces.
What is contained between single quotes is considered plain text
\ to escape a single caracter
\b is a backspace
\n is a newline
\r is the carriage return
\t is a tab
ctrl+lclear screenctrl+ttranspose actual char with previous onealt+ttransponse actual word with previous onealt+llowercase from cursor to endalt+uuppercase from cursor to endctrl+kerase linectrl+uerase from cursor to the beginning of the linealt+derase from the cursor to the end of the linealt+backspaceerase last word- double tab display all the possible completions
-
pssnapshot of running processes.Rmeans process running,Ssleeping,Dunstoppable sleep,Tstopped,Zzombie,Nlow priority,<high priority process -
auxshows USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND -
topdisplay running tasks in real time and 5 lines containing the summary- uptime, number of users and average load for queued processes
- task situations
- CPU state
- amout of KU in use
- SWAP (virtual memory) in use
-
jobsdisplay running jobs -
bgplace a job in background -
fglplace a job in foreground -
killsend a signal to a process1 HUPhangup (the dial connection)2 INTinterrupt (asctrl+c)9 KILLkill the process without performing any cleanups15 TERMterminate process18 CONTresume stopped process19 STOPpause process3 QUIT11 SEGVsegmentation (memory) violation20 TSTPterminal stop28 WINCHwindow resize/change
-
killallSend a signal to all processes running any of the specified commands. If no signal name is specified, SIGTERM is sent. -
lshwList hardware -
-htmlOutputs the device tree as an HTML page. -
-xmlOutputs the device tree as an XML tree. -
-jsonOutputs the device tree as a JSON object -
-shortOutputs the device tree showing hardware paths -
-businfoOutputs the device list showing bus information, detailing SCSI, USB, IDE and PCI addresses. -
-Ctype of hardware, for examplememory -
shutdownshuts down the system -
pstreeshow processes as parent child tree -
vmstatReport virtual memory statistics: processes, memory, paging, block IO, traps, and cpu activity. -
xloadopens a windo with system stats -
tloaddraws in the termina a graph with system stats
setset shell optionsexportput in the environmentaliasprintenvshows all the system variables Some interesting variables:EDITOR,HOME,PAGER,SHELL,LANG,PATH(where executables are searched),PS1(prompt string),TERM,PWD,TZ,USER
The system configuration is established by the following files in this order:/etc/procfile, ~/.bash_profile, ~/bash_login, ~/profiler. If the user is not logged in the shell starts loading /etc/.bashrc and ~/.bashrc.
To reload the environment source .bashrc.
echo $PS1 to show the actual prompt config (generally stored in .bashrc).
In the output is possible to find \w for the working directory and \h for the full hostname.
Each color number is included between [033[ and ] and followed by a m.
| Black | 0;30 | Dark Gray | 1;30 |
| Blue | 0;34 | Light Blue | 1;34 |
| Green | 0;32 | Light Green | 1;32 |
| Cyan | 0;36 | Light Cyan | 1;36 |
| Red | 0;31 | Light Red | 1;31 |
| Purple | 0;35 | Light Purple | 1;35 |
| Brown | 0;33 | Yellow | 1;33 |
| Light Gray | 0;37 | White | 1;37 |
Packages of different systems are, obvioulsly, not compatibles; for example deb and rpm.
All systems use 2 kind of tools: low and high level management tools.
Low level tools are for install and remove packages into or from the system.
High level tools are to perform metadata searches and dependency resolution.
For Ubuntu the low level one is dpkg and the high level are. apt-get and aptitute.
dpkg --install packagefile install the given package without performing the dependecy resolution.
dpkg --list list all the installed packages.
dpkg --status packagename show the package status
dpkg -r packagename removes the package
dpkg --search packagename tells who installed that package
apt-cache search packagename (or string) looks for a repo for that package (or containing one with the given string).
apt-get install packagename install the package and performs the dependecy resolution.
apt-get remove removes the package
apt-get update and apt-get upgrade perform a global update pr upgrade
apt-cache show packagename show infos about the given package
/etc/fstab contains ext3 hard disk partitions. It shows:
- file system
- mount point
- file system type
- options Mount options of access to the device/partition
- dump frequency of backups; if is set to 0 dum is disabled
- pass Controls the order in which fsck checks the device/partition for errors at boot time. The root device should be 1. Other partitions should be 2, or 0 to disable checking.
ls /dev lists all the connected devices
mountif executed without params shows actuals mounted filesystems-tdevicename (or isoname)mounting pointmounts the filesystem. Examplesudo mount -o loop /<path>/<filename>.iso /mnt/isoto mount an ISO image as it was an external cd.unmountfdisk /dev/devicename formats that devicefsckCheck and repairmkfscreate a file systemddwrite info devicewodimburn cdmd5sumcalculate MD5 checksum
pingtracerouteservername shows the first 30 hopt to reach the specified server. * * * means DNS lookup failure.-ndisplay IPs instead of servernames-wwaiting timenetstatshows netweork settings and statistics-kdisplay the kernel routing tableftpwgeturl to download it-Oname to change the name of the file when downloaded-itextfile containing a list of url to download them all in one shotwget --ftp-user=USERNAME --ftp-password=PASSWORD URLto download from an FTP with authentication--user-agent=AGENT URLto fake an user aged as mozilla or chrome-rrecursively-Hconvert links to local version-level=NUMBERlevel of recursion. 0 means infinitesshuser@host to log into a remote hostssh host commandruns a comand on a remote hostscpscp [email protected]:foobar.txt /some/local/directoryCopy the file "foobar.txt" from a remote host to the local hostscp foobar.txt [email protected]:/some/remote/directoryCopy the file "foobar.txt" from the local host to a remote hostscp -r foo [email protected]:/some/remote/directory/barCopy the directory "foo" from the local host to a remote host's directory "bar"scp [email protected]:/some/remote/directory/foobar.txt [email protected]:/some/remote/directory/Copy the file "foobar.txt" from remote host "rh1.edu" to remote host "rh2.edu"scp foo.txt bar.txt [email protected]:~Copying the files "foo.txt" and "bar.txt" from the local host to your home directory on the remote hostscp -P 2264 foobar.txt [email protected]:/some/remote/directoryCopy the file "foobar.txt" from the local host to a remote host using port 2264scp [email protected]:/some/remote/directory/\{a,b,c\} .Copy multiple files from the remote host to your current directory on the local hostscp [email protected]:~/\{foo.txt,bar.txt\}.
locateFind by name into system db. The internal system db is updated daily but it can be manually updated withupdatedbfindaccepts some options-name-size-empty-groupname-neweror-cnewerfilename as time reference-nogroupNo group corresponds to file's numeric group ID.-nouserNo user corresponds to file's numeric user ID.-typeSupported. POSIX specifiesb,c,d,l,p,fands. GNU find also supportsD, representing a Door, where the OS provides these.
And can perform some action on the resulting search
-
-delete -
-ls -
-print -
-quitexit immediatly without doing anything else -
-execexecute the command without asking. it accepts an array of params -
-okLike-execbut ask the user first. If the user agrees, run the command. -
xargscommand take the input and use it as param for the specified command -
--nullor-0Input items are terminated by a null character instead of by whitespace; the quotes and backslash are not special (every character is taken literally). -
touchUpdate the access and modification times of each file to the current time. A file that does not exist is created empty, unless -c is supplied. -
-cdo not create anything -
statfilename or dirname or filesystem display properties
gzipfilename compress and replace-dis the same ofunzipgunzipfilename uncompress and replace-lFor each compressed file list compressed size, uncompressed size, ratio, uncompressed_name-tCheck the compressed file integrity-rrecursively-#(0-9),--fast--bestvelocity VS more compressionbzipThe same ofgzipbut using a different algorithmtarMakes a single file out of multiple files or extract from an archive. Example:tar -zxvf data.tar.gz -C location-ccreate-xextract-rappend to the end of an archive-tlist the content-fspecify the archive name-zUncompress the resulting archive with gzip command.-CChange directory to the specified locationzipjoin and compress Filesunziplocation filenamersync [OPTION] SOURCE [DEST]-acreate an unique archive-rrecursive-uskip files that are newer on the receiver-tpreserve times-ppreserve permissions-gpreserve group-opreserve owner (super-user only)-nperform a trial run with no changes made--deletedelete files which no loger exists on source--excluderegexp exclude matches from syncronization
grep means global regular expression print
-iignore case-vinvert match (aka exclude)-ccount the number of matches-lprint the name of the file containing the match instead of the match itself-Lfilenames that not match-nprint the line number where the match occurr-hsuppress filenames in the output^string starting with$string ending with
[chars]Specified chars[^chars]Exclude specified chars[start-end]likea-kor0-9[:alnum:]a-Zand0-9[:word:]Alphanumeric and_[:alpha:]a-Z[:blank:]Spaces and tabs[:cntrl:]Ascii chars from 0 to 127[:digit:]0-9[:graph:]Any visible char[:lower:]Lowercase letters[:punct:]Punctuaction chars[:print:]graphrange and space[:upper:]Uppercase chars[:xdigit:]Chars used in exadecimal numbers
?More than 1+at least 1{n,m}at least n to maximum m
catconcatenate-Adisplay non printing chars too-ndisplay line numbers-ssuppress multiple blank linessortsort lines. Is possible specify an offset to a column. Examplesort -k 3-7means sort by the seventh char of the third field-bignore leading blanks-fignore case-mmerge-nnumeric sort-ooutput to a file-rreverse-tspecify column separatoruniqReport or omit repeated lines. With no options, matching lines are merged to the first occurrence.-cprefix lines by the number of occurrences-donly print duplicate lines, one for each group-fNumber avoid comparing the first N fields-iignore case-sNumber avoid comparing the first N characterscutremove sections from file. Examplecut -d ':' -f filename-cselect only these characters-ddelimiter Use specified delimiter instead of TAB for field delimiter. It sould go between'-ffield list select only these fields--complementreverse extractionpasteCopy content from origin to destinationjoinJoin lines of two files on a common field.commCompare 2 sorted files. With no options, produce three-column output. Column one contains lines unique to FILE1, column two contains lines unique to FILE2, and column three contains lines common to both files. Files must be sorted. Examplecomm <(sort firstfile) <(sort secondfile)-1Suppress column 1 (lines unique to FILE1)-2Suppress column 2 (lines unique to FILE2)-3Suppress column 3 (lines that appear in both files)--check-orderCheck that the input is correctly sorted, even if all input lines are pairablediffCompare 2 sorted files showing differences-cShow context (display the first file before and after the second one)-uCompact difference (git diff style). Without, equal lines are grouped-aTreat all as text-rRecursively compare any subdirectories foundpatchreceives a file containingdiffoutput and apply those difference to a given target.trConvert input changing a set of chars with another one-sreplace each input sequence of a repeated character that is listed in SET1 with a single occurrence of that charactersedStream EditaspellCheck spelling interactively and replace errors,--dont-backupto avoid the creation of a.bakfile as backup--add-html-check=<list>,--rem-html-check=<list>Add or remove a list of HTML attributes to always check.--add-html-skip=<list>,--rem-html-skip=<list>Add or remove a list of HTML attributes to always skip while spell checking
nlnumebr lines of files-bstyle use style for numbering body lines. Styles can be:-aAll-tNon blank-nNone-pNumber only lines matching regexp-fNumber footer-hNumber header-inumber Step increment-nNumber format-lnLeft justified-rnRight justified-rzRight justified with leading zeros-pDo not reset page number-sAdd a string after the number-vFirst line number on each logical page-wnumber Use the given number for line numbersfoldBreak lines at specified width-wSpecify width (default is 80)-sRespect words spacesfmtText formatterpriPaginate for printingprintfPrint a string following the specified format%das decimal%fas float%ointeger as octal%sas string%xas hexadecimal%yas hexadecimal in upcase%%print a single%
groffand family are a group of text editors as LATEX
Every script must start with #!/bin/bash
Every script must have read and execute permission
Is a good practice to use the long form for commands in scripts
variable=value must be written without spaces around the =.
$variable echoes the variable value.
Variables can't start start with numbers, spaces and puntuation signs are not allowed.
declare -r UPPERCASED_NAME=VALUE creates a constant.
{enclose variable name} to avoid confusion in case of composed names.
function name {code} is a funcion declaration. Function are called by name and they must be declared before their call.
Local variabled inside a function are declared with LOCAL.
A script executed with the -x flag will output all the executed lines.
set -x (and set +x) can be used to trace only a section of the script
TIME command returns the amount of time spent executing the given command.
{} and () can be used to group a set of commands.
< () sends the output of the group to its parent.
trap [commands] [signals] Creates a listener to the system signals to catch them (for example keyboard abort sequences) and execute the specified command. Example trap "echo 'killing signal'" SIGINT SIGTERM.
sleepseconds stops the execution for the amount of given seconds
waitPID Waits for a process to finish it execution.
IF [$var=value];THEN
ELSIF
ELSE
FI
When a command executes, it returns 0 if it success or any other value up to 255 if it fails.
The exit command return the execution status
To execute an expression, can be used the command test or the more powerful [[ expression ]]. For integers the command is (( expression )).
Parenthesis can be used to group expression but they must be escaped.
-nstring length > 0-zstring length = 0==equal!=not equal<or>given 2 strings, check if the first string orders before (or after) the second one
eqequalnenot equalleless than or equalltless thangegreater than or equalgtgreater
Logical operators can be used between commands too.
-afor string is written as[[&&]]and for integers((&&)). It means and.-ofor string is written as[[||]]and for integers((||)). It means or.!for string is written as[[!]]and for integers((!)). It means not.
read varname (withour $)
read varname1, varname2, varname3, varname4 ...
If less values are provided, the rest will be set as empty string. Space is used to separate input assignments. The default receiver is the variable REPLY.
The read command can't be piped because pipes create subshells, each with its own REPLY variable.
The read command supprts the following options:
-aassign input to an array-ddelimiter declare a string delimiter which indicates the end of the input. (the default is the new line char)-ethe input can be edited before submitting-nnumber read only X chars-pdisplay a prompt-vraw mode. it means that\is not an escape char but is traten as simple text-ssilent mode-tseconds timeout-uread from file
The IFS (internal field separator) command can be used to change the separator between columns (which by default is space). Example IFS=":"
The commands << and <<< stay for here document and here string, everything follows these commands is considered all input until read delimiter is found, no matter what it contains or how large it could be.
$0...$9 by default, ${10}... from numbers with more than one digit.
WHILE [expression]; DO
code
DONE
UNTIL [expression]; DO
code
DONE
They can be used to read files too.
WHILE [expression]; DO
code
DONE < file.txt
CASE input IN
option1)
;;
option....)
;;
ESAC
;; means _break. The option) can be a values or a regexp or a set (like [:alpha:])
FOR var IN [words]; DO
code
DONE
FOR ((i=0;i<5;i=i+1));DO
code
DONE
variable=valueAssignmentlet var2=var1 operationSet var2 with the result of the operation over var1.echo $variableEchoes the variable value$variableand${variable:+default}Execute the variable values as command, if it is null does nothing${variable:-default}Execute the variable values as command, if it is null execute the default value as command{$variable:=default}Execute the variable values as command, if it is null set the variable to the default value and executes it.{$variable:?default}Execute the variable values as command, if it is null return the default value as error messageecho ${!prefix*}return a list of variables beginning with the give prefix.
${#string}String length${string:position:length}Extracts substring -${string#pattern}Removes the leading shortest match from string -${string##pattern}Removes the leading largest match from string -${string%pattern}Removes the starting shortest match from string -${string%%pattern}Removes the starting largest match from string -${value_to_find/string/replacing_value}replace value to find with replacing value. The search accepts://global replace/#replace at the beginning/%replace at the end
Numbers are in decimal base by default. Numbers beginning with 0 are considered octals, numbers beginning with 0x are considered hexadecimals.
Assignments are the common ones: =, +=, -=, *=, /=, %=, ++, --
bc Is the bash decimal calculator. It could be used with the here doc notation. Example: bc -l <<< '10/3', without -l the output is rounded to the nearest integer. Alternatively, scale=number can be used to specify the number of decimals: bc <<< 'scale=2; 10/3'
There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Arrays are zero-based: the first element is indexed with the number 0.Return to top
declare -a ARRAYNAMEInstantiate an array.ARRAY[index]=valueAssign the value to the specified index.*and@Mean all the keys of the array.#ARRAYReturn the array length#array[@]Returns all the keys of the given array#array[key]Return the value of the given key+=Push a new value into the arrayunsetdeletes the array ot the element at the given key