<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jason Aricheta on Medium]]></title>
        <description><![CDATA[Stories by Jason Aricheta on Medium]]></description>
        <link>https://medium.com/@jason.aricheta?source=rss-68ba1cded433------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yM0lnPaA4ORRDOyhhO06cg.png</url>
            <title>Stories by Jason Aricheta on Medium</title>
            <link>https://medium.com/@jason.aricheta?source=rss-68ba1cded433------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 05:31:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jason.aricheta/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building an interactive shell from scratch (with ruby)]]></title>
            <link>https://medium.com/@jason.aricheta/building-an-interactive-shell-from-scratch-with-ruby-ae656ab53167?source=rss-68ba1cded433------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae656ab53167</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[unix]]></category>
            <dc:creator><![CDATA[Jason Aricheta]]></dc:creator>
            <pubDate>Sun, 23 Feb 2025 06:44:18 GMT</pubDate>
            <atom:updated>2025-02-25T00:55:29.284Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QYLs2D3aKMYDkw77" /><figcaption>Photo by <a href="https://unsplash.com/@6heinz3r?utm_source=medium&amp;utm_medium=referral">Gabriel Heinzer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Reading user input in Ruby is easy with gets, but it blocks execution until enter/return is pressed — <strong>not ideal for an interactive shell</strong>. To handle keystrokes in real time, we need a different approach.</p><p>In this article, we’ll build an <strong>interactive shell</strong> from the ground up, exploring /dev/tty, raw mode, and ANSI escape sequences to capture and process keystrokes instantly.</p><h3>Starting Simple</h3><p>First of all, when creating an interactive shell in Ruby, you can get pretty far with just the following code:</p><pre>loop do<br>  print &quot;$ &quot;<br>  input = gets<br>  puts input<br>end</pre><p>This will create a shell that prepends your cursor &quot;$” and prints your input back to you.</p><p>Internally, gets is implicitly STDIN.gets(&quot;\n&quot;) — see <a href="https://ruby-doc.org/3.3.3/IO.html#method-i-gets">ruby docs</a>. The calling method repeatedly reads from the <a href="https://www.lenovo.com/us/en/glossary/stdin/">standard input</a> until it encounters &quot;\n” (newline character). Essentially blocking your runtime until you press <strong>enter</strong> or <strong>return</strong> in your keyboard and delivering &quot;\n” to the input stream for getsto see.</p><p>Once the newline character is encountered, gets returns with the newline and preceding characters which are then printed out with puts.</p><p>Simple, but <strong>not interactive</strong>! We want to react as the user is typing! We certainly can’t do it with gets — we need other tools for more control! ⚡</p><h3>Gathering our Tools</h3><p>In the following sections, we will gather three essential tools for better input control! Afterwards, we will combine them to create an interactive shell.</p><h4>1. Reading user input: Standard Input vs /dev/tty</h4><p>Before we get started, we need to know <strong>where we should read user input from</strong>. Previously, we relied on STDIN — however, this can be redirected. Unix systems have a better alternative: /dev/tty which <strong>always reads</strong> directly from the terminal — see <a href="https://stackoverflow.com/questions/6868296/whats-the-difference-between-stdin-and-tty-at-all">Stackoverflow</a>.</p><p><strong>Experiment 1: Using STDIN with and without redirect</strong></p><pre># stdin.rb<br>c = 0<br>loop do<br>  print &quot;$ &quot;<br>  input = STDIN.gets<br>  puts input<br>  c &lt; 3 ? (c += 1) : exit<br>end</pre><p>Then running without and with redirects:</p><pre>ruby stdin.rb<br># your user input<br><br>echo &quot;hello\nworld\nfoo&quot; | ruby stdin.rb<br>$ hello<br>$ world<br>$</pre><p>The former works as expected! 👌 As for the latter, <strong>the script didn’t wait for my user input before outputting! </strong>We can see that STDIN was filled automatically by the echo command due to redirection via |. This makes STDIN unreliable for interactive input.</p><p><strong>Experiment 2: Using /dev/tty Instead</strong></p><p>Now, let’s try /dev/tty:</p><pre># tty.rb<br>ftty = File.new &#39;/dev/tty&#39;<br>loop do<br> print &quot;$ &quot;<br> input = ftty.gets<br> puts input<br>end</pre><p>Try running this with and without redirection. /dev/tty always reads directly from the terminal, making it ideal for our use case 😃</p><p><strong>Experiment 3: Comparing File Descriptors</strong></p><pre># tty_test.rb<br>puts &quot;STDIN: fd #{STDIN.fileno}, tty? #{STDIN.tty?}&quot;<br>ftty = File.new(&quot;/dev/tty&quot;)<br>puts &quot;/dev/tty: fd #{ftty.fileno}, tty? #{ftty.tty?}&quot;</pre><p>Run it normally:</p><pre>ruby tty_test.rb<br># STDIN: fd 0, tty? true<br># /dev/tty: fd 6, tty? true<br><br>echo &quot;hello world&quot; | ruby tty_test.rb<br># STDIN: fd 0, tty? false  # &lt;---- now false!<br># /dev/tty: fd 6, tty? true</pre><p>The distinction is highlighted by the .tty? method — <a href="https://ruby-doc.org/3.3.3/IO.html#method-i-tty-3F">ruby docs</a>. Wherein if we execute the script with redirection, we can see that STDIN is no longer associated with the terminal but /dev/tty keeps it associated!👌</p><p>So, for a reliable interactive shell - we’ll use /dev/tty instead of STDIN.</p><h4>2. Fetching single keystrokes: `.getch`</h4><p>Now that we know where to read user input from, we still have one key problem: <strong>how do we capture input as the user types?</strong> We need a way to react to each keystroke <strong>instantly</strong>, rather than waiting for the user to press Enter.</p><p>This is where Ruby’s io/console library comes in, specifically the .getch method — <a href="https://ruby-doc.org/3.3.3/exts/io/IO.html#method-i-getch">ruby docs</a>.</p><p><strong>Experiment: Capturing Keystrokes</strong></p><p>Try running this script and typing hello:</p><pre># getch.rb<br>require &#39;io/console&#39;<br><br>ftty = File.new(&#39;/dev/tty&#39;)<br>c = 0<br>loop do<br>  char = ftty.getch<br>  print char + &quot; (#{char.ord}) &quot; + &quot;\n&quot;<br>  c &lt; (&quot;hello&quot;.length - 1) ? (c += 1) : exit<br>end</pre><p>You’ll see output like this:</p><pre>ruby /tmp/getch.rb<br>(104) $ h<br>(101) $ e<br>(108) $ l<br>(108) $ l<br>(111) $ o</pre><p>Instead of waiting for Enter, we capture <strong>each keystroke</strong> as it happens! The output shows both the character and its ASCII code, giving us full control over user input.</p><p>But before we can build our shell, we need <strong>one more tool</strong>. I promise, just one! 🤞</p><p><strong>3. Enabling Raw Mode with .raw</strong></p><p>By default, the terminal processes input and output for us — it buffers keystrokes, etc. However, we need <strong>full control</strong> over input and output to build an interactive shell.</p><p>According to <a href="https://www.gnu.org/software/mit-scheme/documentation/stable/mit-scheme-ref/Terminal-Mode.html">GNU.org</a>:</p><blockquote>A terminal port in raw mode disables all of that processing. In raw mode, characters are directly read from and written to the device without any translation or interpretation by the operating system.</blockquote><p>This means no automatic newline handling, no special key processing — just raw input &amp; output! (side note: <em>the reason we&#39;re able to fetch single user inputs with </em><em>.getch is because it </em><strong><em>momentarily</em></strong><em> enables raw-mode to turn off any buffering</em>)</p><p><strong>Experiment: Using .raw Mode</strong></p><p>Let’s modify our previous script to run in raw mode:</p><pre># raw.rb<br>require &#39;io/console&#39;<br><br>ftty = File.new(&#39;/dev/tty&#39;)<br>c = 0<br>ftty.raw do<br>  loop do<br>    char = ftty.getch<br>    print char + &quot;\n&quot;<br>    c &lt; (&quot;hello&quot;.length - 1) ? (c += 1) : exit<br>  end<br>end</pre><p>Run it and type hello:</p><pre>ruby /tmp/raw.rb<br>h<br> e<br>  l<br>   l<br>    o</pre><p>Wait… why is the text shifting to the right?</p><p><strong>Understanding the Issue</strong></p><p>Let’s break down what’s happening at the byte level. Our script is sending the following sequence to the terminal:</p><pre>h\ne\nl\nl\no\n</pre><p>Here’s what happens step by step:</p><ol><li>We type “h”. Nothing special — it’s printed normally.</li><li>Then we send “\n” (newline). This moves the cursor down a line but keeps the column it is on.</li><li>Next, we type “e”. Since the cursor is still indented from where “h” was printed, “e” appears shifted.</li><li>The pattern continues, causing a <strong>staircase effect</strong> in the output.</li></ol><p>The issue is that we never told the terminal to return to the start of the line after each newline. So let’s do just that!</p><p><strong>Fixing the Output with Carriage Returns (\r)</strong></p><pre>print char + &quot;\r&quot; + &quot;\n&quot;<br><br>### raw sequence ###<br># h\r\ne\r\nl\r\nl\r\no\r\n<br><br>### visible output ###<br># h<br># e<br># l<br># l<br># o</pre><p>Sweet! That fixes things! By telling the terminal to: (1) Move the cursor back to the start — \r (2) Move the cursor down a line — \n — we are able to get a legible output!</p><p>With raw mode enabled, we now have <strong>complete</strong> control over input and output — no interference from the operating system. <strong>We’re ready to build our interactive shell!</strong></p><blockquote>Aside: We know that the terminal came from typewriters. To visualize the “\r\n” combination from a physical type writer — check out this <a href="https://youtu.be/FkUXn5bOwzk?si=EReKdf0BVDF5YTwn&amp;t=90">youtube video</a>!</blockquote><h3>Building the Shell!</h3><p>Phew! We’ve gathered all our tools — now it’s time to put them together and build our interactive shell.</p><p>Here’s the basic version, incorporating everything we’ve learned:</p><pre># script.rb<br>require &quot;io/console&quot;<br><br>buffer = &quot;&quot;<br>prefix = &quot;\r\e[K&quot; + &quot;$ &quot;<br>ftty = File.new(&#39;/dev/tty&#39;)<br><br>c = 0<br>ftty.raw do<br>  print prefix<br>  loop do<br>    char = ftty.getch<br>    case char<br>    when &quot;\r&quot;<br>      print &quot;\r\n&quot;<br>      buffer = &quot;&quot;<br>    else<br>      buffer &lt;&lt; char<br>    end<br>    debug = ENV.fetch(&quot;DEBUG&quot;, &quot;&quot;) == &quot;1&quot; ? &quot; (#{ char.ord })&quot; : &quot;&quot;<br>    print prefix + buffer + debug<br><br>    # if removed, there&#39;s no mechanism to exit the process!<br>    c &lt; 20 ? (c += 1) : exit<br>  end<br>end</pre><p>Yeah… it’s definitely more complex than our original 5-line gets version — but we got what we wanted:<strong> more control! ⚡️</strong></p><p>Let’s test it out. There are two ways to run the script:</p><pre>ruby script.rb<br># $ aa<br># $ bbb<br># $ abcd<br># $ cba<br><br>DEBUG=1 ruby script.rb<br># $ aa (97)<br># $ bbb (98)<br># $ abcd (101)<br># $ cba (97)</pre><p>So cool! Let&#39;s try and go through this with some detail 🔍</p><h4>ANSI Escape Sequences</h4><p>First, we define two key variables:</p><pre>prefix = &quot;\r\e[K&quot; + &quot;$ &quot;<br>buffer = &quot;&quot;</pre><p>prefix contains <strong>static</strong> characters that define how our shell displays input while the buffer holds <strong>dynamic</strong> user input.</p><p><strong>What’s in the Prefix?</strong></p><p>The key to how this works lies in <strong>ANSI escape sequences</strong> — <a href="https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797">github gist</a>. Here’s what’s happening:</p><pre>&quot;\r&quot;   - Carriage return - move cursor to beginning of line<br>&quot;\e&quot;   - Marks beginning of an ANSI sequence<br>&quot;[K&quot;   - Erase from cursor to end of line<br>&quot;$ &quot;   - Shell prompt → simple visual cue</pre><p>Now, every time we print the prefix<strong> </strong>before updating the buffer, effectively <strong>we reset the input line to a clean state</strong>.</p><p><strong>How Printing Works (Step-by-Step)</strong></p><p>Say we type “hi” in our shell. Here’s what happens:</p><pre>ruby script.rb<br><br># Initial prompt:<br>$ <br><br># User types &quot;h&quot;:<br># 1. Store &quot;h&quot; in buffer.<br># 2. Move cursor to start (`\r`).<br># 3. Clear the line (`\e[K`).<br># 4. Print &quot;$ &quot; + buffer (&quot;h&quot;).<br><br># Output:<br>$ h<br><br># User types &quot;i&quot;:<br># 1. Add &quot;i&quot; to buffer (&quot;hi&quot;).<br># 2. Move cursor to start.<br># 3. Clear the line.<br># 4. Print &quot;$ &quot; + buffer (&quot;hi&quot;).<br><br># Output:<br>$ hi</pre><p>This process repeats <strong>for every keystroke</strong> — we’re essentially “re-rendering” the line each time, reminds me of react and DOM re-rendering! — <a href="https://www.joshwcomeau.com/react/why-react-re-renders/">article</a>.</p><h4><strong>Backbone of the Shell</strong></h4><p>Here’s a stripped-down version of our core logic:</p><pre>char = IO.console.getch<br><br>case char<br>when &quot;\r&quot;<br>  print &quot;\r\n&quot;<br>  buffer = &quot;&quot;<br>else<br>  buffer &lt;&lt; char<br>end<br><br>print prefix + buffer</pre><p>Most characters are <strong>added to the buffer</strong> and reprinted. But special cases (like “return”) trigger different behaviour —in our case — we <strong>reset the buffer and move to a new line</strong>.</p><p>To add a new behaviour, we can simply add a when clause! Let’s try just that!</p><h4>New Feature: Properly exiting our shell</h4><p>Right now, our shell exits after <strong>20 keystrokes </strong>— not ideal!</p><pre>c &lt; 20 ? (c += 1) : exit</pre><p>On macOS and Linux, pressing Ctrl + C (SIGINT) normally <strong>interrupts</strong> a running process. To see how this is represented, let&#39;s run script.rb in DEBUG mode.</p><pre>DEBUG=1 ruby script.rb<br><br># Output when pressing Ctrl + C:<br>$ (3)</pre><p>That (3) means the OS sends \x03 (ASCII 3) when Ctrl + C is pressed! Let’s modify our script to <strong>exit on Ctrl + C instead of after 20 keystrokes</strong>:</p><pre>case char<br>when &quot;\r&quot;<br>  print &quot;\r\n&quot;<br>  buffer = &quot;&quot;<br>when &quot;\x03&quot;  # Ctrl + C<br>  exit<br>else<br>  buffer &lt;&lt; char<br>end</pre><p>Now, pressing Ctrl + C <strong>properly exits</strong> the shell — no arbitrary keystroke limit needed! 👌</p><h3>Final Thoughts</h3><p>Phew! We made it!</p><p>In this article, we explored how to build an interactive shell in Ruby from scratch. We started with the basic gets method but we quickly found out that it’s simply not enough. Then, we explored the differences between STDIN and /dev/tty, learned how terminal raw-mode gives us direct control over keystrokes and broke down ANSI escape sequences to manage the display.</p><p>Here’s a challenge: how would you handle backspaces? or better yet, we’ve assumed that a keystroke is equal to a single byte - how would you handle multi-byte signals such as arrow keys? ⬆️⬇️⬅️➡️</p><p>Lastly, 9 times out of 10, you’re better off using frameworks like the inbuilt <a href="https://ruby-doc.org/stdlib-2.5.1/libdoc/readline/rdoc/Readline.html">readline module</a>. But where’s the fun in that? 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae656ab53167" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>