$PATH – list of paths to executable commands && and, || or; binary: ~, &, |; <<, >> shifts; assignment: = *= /= %= += -= <>= &= – omit repeated lines, -d show only duplicates Bourne-AgainBourne-Again SHell SHell and and Linux CLI CLI $IFS – Internal field separator. List of chars, that delimiter words ^= |= >>= <<=; relations: < <= > >= -e 'script' – stream editor, script y/ABC/abc/ replaces A, B, C from input, usually space, tabulator $' t' and new line $' n'. n – factorize into primes for a, b, c; s/regexp/substitution/ © 2013 Martin Bruchanov, [email protected] • • Floating point operations: "scale=10; 22/7" | bc a b – replace char a for b •4. Script line parameters • Set interpreter: #!/bin/bash Remarks: # this is comment tr '[a-z]' '[A-Z]' < file.txt – change lowercase to uppercase $0, ${0} – name of script \ \ •8. Screen output 푛 '/pattern/ {action }' – process lines containing pattern Interactive control $1 to $9, ${1} to ${255} – positional command line parameters • • echo "text" – print text, echo * print all files in current dir -d delimiter -f field – print column(s) Action set -o set -o emacs $# – number of command line parameters (argc) echo -e "text" – interpret escape-sequences (\t tab., a beep, \f • • file1 file2 – compare files and print first difference vi-command mode (C) Esc — $* – all parameters, "$*" = "$1 $2 $3 " new page, \n new line), -n, \c suppressing \n, \xHH hex-byte, nnn • Previous/next command in Ctrl+p / Ctrl+n • • , diff3, sdiff, vimdiff – compare whole files jC / kC $@ – expand all parameters, "$@" = "$1" "$2" "$3" oct. byte, u03B1 „ “ (U+03B1) in UTF-8 • PageUp / PageDown • • \ if=in of=out bs=k count=n – read blocks of bytes $_ – last parameter of previous command stty – change and print terminal line settings • Automatic fill of file name Esc EscC Tab • … \ – show printable strings in binary file shift – rename arguments, $2 to $1, $3 to $2, etc.; lower counter $# – print name of terminal connected to stdout • List of all matches Esc = Tab Tab • … \ 훼 file file – merge lines of files command – read stdin and put it as parameters of command format values – format output • 1 2 푛 푘 Horizontal move in command line hC / lC Ctrl+b / Ctrl+f, / • • rev – reverse every line printf -v variable form. val. – form. output into variable • Jump to line begin/end ^C / $C Ctrl+a / Ctrl+e •4.1. Read options from command line • Backward/forward search in % [flags][width][.precision][length]specifier •13. Search / / ? Ctrl+r / Ctrl+s while "a:b" opt; do case $opt in history C C ← → • • a) echo a = $OPTARG ;; Specifier: %u, %d, %i decimal; %E, %f float, %x, %X hex; %o octal, %s string, %% char % • , – find path to command Delete word to the end/begin dw / db Esc d / Esc h • C C b) echo b ;; Width: prints least chars, spaces from right, print at least chars, – -i ignore case, -n print line number, -v display everything Delete text from cursor to the line − d$ / d^ Ctrl+k / Ctrl+u zeros from left, * width specified in preceding parameter except pattern, -E extended regexp end/begin C C ?) echo "Unknown parameter!" ;; − • Precision: min. number of digits, digits after decimal point, number of printed file – find file esac; done − 푛 푛 0푛 푛 • 1.1. Command line history shift $(($OPTIND - 1)); echo "Last: $1" chars, * number of chars given by preceding parameter path -name 'file*' – search for file* \ Flags: - left-justify, + prints number with sign +/- find path -exec grep text -H {} ; – find file containing text history, -l – display numbered history of commands − • printf "%d" \'A – display ASCII code of char “A” (65) !n – run command number n 5. Control expressions •14. Users and permissions – run last command beginning by p printf \\$(printf'%03o' 65) – print char given by ASCII code !p − • , am i – tell who I am :)\ • – repeat last entered command (commands), $(commands), `commands`, {commands;} – run in subshell action – terminal dependent action !! • , who, users, finger – list connected users • – expand n-th parameter of last command $(program), `program` – output of program replaces command reset, tput sgr0, tset – reset terminal, cancel attributes !!:n • last / lastb – history successful / unsuccessful logins • – expand the last parameter of last command , [] – condition evaluation: , tput clear – clear screen • !$ • • logout, Ctrl+d – shell • – run defined wit last command numeric comparison: a -eq b , a -ge b , a -gt • fc $EDITOR • •9. Process management login – change user to login • – open editor with commands from to b , a -le b , a -lt b • fc -e vim z k vim • • command & – run command in background – run command as other user • – substitute old with new in last command file system: -d file is directory, -f file exists and is not dir., • ^old^new − …푎 = 푏 …푎 ≥ 푏 prog && prog – run prog , if prog ends with success id login, groups login – show user details • – use output of last command as input -r file exists and is readable, -w file exists and is writable, -s 1 2 2 1 • program `!!` …푎 > 푏 …푎 ≤ 푏 …푎 < 푏 prog || prog – rub prog , if prog ends with error useradd, userdel, usermod – create, delete, edit user • 푧 푘 file is non-zero size, -a file exists • 1 2 2 1 • 1.2. and manuals − Ctrl+z – stop process (SIGSTOP) groupadd, groupdel, groupmod – create, delete, edit group • logical: -a and, -o or, ! negation • • -a command – information about command bg / fg – run last stopped process in background/foreground – change password • [[ ]] – comparison of strings, equal =, non-equal !=, -z string is • • help command – brief help on bash command jobs – list processes running in background pwck – check integrity of /etc/passwd zero sized, -n string is non-zero sized, <, > lexical comparison • • man command, command – detailed help − exec command – shell is replaced by command user:group file – change owner, -R recursion • [ condition ] && [ condition ] • • man -k key, key, whatis key – find command • – returns 0 value – wait for end of background tasks group file – change group of file • true • • false – returns 1 value CPU, memory, system utilization permissions file – change permissions in octal of user, group, •2. Debugging • • • break – terminates executed cycle -xau – list processes and users, ps -xaf, listing others; 444=-r--r--r--, 700=-rwx------, 550=-r-xr-x--- •Run a script as: bash option script and its parameters • • • continue – starts new iteration of cycle process, pidof process – get PID by name of process runuser login -c "command" – run command as user bash -x – print commands before execution • • • eval parameters – executes parameters as command -n p command – priority 20 (max.) to 19 (min.) bash -u – stop with error if undefined variable is used • • 15. System utilities exit value – terminates script with return value renice -n p -p pid – change priority of running process bash -v – print script lines before execution • • • -a – name and version of • . script, source script – reads and interprets another script -s k n – send signal to proces id. , 0, 1 SIGHUP; 2 SIGINT bash -n – do not execute commands • • 푝 − – how long the system has been running • : argument – just expand argument or do redirect Ctrl+c; 3 SIGQUIT; 9 SIGKILL; 15 SIGTERM; 24 SIGSTOP • • – identify processes using files or sockets •3. Variables, arrays and hashes name='commands' – expand name to commands trap 'command' signals – run command when signal received • • • 푘 푛 – list open files • NAME=10 – set value to variable $NAME, ${NAME} unalias name – cancel alias name – send signals to process by name • • – flush file system buffers export NAME=10, typedef -x NAME – set as if [ condition ]; then commands; command & – command will continue after logout • • • dir command – run command with special root directory D=$(date); D=`date` – variable contains output of command date elif [ condition ]; then commands; command – print time of process execution • • • • strace,ltrace program – show used system/library calls , printenv – list all environment variables else commands; fi times – print user and system time utilization in current shell • • • • ldd binary – show library dependencies set – list env. variables, can set bash options and flags shopt for variable in arguments; do commands; done watch -n s command – every s seconds run command • • • unset name – destroy variable of function {a..z} – expands to a b c z •15.1. Disk partitions • •10. Time and process planning typeset, declare – set type of variable {i..n..s} – sequence from i to n with step s • – display free space • • • date – print date, date --date=@unix_time readonly variable – set as read only \"{a,b,c}\" – expands to "a" "b" "c" – print mounted partitions • − … date +"%Y%m%d %H:%M:%S %Z" – format to 20130610 13:39:02 CEST local variable – set local variable inside function {1,2}{a,b} – expands to 1a 1b 2a 2b mount -o remount -r -n / – change mount read only • − – display calendar • ${!var}, eval $$var – indirect reference start step end – number sequence • mount -o remount -w -n / – change mount writeable • − crontab -e – edit crontab, -l list, format min hour date month day • ${parameter-word} – if parameter has value, then it is used, else word for((i=1; i<10; i++)); do commands; done • mount -t iso9660 cdrom.iso /mnt/dir -o loop – mount image • − command, * * * * * command run every minute, 1 * * * * command • is used while returns true; do commands; done • mount -t cifs \\\\server\\ftp/mnt/adr -o user=a,passwd=b • \ − 1st min of every hour • ${parameter=word} – if parameter has no value assing word. Doesn’t until [ test returns true ]; do commands; done • umount partition – unmount partition • • at, batch, atq, atrm – queue, examine or delete jobs for later • work with $1, $2, ets. case $prom in value ) commands ;; fdisk -l – list disk devices and partitions • execution • ${parameter:-word} – works with $1, $2, etc. value ) commands ;; *) implicit. commands ;; blkid – display attributes of block devices • • 11. File operations • ${parameter?word} – if parameter has value, use it; if no display word esac 1 • tune2fs – change ext2/3/4 filesystem parameters • File name wildchars: ? a char; * zero or chars; [set] one or more • and exit script. Function2 definition: function name () {commands;} .ext2, mkfs.ext3 – build file-system • • ${parameter+word} – if parameter has value, use word, else use empty return value – return value of the function given chars, interval [0-9] [a-z], [A-Z]; [!set], [^set] none of chars. hdparm – set/read parameters of SATA/IDE devices • – list directory, ls -la, vdir all files with info • string declare -f function – print function declaration 15.2. System utilization array=(a b c); echo ${array[1]} – print ‚b‘ • tree – display hierarchy tree of directories • • •6. Redirections file file – determine file by its magic number • ulimit -l – print limits of system resources array+=(d e f) – append new item/array at the end • • 0 stdin/input, 1 stdout/output, 2 stderr/error output lsattr, – list and change file attributes for ext2,3 free, vmstat – display usage of physical, virt. memory ${array[*]}, ${array[@]} – all items of array • • > file – redirection, create new file or truncate it to zero size – define permission mask for new file lspci, lsusb – list PCI, USB devices ${#array[*]}, ${#array[@]} – number of array items • • • >> file – append new data at the end of file (-P) – logical (physical) path to current directory dmesg – display messages from kernel declare -A – create associative array (from version) • • • • command <<