I have written a simple script to analyse BED files (a text file format used to store genomic regions as coordinates and associated annotations. The data are presented in the form of columns separated by spaces or tabs.) and in one of my arguments I have used awk. The problem is that my second variable of my script $2 matches with the second column of the file using awk.

Here my script (the problem is in the last elif)

#/bin/bash -e

# This script provides handly funtions to analyse bed files.

function show_usage (){
    printf "Usage: $0 [options [parameters]]\n"
    printf "\n"
    printf "Options:\n"
    printf " -g|--genes, Print genes avoiding repetition\n"
    printf " -cg|--count_genes, Print the number of different genes found in the file\n"
    printf " -cl|--count_lines,Count the number of liles\n"
    printf " -chr|--count_chromosomes, Print chromosomes avoiding repetition\n"

 return 0

if [[ "$1" == "--genes" ]] || [[ "$1" == "-g" ]];then
    echo gene
    # shows all genes
    cat $2 | cut -f4 | cut -d "_" -f1 | sort -u

 elif [[ "$1" == "--count_genes" ]] || [[ "$1" == "-cg" ]]; then
    echo count genes
    # Count genes
    cat $2 | cut -f4 | cut -d "_" -f1 | sort -u| wc -l

 elif [[ "$1" == "count_lines" ]] || [[ "$1" == "-cl" ]]; then
    echo Number of lines:
    # Count the number of liles
    cat $2 | cut -f4 | cut -d "_" -f1 | sort -u| wc -l

elif [[ "$1" == "count_chromosomes" ]] || [[ "$1" == "-chr" ]]; then
    echo Number of chromosomes
    # The chromosomes of this file are:
    cat $2 | cut -f1 | sort -u | sort -g

 elif [[ "$1" == "Count Total Length Of Regions" ]] || [[ "$1" == "-p" ]]; then
    echo Count Total Length Of Regions
    # The Count Total Length Of Regions:
    cat "$2" | awk -F"\t" "BEGIN{SUM=0}{ SUM+=$3-$2 }END{print SUM}"

    echo Incorrect input provided


cat "$2" | awk -F"\t" "BEGIN{SUM=0}{ SUM+=$3-$2 }END{print SUM}"

The first $2 in the previous line refers the second variable of my script( the file input) . The second $2 refers the second column of the file input.

When I faced this I thought that this must be a very typical problem and that awk should have an alternative way for selecting fields. But I have not found any way to avoid this problems.

Do I have to choose another command to avoid this issue?

  • you should copy/paste your script into shellcheck.net and fix the issues it tells you about as it might tell you how to fix the problem you're asking about and it'll certainly tell you about other problems that presumably haven't bit you yet.
    – Ed Morton
    Commented Nov 11, 2020 at 0:05

1 Answer 1


The problem here is that the shell is expanding $2 and $3; to avoid that, use single quotes:

cat "$2" | awk -F"\t" 'BEGIN{SUM=0}{ SUM+=$3-$2 }END{print SUM}'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .