Avoiding unnecessary commands in bash….

Some alternative bash things…. ( avoiding unneecessary use of cat / awk / grep …. )

Sometimes I try and avoid spawning an additional process just to get a specific field out of a list.

So, unnecessary use of awk

echo $line | awk '{print $2}'

Instead get bash to convert it to an array (based on IFS) and then output the field …

VAR=( $line )
echo ${VAR[2]}

Unnecessary use of grep

If needing to do a regexp match, and check with a substring is in a string, you could use :

if [[ $var =~ "pattern" ]]; then    
    echo "$var matches pattern..."
fi

Unnecessary use of cat

for line in $(cat /path/to/filename)
do
    echo $line ....
done

You could do :

while read line
do   
    echo $line ....
done < /path/to/filename

Leave a Reply

Your email address will not be published. Required fields are marked *