1

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?

user710818
  • 23,228
  • 58
  • 149
  • 207

2 Answers2

3

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))
Mat
  • 202,337
  • 40
  • 393
  • 406
1

If this is pure bourne shell, instead of:

column=1+1

Try this:

column=`expr 1+1`

If it's bash, it should be:

column=$[1+1]

See here: http://linuxreviews.org/beginner/bash_GNU_Bourne-Again_SHell_Reference/#toc12

Jonathan M
  • 17,145
  • 9
  • 58
  • 91