© 2021 Martin Bruchanov, bruchy@gmail.com
Set interpreter: #!/bin/bash Remarks: # this is comment
| Action | set -o vi | set -o emacs |
|---|---|---|
| vi-command mode ( C) | Esc | — |
| Previous/next command in history | jC / kC | Ctrl+p / Ctrl+n PageUp / PageDown |
| Automatic fill of file name | EscEscC | Tab |
| List of all matches | Esc= | TabTab |
| Horizontal move in command line | hC / lC | Ctrl+b / Ctrl+f, ← / → |
| Jump to line begin/end | ^C / $C |
Ctrl+a / Ctrl+e |
| Backward/forward history search | /C / ?C | Ctrl+r / Ctrl+s |
| Delete word to the end/begin | dwC / dbC | Esc d / Esc h |
| Delete text from cursor to the line end/begin | d$C / d^C |
Ctrl+k / Ctrl+u |
history, fc -l – display numbered history of commands!n – run command number n!p – run last command beginning by p!! – repeat last entered command!!:n – expand n-th parameter of last command!$ – expand the last parameter of last commandfc – run defined $EDITOR wit last commandfc -e vim z k – open vim editor with commands from z to k^old^new – substitute old with new in last command!n:s/old/new/ – substitute old in command number nprogram `!!` – use output of last command as inputtype -a command – information about commandhelp command – brief help on bash commandman command, info command – detailed helpman -k key, apropos key, whatis key – find command
Run a script as: bash option script and its parameters
bash -x – print commands before executionbash -u – stop with error if undefined variable is usedbash -v – print script lines before executionbash -n – do not execute commandsNAME=10 – set value to variable $NAME, ${NAME}export NAME=10, typedef -x NAME – set as environment variableD=$(date); D=`date` – variable contains output of command dateenv, printenv – list all environment variablesset – list env. variables, can set bash options and flags shoptunset name – destroy variable of functiontypeset, declare – set type of variablereadonly variable – set as read onlylocal variable – set local variable inside function${ !var}, eval \$$var – indirect reference${parameter-word} – if parameter has value, then it is used, else word is used${parameter=word} – if parameter has no value assing word. Doesn't work with $1, $2, ets.${parameter:-word} – works with $1, $2, etc. ${parameter?word} – if parameter has value, use it; if no display word and exit script.${parameter+word} – if parameter has value, use word, else use empty stringarray=(a b c); echo ${array[1]} – print „b“array+=(d e f) – append new item/array at the end ${array[*]}, ${array[@]} – all items of array${#array[*]}, ${#array[@]} – number of array itemsdeclare -A hash – create associative array (from version)hash=([key1]=value ["other key2"]="other value") – store items${hash["other key2"]}, ${hash[other key2]} – access${hash[@]}, ${hash[*]} – all items ${!hash[@]}, ${!hash[*]} – all keysSTRING="Hello" – indexing: H0 e1 l2 l3 o4STRING+=" world!" – concatenate strings ${#string}, expr length $string – string length${string:position} – extract substring from position${string:position:length} – extract substr. of length from position${string/substring/substitution} – substitute first occurrence${string//substring/substitution} – substitute all ${string/%substring/substitution} – substitute last occurrence${string#substring} – erase shortest substring ${string##substring} – erase longest substring ~, $HOME – home directory of current user$PS1, $PS2 – primary, secundary user prompt $PWD, ~+ / $OLDPWD, ~- – actual/previous directory$RANDOM – random number generator, 0 – 32,767$? – return value of last command$$ – process id. of current process$! – process id. of last background command$PPID – process id. of parent process$- – display of bash flags $LINENO – current line number in executed script$PATH – list of paths to executable commands$IFS – Internal field separator. List of chars, that delimiter words from input, usually space, tabulator $'\t' and new line $'\n'.$0, ${0} – name of script/executable$1 to $9, ${1} to ${255} – positional command line parametersPAR=${1:?"Missing parameter"} – error when ${1} is not setPAR=${1:-default} – when ${1} is not set, use default value$# – number of command line parameters (argc)${!#} – the last command line parameter$* – expand all parameters, "$*" = "$1 $2 $3…"$@ – expand all parameters, "$@" = "$1" "$2" "$3"…$_ – last parameter of previous commandshift – rename arguments, $2 to $1, $3 to $2, etc.; lower counter $#xargs command – read stdin and put it as parameters of commandwhile getopts "a:b" opt; do case $opt in a) echo a = $OPTARG ;; b) echo b ;; \?) echo "Unknown parameter!" ;; esac; done shift $(($OPTIND - 1)); echo "Last: $1"
(commands), $(commands), `commands`, {commands;} – run in subshell$(program), `program` – output of program replaces commandtest, [ ] – condition evaluation:
a -eq b … a=b, a -ge b … a≥b, a -gt b … a>b, a -le b … a≤b, a -lt b … a<b-d file is directory, -f file exists and is not dir., -r file exists and is readable, -w file exists and is writable, -s file is non-zero size, -a file exists-a and, -o or, ! negation [[ ]] – comparison of strings, equal =, non-equal !=, -z string is zero sized, -n string is non-zero sized, <, > lexical comparison[ condition ] && [ condition ]true – returns 0 valuefalse – returns 1 valuebreak – terminates executed cyclecontinue – starts new iteration of cycleeval parameters – executes parameters as commandexit value – terminates script with return value. script, source script – reads and interprets another script: argument – just expand argument or do redirectalias name='commands' – expand name to commandsunalias name – cancel alias if [ condition ]; then commands;
elif [ condition ]; then commands;
else commands; fifor variable in arguments; do commands; done
{a..z – expands to a b c … z{i..n..s} – sequence from i to n with step s \"{a,b,c}\" – expands to "a" "b" "c"{1,2}{a,b} – expands to 1a 1b 2a 2bseq start step end – number sequencefor((i=1; i<10; i++)); do commands; donewhile returns true; do commands; doneuntil [ test returns true ]; do commands; donecase $prom in value_1) commands ;; function name () { commands; }return value – return value of the function declare -f function – print function declaration0 stdin/input, 1 stdout/output, 2 stderr/error output> file – redirection, create new file or truncate it to zero size>> file – append new data at the end of filecommand1<<<command2 – ouput from 2nd to stdin of 1stcommand < file – read stdin from filetee file – read stdin, writes to file and to stdoutcommand 2> file – redirect error messages to fileexec 1> >(tee -a log.txt) – redirect stdout also to file 2>&1 – merge stderr and stdoutexec 3<>/dev/tcp/addr/port – create descriptor for network read/writeexec 3>&- – close descriptorcommand > /dev/null 2>&1 – suppress all outputn> n>> n>&m – operation redirect for descriptors n, mmkfifo name – make a named pipe, it can be written and read as filecommand1 | command2 – pipe, connection between processescommand 2>&1 | \periods[3] – can be shortened to command |& \periods[3]${PIPESTATUS[0]}, ${PIPESTATUS[1]} – retvals before and after piperead parameters – read input line and separate it into parameters./program << EOF ./program <<-'EOF' # suppress tabulators Input1 Input1 Input2 Input2 EOF EOF
cat file.txt | (while read L; do echo "$L"; done)
let expression, expr expression, $((expression)), $((expression1, expression2)), $[expression]#number; hexa 0xABC, octal 0253, binary 2#10101011i++, ++i, i--, --i, +, -; ** power, *, /, % remainder; logical: ! neg., && and, || or; binary: ~, &, |; <<, >> shifts; assignment: = *= /= %= += -= <>= &= ^= |= >>= <<=; relations: < <= > >= factor n – factorize n into primes echo "scale=10; 22/7" | bcecho "text" – print text, echo * print all files in current dir echo -e "text" – interpret escape-sequences (\t tab., \a beep, \f new page, \n new line), -n, \c suppressing \n, \xHH hex-byte, \nnn oct. byte, \u03B1 „α“ (U+03B1) in UTF-8stty – change and print terminal line settingstty – print name of terminal connected to stdoutprintf format values – format outputprintf -v variable form. val. – form. output into variable
%u, %d, %i decimal; %E, %f float, %x, %X hex; %o octal, %s string, %% char %* width specified in preceding parameter* number of chars given by preceding parameter - left-justify, + prints number with sign +/-printf "%d" \'A – display ASCII code of char “A” (65)printf \\$(printf '%03o' 65) – print char given by ASCII codetput action – terminal dependent actionreset, tput sgr0, tset – reset terminal, cancel attributesclear, tput clear – clear screen& – run command in backgroundprog1 && prog2 – run prog2, if prog1 ends with successprog1 || prog2 – rub prog2, if prog1 ends with errorbg / fg – run last stopped process in background/foreground jobs – list processes running in backgroundexec command – shell is replaced by commandwait – wait for end of background taskstop – watch CPU, memory, system utilizationps -xau – list processes and users, ps -xaf, pstree tree listingpgrep process, pidof process – get PID by name of processnice -n p command – priority p od -20 (max.) to 19 (min.)renice -n p -p pid – change priority of running processkill -s k n – send signal k to proces id. n, 0, 1 SIGHUP; 2 SIGINT Ctrl+c; 3 SIGQUIT; 9 SIGKILL; 15 SIGTERM; 24 SIGSTOPtrap 'command' signals – run command when signal received killall name – send signals to process by namenohup command & – command will continue after logouttime command – print time of process executiontimes – print user and system time utilization in current shellwatch -n s command – every s seconds run commandtimeout N command – quit command after N secondsdate – print date, date --date=@unix_timedate +"%Y%m%d %H:%M:%S %Z" – format to 20130610 13:39:02 CESTprintf '%(%Y-%m-%dcal – display calendarcrontab -e – edit crontab, -l list, format min hour date month day command, * * * * * command run every minute, 1 * * * * command 1st min of every hourat, batch, atq, atrm – queue, examine or delete jobs for later execution
File name wildchars: ? a char; * zero or more chars;
[set] one or more given chars, interval
[0-9] [a-z], [A-Z]; [!set],
[^set] none of chars.
ls – list directory, ls -la, vdir all files with infotree – display hierarchy tree of directories file file – determine file by its magic numberlsattr, chattr – list and change file attributes for ext2,3umask – define permission mask for new filepwd (-P) – logical (physical) path to current directory cd directory – change directory, cd jump to $HOME, cd - to $OLDPWDdirs – list stack of directoriespushd directory – store directory to stackpopd – set top stack directory as actual directorycp source target – copy fileln -s source link – create a symbolic linkmkdir, rmdir – create, remove directoryrm file, rm -r -f directory, unlink – deletetouch file – create file, set actual time to existing filedu -h – display space usage of directoriesstat file – file statistics, stat --format=%s sizebasename name suffix – remove path or suffixdirname /path/to/file – print only pathrepquota – summarize quotas for a filesystemmktemp – create file with unique name in /tmp cat – concatenate files and print them to stdoutcat > file – create file, end with Ctrl+dmapfile A < file – store stdin into array $Atac – like cat, but from bottom to top linemore, less – print by pages, scrollableod, hexdump -C, xxd – print in octal, hex dumpwc – get number of lines -l, chars -n, bytes -c, words -whead/tail – print begin/end, tailf, tail -f wait for new linessplit, csplit – split file by size, contentsort – -n numerical, -r reverse, -f ignore caseuniq – omit repeated lines, -d show only duplicatessed -e 'script' – stream editor, script y/ABC/abc/ replaces A, B, C for a, b, c; s/regexp/substitution/tr a b – replace char a for btr '[a-z]' '[A-Z]' < file.txt – change lowercase to uppercaseawk '/pattern/ { action }' file – process lines containing pattern cut -d delimiter -f field – print column(s)cmp file1 file2 – compare files and print first differencediff, diff3, sdiff, vimdiff – compare whole files dd if=in of=out bs=k count=n – read n blocks of k bytesstrings – show printable strings in binary filepaste file1 file2 – merge lines of filesrev – reverse every linewhereis, which – find path to command grep – -i ignore case, -n print line number, -v display everything except pattern, -E extended regexplocate file – find filefind path -name 'file*' – search for file*find path -exec grep text -H {} \; – find file containing textwhoami, who am i – tell who I am :)w, who, users, pinky, finger – list connected userslast / lastb – history successful / unsuccessful loginslogout, Ctrl+d – exit shellsu login – change user to loginsudo – run command as other usersu - login -c 'command' – run one command as loginid login, groups login – show user detailsuseradd, userdel, usermod – create, delete, edit usergroupadd, groupdel, groupmod – create, delete, edit group passwd – change passwordpwck – check integrity of /etc/passwdchown user:group file – change owner, -R recursionchgrp group file – change group of filechmod permissions file – change permissions in octal of user, group, others; 444=-r--r--r--, 700=-rwx------, 550=-r-xr-x---runuser login -c "command" – run command as useruname -a, cat /proc/version – name and version of operating systemuptime – how long the system has been runningfuser – identify processes using files or socketslsof – list open filessync – flush file system bufferschroot dir command – run command with special root directorystrace,ltrace program – show used system/library callsldd binary – show library dependenciesdf – display free spacemount, findmnt – print mounted partitionsmount -o remount -r -n / – change mount read onlymount -o remount -w -n / – change mount writeablemount -t iso9660 cdrom.iso /mnt/dir -o loop – mount image mount -t cifs \\\\server\\ftp /mnt/adr -o user=a,passwd=bumount partition – unmount partitionfdisk -l – list disk devices and partitionsblkid – display attributes of block devicestune2fs – change ext2/3/4 filesystem parametersmkfs.ext2, mkfs.ext3 – build file-systemhdparm – set/read parameters of SATA/IDE devicesulimit -l – print limits of system resourcesfree, vmstat – display usage of physical, virt. memorylspci, lsusb – list PCI, USB devicesdmesg – display messages from kernelsysctl – configure kernel parameters at runtime dmidecode – decoder for BIOS data (DMI table)init, telinit – command init to change runlevelrunlevel, who -r – display current runlevelhostname – display computer hostnameping host – send ICMP ECHO_REQUEST dhclient eth0 – dynamically set eth0 configurationhost, nslookup host/adr – DNS querydig – get record from DNSwhois domain – finds owner of domain or network rangeethtool eth0 – change HW parameters of network interface eth0ifconfig – display network devices, device configurationifconfig eth0 add 10.0.0.1 netmask 255.255.255.0 ifconfig eth0 hw ether 01:02:03:04:05:06 – change MAC addressroute add default gw 10.0.0.138 – set network gatewayroute -n, netstat -rn – display route tablenetstat -tlnp – display processes listening on portsarp – display ARP tableiptables -L – display firewall rulestcpdump -i eth0 'tcp port 80' – display HTTP communicationtcpdump -i eth0 'not port ssh' – all communication except SSHssh user@hostname command – run command remotelymail -s "subject" address – send email to addresswget -e robots=off -r -L http://path – mirror given page