Why awk arithmetic doesn't work?
-
29-10-2019 - |
Question
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))
OTHER TIPS
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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow