2011-06-22

LINUX BASH

Set


set -xDisplay commands and their arguments as they are executed. +x turn off
set -vDisplay shell input lines as they are read. +v turn off





Params


$?error code
$#a number of params
$@list params
$*list params
$0script name
$1param nr 1
$$process ID





Keybindings


S-M-$complete variable
S-<first command in history
C-pprevious command in history
C-nnext command in history
S->last command in history
C-ejump to EOL
C-ajump to BOL
M-fjump forward a word
M-bjump back a world
C-udelete from BOL to cursor
C-kdelete from cursor to EOL
M-ddelete word forward from cursor
C-wdelete word backward from cursor




Variable manipulation


  • (command1; command2;…) #command inside brackeds are lauched in subshell with new process id(childs)
    subshell variables are recognized in subshell only
  • ${var}
  • ${#var} #a number of variable var characters


commandoutputdesc
export var=(el1 el2 el3); echo ${var[1]}val2the second element var variable, which is a list
export var=(el1 el2 el3); echo ${#var[1]}4a number of chars in the second element
export var=(el1 el2 el3); echo ${#var[@]}3list size
export var=12345; echo ${var:-text}if var was set the output is var value, if not the output is text, var is not change
export var=12345; echo ${var:=text}if var was set the output is var value, if not the output is text, var is changed to text
export var=12345; echo ${var:?text}if var was set the output is var value, if not the output is text to the error output
export var=12345; echo ${var:+text}if var was set the output is text, var is not change
export var=12345; echo ${var:1:3}234get second element (first is 0) and next 3
export var=12345; echo ${var#12}345remove elements based on schema 12 from the begining
export var=12345; echo ${var%45}123remove elements based on schema 45 from the end
export var=12345; echo ${var/34/ab}12ab5substitute elements by pattern 34 to ab anywhere
export var=12345; echo ${var/#12/ab}ab123substitute elements by pattern 12 to ab from the beggining
export var=12345; echo ${var/%45/ab}123absubstitute elements by pattern 45 to ab from the end





Array


  • Array=(el01 el02 el03)
  • element at the table is matched by [] symbol and by ${Array[0]}
  • iteration: for i in ${Array[@]};do echo $i; done




Buildin variables and commands


zmiennadesc
BASH_SUBSHELLsubshell nr
SECONDSamount of time running script
FUNCNAMEfuction name
DIRSTACKcurrent dir
LINENOcurrend row
:true
PWDcurrent dir
CDPATHcd command path
TMOUTlogout after [sec] of inactivity





Debug


bash -n [script]set -ncheck without run
bash -x [script]set -xdebug




Range variable


  • function inherits variables from script
  • script do not inherit variable from function
  • script inherit variable from for loop




Function


  • {} #anonymous function, variables from script
  • in {} there is the block of code which output might be redirect to file {} > output.file,
    block of code from {} is not placed in subshell like for ()




Test




[[


  • less suprises, safer to use, but it is not portable, not POSIX only bash,
    regexp matching, it is a keyword, not a program
  • string comparision:

    <, >, =, ==, !=
  • integer comparison:

    -lt, -le, -eq, -ge, -gt, -ne
  • conditional evaluation:
    &&, ||
  • expression grouping:

    (…)



[


  • right side must be quote ex. if [ -z "$variable ], is sysnonym for test but
    requires a final ], it is a program /usr/bin/[
  • string comparision:

    \<, \>, =, !=
  • integer comparison:

    -lt, -le, -eq, -ge, -gt, -ne




files


-f filetrue if file exists and is a regular file
-e filetrue if file exists
-d filetrue if file exists and is a directory





strings


-z stringtrue if the length of string is zero
-n stringtrue if the length of string is non-zero





using


  • [ c1 ] ||/&& [ c2 ]
  • both alternatives are different ex:
    c1c2
    andOKis run
    andFAILis not run
    orOKis not run
    orFAILis run






Getopts


variabledescription
OPTINDHolds the index to the next argument to be processed. This is how getopts "remembers" its own status between invocations. Also usefull to shift the positional parameters after processing with getopts. OPTIND is initially set to 1, and needs to be re-set to 1 if you want to parse anything again with getopts
OPTARGThis variable is set to an argument for an option found by getopts, but if the option is unknown it contains the option flag.
OPTERR(Values 0 or 1) Indicates if Bash should display error messages generated by the getopts builtin. The value is initialized to 1 on every shell startup - so be sure to always set it to 0 if you don't want to see annoying messages!


  • getopts OPTSTRING VARNAME [ARGS…]
    OPTSTRINGtells getopts which options to expect and where to expect arguments (see below)
    VARNAMEtells getopts which shell-variable to use for option reporting
    ARGStells getopts to parse these optional words instead of the positional parameters


  • commands without any args - nothing happened? Right. getopts didn't see any valid or invalid options (letters preceeded by a dash),
    so it wasn't triggered.
  • commands without any flags - nothing happened? The very same case: getopts didn't see any valid or invalid options
    (letters preceeded by a dash), so it wasn't triggered.
  • invalid options don't stop the processing: If you want to stop the script, you have to do it yourself (exit in the right place)
  • multiple identical options are possible: If you want to disallow these, you have to check manually (e.g. by setting a variable or so)




OPTSTRING


  • When you want getopts to expect an argument for an option, just place a : (colon) after the proper option flag.
  • If the very first character of the option-string is a : (colon), which normally would be nonsense
    because there's no option letter preceeding it, getopts switches to the mode "silent error reporting".
    In productive scripts, this is usually what you want (handle errors yourself and don't get disturbed by annoying messages).




ARGS


  • The getopts utility parses the positional parameters of the current shell or function by default (which means it parses "$@").
    You can give your own set of arguments to the utility to parse. Whenever additional arguments are given after the VARNAME parameter,
    getopts doesn't try to parse the positional parameters, but these given words.
    A call to getopts without these additional arguments is equivalent to explicitly calling it with "$@".




Calculate


  • echo $((2+3))



Return status


  • last command at function or script determe exit status, thisis bash return value
  • exit status might be at range 0-255




Commands


evalchange string from variable to command ex. i="ls"; eval $i
sourcefrom command line run script, from script working as #include (same as dot-command)
execdo not create fork but create new shell process, go out from script
true,falsereturn 0 as exit status of error
help [bash_command]help for bash commands ex. help eval





Output




ex 1: command > /dev/null 2>&1


  1. redirect standard output /dev/stdout to /dev/null
  2. redirect standard error /dev/stderr to device point at standard output /dev/stdout, so to /dev/null

Summarize: all output is redirect to /dev/null



ex 2: command 2>&1 > /dev/null


  1. redirect error output /dev/stderr to device point at standard output /dev/stdout
  2. redirect standard ouptut /dev/stdout to /dev/null but error output /dev/stderr
    is still redirected to /dev/stdout

Summarize: /dev/stdout to /dev/null and /dev/stderror to previous /dev/stdout



Printf


  • printf "%-30s%s" "hello" $VAR




Colors in directory


  • dircolors -p ~/.dircolors
  • eval `/usr/bin/dircolors -b ~/.dircolors`
  • alias dir="dir –color"
  • alias ls="ls –color"



color symbols


descatrybut
none00
bold01
underscore04
blink05
reverse07
concealed08
font kolorbackground color
black3040
red3141
green3242
yellow3343
blue3444
magenta3545
cyan3646
white3747