3

I need to substitute a portion of an awk command in a script with different cases, from this:

CONTAINER=$1

RESULTS=$(ssh -o LogLevel=QUIET -t -i ~/key.pem user@server sudo docker stats --no-stream $CONTAINER | awk '{if (NR!=1) {print substr($2, 1, length($2)-1)}}')

to this:

#!/bin/bash

CONTAINER=$1
TYPE=$2

case "${TYPE}" in   
    cpu)
        AWK="'{if (NR!=1) {print substr($2, 1, length($2)-1)}}'"
    ;;   
esac

RESULTS=$(ssh -o LogLevel=QUIET -t -i ~/key.pem user@server sudo docker stats --no-stream $CONTAINER | awk $AWK)

But I always get a syntax error.

2
  • Does initial expression work good? Aug 23, 2016 at 10:01
  • You need to escape the $2 since it will be interpreted by the shell before awk.
    – user14755
    Aug 23, 2016 at 10:02

1 Answer 1

8

In a variable declaration, anything (other than parameter/command/arithmetic expansion) inside " is treated literally, so when you do:

var="'foobar'"

$var will be expanded to 'foobar', not foobar.

So you need:

AWK='{if (NR!=1) {print substr($2, 1, length($2)-1)}}'

as you don't need any pre-expansion by shell, better to use single quotes to stay on the safer side. If you use double quotes, then e.g. $2 will be expanded beforehand by the shell as parameter expansion, this is true for any other tokens that are special to shell.

And don't forget to quote $AWK when you use it to disable the split+glob operator:

… | awk "$AWK"
1
  • OK thanks, my problem was the "" to $AWK, thanks!
    – Steph
    Aug 23, 2016 at 10:27

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.