Domanda

Ho una semplice sceneggiatura:

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

Ma quando corri

ls -la | ~/test/Column.sh

Ricevo sempre

1
1
1
1

Qual è il problema?

È stato utile?

Soluzione

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))

Altri suggerimenti

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top