Search code examples
awkarithmetic-expressions

Why awk arithmetic doesn't work?


I have simple script:

#!/bin/sh
#NOTE - this script does not work!
#column=${1:-1}
column=1+1
awk '{print $'$column'}'

But when run

ls -la | ~/test/Column.sh

I receive always

1
1
1
1

What the problem?


Solution

  • Your script is equivalent to:

    awk '{print $1+1}'
    

    Awk tries to add one to the first column of the output of ls -al in your example, which is the file type and mode bits. That's not a number, so it gets converted to 0. Add one to zero, and you get your output.
    See here:

    Strings that can't be interpreted as valid numbers convert to zero.

    If you want the shell to calculate the number, try:

    column=$(expr 1 + 1)
    

    or even

    column=$((1 + 1))