I am trying to run bash inside a Docker container using docker exec bash -c and store its output on the host (not the container) by echoing something which will be used in a conditional statement. I could be echoing anything like IP hostname or just a string. The problem is the echo output:

$ var1=$(docker exec -t test_masternode1 bash -c 'echo 1')
$ echo $var1
$ declare -p var1
"eclare -- var1="1
$ var2=1
$ declare -p var2
declare -- var2="1"
$ echo $var2
$ if [ "$var1" == "$var2" ];then echo "same";else echo "not same";fi
not same

As you can see var1 and var2 are both 1 but the if-else test is failing. Also, the variable declaration output is misaligned. Something is messing up the output from the Docker container; not sure what that is.

I also tried another Docker image from Ubuntu. The example above was from CentOS 7.

$ var3=`docker run -t ubuntu bash -c 'echo 1'`
$ declare -p var3
"eclare -- var3="1
  • 2
    It's obvious that the string comes back with a carriage return (\r) at the end, as if it had been a line from a DOS text file. I don't know Docker so I can't say whether this is to be expected or not.
    – Kusalananda
    Dec 10, 2018 at 13:40
  • Good eyes & theory! I was tempted to ask if it was a copy/paste typo.
    – Jeff Schaller
    Dec 10, 2018 at 14:15
  • 2
    Related: github.com/moby/moby/issues/8513
    – Jeff Schaller
    Dec 10, 2018 at 14:31
  • Thanks for all for your comments.. i have been to same post. looks like the best way to deal with the issue is to filter out the carriage return from the command and then store it into variable since linux terminal uses CRLF. [root@localhost ~]# var3=docker exec -t test_masternode1 bash -c 'echo 1' | sed -e's/\r//' Dec 10, 2018 at 15:09

1 Answer 1


The data comes back with a carriage return from Docker. The carriage return, when outputted, causes the cursor to move to the beginning of the line. Hence the slightly odd-looking output when you display the value of your variable. This seems to be (or has been) an issue for others as well, as is evident from this GitHub issue.

To remove any carriage returns from the data, pass it through tr -d '\r':

var1=$(docker exec -t test_masternode1 bash -c 'echo 1' | tr -d '\r')

... or simply run your command without the -t option. The -t option to docker exec and docker run allocates a pseudo-TTY, which is only really needed for interactive commands. The command echo 1 is not such a command.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .