Home : unix

bash


Feeding command output to a while loop without using pipes

From a file:
while read line
do
 echo $line
done <FILE
From a command output
ls -1d *|while read line
do
 echo $line
done

Command-line processing

Arguments

$* - all the command arguments

$# - number of arguments (excludes the command itself)

${@:2} - arguments 2 onwards. E.g. interesting=${@:2}

Printing help

function print_help {
cat <<EOF                                                                       
$0 - accounts processing                                                        
-d download, decode and store values                                            
-h this help                                                                    
-m prep, create accounts, enyafi                                                
EOF                                                                             
}

Getopts

while getopts "a:h" opt
do
    case $opt in
        a) echo "$OPTARG" >>$FILE ;; # OPTARG in quotes to preserve spaces
        h) print_help ;;
        *) echo Unknown option ; print_help ;;
    esac
done


If

One-line statements:
   if [ "$QUIET" != "-q" ]; then echo ; echo $cmd ; fi

Inline here documents

<<< - inline here documents. E.g.
bc <<< "2 * 3"
6

Redirect as pseudo-file

Example: comm takes two file names as arguments. You can treat outputs from other commands as file arguments to comm using a structure like:
comm -12 <(sort names1) <(sort names2)

Random numbers

Generate a random number: echo $RANDOM
Generate a number between 0 and 9 inclusive: echo $((RANDOM%10))
Generate a number between 100 and 109 inclusive: echo $((RANDOM%10+100))
xlink

Links to other sites

  • Working with Stdin and Stdout - explains many nuances of stdin, stdout and stderr, and how to determine if a script is input or output is a pipe or file, or via the keyboard and the screen
    Author:  Mark Carter
    Created: 14-May-2011
    Updated: 06-May-2013