bash – echo command with option to display the output on the same line.

2010-09-21 229 words 2 mins read

Here is a nice little trick to display the output in the same line :

  <td>
    <div class="bash codecolorer">
      &nbsp;<span class="kw3">echo</span> <span class="re5">-ne</span> <span class="st0">"output\<span class="es1">\r</span>"</span>
    </div>
  </td>
</tr>
1

The trick here is simple, first we disable the <a class="zem_slink" title="Newline" rel="wikipedia" href="http://en.wikipedia.org/wiki/Newline">newline printed by <a class="zem_slink" title="Echo (command)" rel="wikipedia" href="http://en.wikipedia.org/wiki/Echo_%28command%29">echo command with the &#8221;-n&#8221; option and then we enable the interpretation of the <a class="zem_slink" title="Backslash" rel="wikipedia" href="http://en.wikipedia.org/wiki/Backslash">backslash characters with the &#8221;-e&#8221; option. As the &#8221;\r&#8221; is used as <a class="zem_slink" title="Carriage return" rel="wikipedia" href="http://en.wikipedia.org/wiki/Carriage_return">carriage return which brings you to the start of the line without the newline (like in <a class="zem_slink" title="Typewriter" rel="wikipedia" href="http://en.wikipedia.org/wiki/Typewriter">typewriter), we will use the same to get the desired effect. So, if you wanted a stopwatch for a 100 seconds on the console then this simple bash <a class="zem_slink" title="For loop" rel="wikipedia" href="http://en.wikipedia.org/wiki/For_loop">for loop would do the same:

  <td>
    <div class="bash codecolorer">
      <span class="kw1">for</span> i <span class="kw1">in</span> <span class="sy0">`</span><span class="kw2">seq</span> <span class="nu0">100</span> <span class="nu0">1</span><span class="sy0">`</span><br /> <br /> <span class="kw1">do</span><br /> <br /> <span class="kw3">echo</span> <span class="re5">-ne</span> <span class="st0">"<span class="es2">$i</span>\<span class="es1">\r</span>"</span><br /> <br /> <span class="kw1">done</span>
    </div>
  </td>
</tr>
1
2
3
4
5
6
7

<img class="size-medium wp-image-2555" title="bash screenshot for the script output" src="http://blog.amit-agarwal.co.in/wp-content/uploads/2010/09/temp-300x170.gif" alt="bash screenshot for the script output" width="300" height="170" />

Have fun playing with this and comment if you find some other interesting use of the same.

\"Enhanced

author

Authored By Amit Agarwal

Amit Agarwal, Linux and Photography are my hobbies.Creative Commons Attribution 4.0 International License.

We notice you're using an adblocker. If you like our webite please keep us running by whitelisting this site in your ad blocker. We’re serving quality, related ads only. Thank you!

I've whitelisted your website.

Not now
This website uses cookies to ensure you get the best experience on our website. Learn more Got it