0

I am observing a weird issue where when I substitute a variable(A) within another variable(B) and print variable B , the console output is messed up.

docker_command="docker ps | grep consul | awk '{print \$1}'"
container_id=$(execute_command_on_host $IP $USER_NAME $USER_PASSWD "$docker_command")
echo "container_id: $container_id"
service_command="docker exec "$container_id" consul catalog services"
echo "service_command: $service_command"

#run script

Output:

container_id: 411d55019dba
consul catalog servicesommand: docker exec 411d55019dba

The last line of the output is messed up and sort of jumbled. But the same script if I run directy using the container_id then it works

container_id="411d55019dba"
service_command="docker exec "$container_id" consul catalog services"
echo "service_command: $service_command"

#run script

Output:

service_command: docker exec 411d55019dba consul catalog services

I feel I am missing out on something very simple. Would appreciate any help

skorada
  • 431
  • 1
  • 4
  • 15
  • Use either backticks or `$()` to execute a command. Now you're asigning the strings to a variable. – Fredrik Pihl Mar 12 '18 at 13:54
  • 2
    Please don't pipe trivial grep to awk. `... | grep "pattern" | awk "{print $1}"` is better written `... | awk "/pattern/{print $1}"` – William Pursell Mar 12 '18 at 13:57
  • @FredrikPihl I have used $() to obtain the container_id actually. container_id=$(execute_command_on_host $IP $USER_NAME $USER_PASSWD "$docker_command") With this the container_id should be a string right? Or should I be using $() elsewhere in my code too? Updated my question – skorada Mar 12 '18 at 14:00

1 Answers1

0

I have tried the following and it worked for me.

docker_command="docker ps | awk '/consul/{print \$1}' | tr -d '\r\n'"

Line encoding seemed to be the issue

skorada
  • 431
  • 1
  • 4
  • 15