I am trying to run bash inside docker container using docker exec bash -c and store its output on the host(not the container) by echo'ing something which will be used in conditional statement. I could be echo'ing anything like ip hostname or just a string. Problem is that the echo output

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

As you can see var1 and var2 both echo 1 but the if-else condition is failing. Also the variable declaration output is maligned. Something is messing up the output from docker container to host, not sure what that is

I also tried another docker image from Ubuntu. Example above was from centos7

[root@localhost ~]# var3=`docker run -t ubuntu bash -c 'echo 1'`
[root@localhost ~]# declare -p var3
"eclare -- var3="1
[root@localhost ~]#
  • 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 have 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.

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.