Search code examples
bashdockerawkpipefilemaker

Piped awk command failing when passed as command to Docker when using docker exec


I'm trying to build a bash shell script to help me monitor the state of a backup schedule in FileMaker Server.

If I run the following bash command in the container shell it works fine

fmsadmin  list schedules -u username -p password'

It returns

result of command showing all schedules

I get the same result when I pass the following command into the container from my user shell.

sudo docker exec -it ebf3769c5611 sh -c "fmsadmin  list schedules -u username -p password"

The problem is that when I add a piped awk command (shown below) from my user shell it gets the same result instead of just returning column 2, which it does when I run the same command in the container shell.

sudo docker exec -it ebf3769c5611 sh -c "fmsadmin  list schedules  -u username -p password | awk '{print $2; }'"

I've tried escaping the single quotes, but that just gives me an error

awk: 1: unexpected character '''
awk: line 2: missing } near end of file
sh: 1: }': not found

If I pipe a different command instead of awk (like listing files instead of schedules), it works as expected. There's something wrong in the awk command. Something in the piped command appears to need special treament when passed as a command to a docker container.

Can anyone see why it's failing?

Thanks in advance!


Solution

  • The problem is the $2. Your shell is expanding that variable to the empty string, preventing the inner awk from seeing it. To fix it, escape the dollar sign: sudo docker exec -it ebf3769c5611 sh -c "fmsadmin list schedules -u username -p password | awk '{print \$2; }'"

    Alternatively, you can use the awk on your host system instead of in the container, and then you won't need to escape anything, like this: sudo docker exec -it ebf3769c5611 sh -c "fmsadmin list schedules -u username -p password" | awk '{print $2; }'

    And for the record, this doesn't really have anything to do with Docker. Here's a minimal example of the problem and solution:

    $ echo one two three | awk '{print $2; }'
    two
    $ sh -c "echo one two three | awk '{print $2; }'"
    one two three
    $ sh -c "echo one two three | awk '{print \$2; }'"
    two
    $