<<

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