Wednesday, April 9, 2014

Bash Specialities, part 1

This post shows some more or less frequently used features in bash, which might come handy in some situations.

tee
tee redirects SDTIN to STDOUT and to a file. This can be used to store data to a file, while they are processed. Following example stores data to a $file (overwrites existing $file) and continues with processing.
  • echo <data to process> | tee $file | <continue processing>

Conditions
TRUE and FALSE can be substituted in bash with : and `let 0`. For example:
  • if :; then echo This is true; fi
  • if `let 0`; then echo Not true; else echo This is false; fi

You can cumulate several expressions with AND relation like this:
  • [ expression -a expression ]

Redirection
To redirect both STDIN and STDOUT use &>/dev/null (this doesn't work when redirecting to a file).
To empty a file use >file (will create file if it doesn't exist).
To create file, but don't overwrite it when it exists use >>file.

To handle positional input parameters $1 $2 etc. in a bash script you can do:
for PARAMETER; do
    echo -e "FOR Cycle $PARAMETER"
done
Another way to handle list of parameters in bash script:
#/bin/bash

set -- space separated list of parameters

for PARAMETER; do
    echo $PARAMETER
done

Numeral system conversions
  • echo $(( 2#101011 )) to convert binary number to decimal
  • echo $(( 8#77 )) to convert octal number to decimal
  • echo $(( 16#5E3 )) to convert hex number to decimal

Some mathematical operations
  • echo $(( 2+3 ))
  • echo $(( n++ ))
  • let "n++"
  • echo $(( n = $n + 2 ))
  • let "n += 2"

Exporting function to sub-shell
#!/bin/bash

QUEUE=('M:0:/mnt/storage')

M(){
    echo function M
}

S(){
    echo function S
}

# export functions to sub-shell, so they can be called from awk
export -f M S

for JOB in ${QUEUE[*]}; do
    echo | awk -v JOB="$JOB" '{
    gsub(":"," ",JOB)
    if ( system(JOB) == 1 )
        exit 1
    }'
done

1 comment: