I have this loop in the shell script, but it seems I don't fully understand what it does:

especially gawk -v

for ((k=$1; $k<3 + 3 ; k=$k + $3))
echo $k | gawk -v s=4 '{print $1*s}'

Assume the arguments we have are 2 10 4

  • 2
    I'd be happy to answer none school work questions. Could you elaborate on in what context this is used and how it fits into a larger picture? You specify three arguments - but only $1 and $3 is used.. – Claus Andersen Dec 11 '18 at 15:27
  • @ClausAndersen gawk -v means that we are assigning the valuse of s to 4 but how about the {print $1*s} – fatima Dec 11 '18 at 15:50
  • This is not a question, just a statement. – ctrl-alt-delor Dec 11 '18 at 15:56
  • What shell is it for? – ctrl-alt-delor Dec 11 '18 at 15:57
  • 1
    Did you run the script and see what it does? – RudiC Dec 11 '18 at 16:32

I can only imagine this is a homework question.

Let's break this down. Firstly you have a loop which starts at $1 and increments by $3 and will stop at 6. So if you pass in 2 10 4, then the loop will start at 2, and increment by 4. It will immediately stop because 2 + 4 = 6.

So the following just print's 2. With the arguments 2 10 4.

for ((k=$1; $k<3 + 3 ; k=$k + $3))
    echo $k

Each time round the loop, you process the output using gawk -v s=4 '{print $1*s}'. This is a very small "awk" program. It sets a variable s=4. Then prints $1*s (ie: it calculates 2 * 4 and just prints 8.


The awk bit just prints the current value of $k (this is $1 in the awk code as it is read from the input) times 4 (this is the value of the awk variable s, as set on the command line).

It would be shorter to do

printf '%d\n' "$(( 4*k ))"

The loop goes from whatever the first argument is to 5 in steps of the third argument. The second argument does not make any difference.

Therefore, the whole thing could be simplified down to

seq "$(( 4*$1 ))" "$(( 4*$3 ))" 20

The three arguments to GNU seq are "start, increment, and end". This is for the output, and the output will always be four times the current value of the loop variable. The loop starts at $1, so the output starts at four times that. The loop increments by $3, so we increment by four times that. The loop ends with $k at a maximum of 5 (one less than 3+3), so the output ends at 4*5.

Or, if you want to do that seq call as a bash loop instead:

for (( k = 4*$1; k <= 20; k += 4*$3 )); do
    printf '%d\n' "$k"

And, as you see,

for (( k = $1; k <= 5; k += $3 )); do
    printf '%d\n' "$(( 4*k ))"

is not far from that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.