<?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 Ricardo Gerardi on Medium]]></title>
        <description><![CDATA[Stories by Ricardo Gerardi on Medium]]></description>
        <link>https://medium.com/@ricardo.gerardi?source=rss-e464162308a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VOxNgXQpi3CsbK7lYQWPmg.jpeg</url>
            <title>Stories by Ricardo Gerardi on Medium</title>
            <link>https://medium.com/@ricardo.gerardi?source=rss-e464162308a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:34:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ricardo.gerardi/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[Configure a Tailscale Exit Node on Fedora IoT]]></title>
            <link>https://medium.com/@ricardo.gerardi/configure-a-tailscale-exit-node-on-fedora-iot-12a684824cb5?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a684824cb5</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[fedora-linux]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[tailscale]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Fri, 25 Oct 2024 22:13:30 GMT</pubDate>
            <atom:updated>2024-10-26T02:16:04.203Z</atom:updated>
            <content:encoded><![CDATA[<h4>Secure your Internet connection using Tailscale and a reliable IoT device running Fedora Linux.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vvU0DNWYCKK0yAVe" /><figcaption>Photo by <a href="https://unsplash.com/@privecstasy?utm_source=medium&amp;utm_medium=referral">Privecstasy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://tailscale.com/">Tailscale</a> is an open-source mesh Virtual Private Network (VPN) service based on the <a href="https://www.wireguard.com/">Wireguard</a> protocol. It allows you to connect devices quickly and securely across different networks without router changes or complicated firewall configuration. To get started with Tailscale, follow the <a href="https://tailscale.com/kb/1017/install">Quickstart</a> guide to create your account and setup a Tailscale network, or Tailnet.</p><p>I’ve been using Tailscale for the past few months to access some of my home services and devices from outside my network, and to secure my connection when working from public places, like a library or a coffee shop.</p><p>To secure your connection when using an untrusted network, you can configure Tailscale to route all your internet traffic through an exit node. You can set any device on your network as the exit node.</p><p>In my case I decided to setup an exit node on a dedicated device using the <a href="https://fedoraproject.org/iot/">Fedora IoT</a> immutable Linux distribution. Fedora IoT is great choice to power small devices that need to run unattended. Since I am going to depend on this device while connected outside the home, I want an operating system that’s reliable and resilient. You can read more about Fedora IoT on my previous article <a href="https://medium.com/pragmatic-programmers/how-to-install-fedora-iot-on-raspberry-pi-4-872bfbdbf16f">How to Install Fedora IoT on Raspberry Pi 4</a>.</p><p>If you prefer to install Fedora IoT on another device, instead of a Raspberry Pi, you can also boot the installer from the <a href="https://docs.fedoraproject.org/en-US/iot/booting-the-simplified-provisioner/">Provisioner ISO</a>. When Fedora IoT is up and running on your device, you can proceed with the Tailscale install.</p><h3>Install Tailscale on Fedora IoT</h3><p>Unlike a regular Fedora Linux, Fedora IoT uses <a href="https://coreos.github.io/rpm-ostree/">rpm-ostree</a>, instead of dnf, to install and manage software packages. rpm-ostree enables atomic system updates and rollbacks in case of issues.</p><p>To get started, enable the Tailscale package repository for Fedora:</p><pre>$ sudo curl https://pkgs.tailscale.com/stable/fedora/tailscale.repo \<br> -O --output-dir /etc/yum.repos.d/</pre><p>Install Tailscale using rpm-ostree:</p><pre>$ sudo rpm-ostree install tailscale</pre><p>Fedora IoT supports the <em>immutable</em> Linux model, which handles operations such as updates and package installs as atomic transactions. This approach makes the system behave as it’s image-based, instead of modifying the file system directly. It enhances system resiliency by allowing you to rollback to a previous working image in case of issues. However, a downside of this approach is that new packages become available only after rebooting the system into the new, updated image.</p><p>Reboot the system to make the new package available:</p><pre>$ sudo systemctl reboot</pre><p>When the system comes back online, verify the rpm-ostree status to ensure tailscale is installed:</p><pre>$ rpm-ostree status<br>State: idle<br>Deployments:<br>● fedora-iot:fedora/stable/x86_64/iot<br>                  Version: 40.20241010.0 (2024-10-10T18:01:21Z)<br>               BaseCommit: 8f93adcadbeb79269ead20f62eb88b46653222338464b2564b53f358a5719c46<br>             GPGSignature: Valid signature by 115DF9AEF857853EE8445D0A0727707EA15B79CC<br>          LayeredPackages: tailscale<br><br>  fedora-iot:fedora/stable/x86_64/iot<br>                  Version: 40.20240422.3 (2024-04-22T19:43:59Z)<br>                   Commit: 5bcc01335c19de1117841d2334062196fc40369bcbe6f71055ac3a2ddaa013f3<br>             GPGSignature: Valid signature by 115DF9AEF857853EE8445D0A0727707EA15B79CC</pre><p>You can now configure the system to work as an exit node.</p><h3>Configure Tailscale Exit Node Pre-Requisites</h3><p>The exit node’s main goal is to forward packets from your devices to the internet, securely. By default, packet forwarding is disabled on Fedora IoT. You can enable packet forward by tuning the required Linux kernel parameters using sysctl. To ensure the setting persists across reboots, use a configuration file under /etc/sysctl.d directory:</p><pre>$ echo &#39;net.ipv4.ip_forward = 1&#39; | sudo tee -a /etc/sysctl.d/99-tailscale.conf<br>net.ipv4.ip_forward = 1<br><br>$ echo &#39;net.ipv6.conf.all.forwarding = 1&#39; | sudo tee -a /etc/sysctl.d/99-tailscale.conf<br>net.ipv6.conf.all.forwarding = 1</pre><p>Then, load the configuration into the running system:</p><pre>$ sudo sysctl -p /etc/sysctl.d/99-tailscale.conf<br>net.ipv4.ip_forward = 1<br>net.ipv6.conf.all.forwarding = 1</pre><p>Tailscale also recommends allowing masquerading to avoid a known issue with firewalld which Fedora IoT uses:</p><pre>$ sudo firewall-cmd --permanent --add-masquerade<br>success<br><br>$ sudo firewall-cmd --reload<br>success<br><br>$ sudo firewall-cmd --list-all<br>public (default, active)<br>  target: default<br>  ingress-priority: 0<br>  egress-priority: 0<br>  icmp-block-inversion: no<br>  interfaces: enp1s0<br>  sources:<br>  services: dhcpv6-client mdns ssh<br>  ports:<br>  protocols:<br>  forward: yes<br>  masquerade: yes<br>  forward-ports:<br>  source-ports:<br>  icmp-blocks:<br>  rich rules:</pre><p>For more information about the exit node pre-requisites, consult the <a href="https://tailscale.com/kb/1103/exit-nodes">Tailscale exit node documentation</a>.</p><p>Finally, enable and start the Tailscale daemon service:</p><pre>$ sudo systemctl enable --now tailscaled<br>Created symlink /etc/systemd/system/multi-user.target.wants/tailscaled.service → /usr/lib/systemd/system/tailscaled.service.</pre><p>You’re ready to start Tailscale and advertise your device as an exit node.</p><h3>Advertise Device as a Tailscale Exit Node</h3><p>With all the pre-requisites in place and the daemon started, you can start Tailscale and authorize the device on your Tailnet:</p><pre>$ sudo tailscale up<br><br>To authenticate, visit:<br><br>        https://login.tailscale.com/a/XXXXXXXXXXX<br><br>Success.</pre><p>Copy the login URL and paste it on a browser to authenticate the device. Alternatively you can use a QR code and your mobile device, to make the authentication easier:</p><pre>$ sudo tailscale up --qr</pre><p>Your new device shows up in the Admin console:</p><figure><img alt="Tailscale console — device connected" src="https://cdn-images-1.medium.com/max/1024/1*EwF3S2TcVwunA74UhDeDaA.png" /></figure><p>Now, advertise your device as an exit node:</p><pre>$ sudo tailscale set --advertise-exit-node</pre><p>Back in the Admin console, select the newly added device, click on … and select “Edit route settings”:</p><figure><img alt="Tailnet edit route settings" src="https://cdn-images-1.medium.com/max/1024/1*t4sg_oS2Ls1NEOtWUvQgsA.png" /></figure><p>Then on the pop-up box, check the option “Use as exit node”:</p><figure><img alt="Tailnet use as exit node" src="https://cdn-images-1.medium.com/max/498/1*Dus910LA7nkqOSA1EPax6g.png" /></figure><p>Now you can use this device as an exit node to route internet traffic securely from other devices connected to your Tailnet.</p><h3>Enable Tailscale Greenboot Check</h3><p>Fedora IoT offers another feature to increase the system reliability: <a href="https://github.com/fedora-iot/greenboot">Greenboot</a>, a generic health check framework for <em>rpm-ostree</em> based systems.</p><p>In a nutshell, Greenboot checks the system health after each reboot and, in case of issues such as a failed update, it automatically restarts or even rolls back to a previous working image of the system. Greenboot comes with several pre-configured system checks that ensure the system is working, and it shines when managing unattended devices.</p><p>Since this device works as an exit node, it would be particularly interesting to use Greenboot to ensure Tailscale is working as part of the health check.</p><p>To enable a custom health check, add a script to Greenboot’s required checks directory /etc/greenboot/check/required.d. If any script in this directory exits with an error code, Greenboot considers the system unhealthy and proceeds with the restarts and potential rollback.</p><p>Add a Tailscale check script like this:</p><pre>$ cat &lt;&lt; &#39;EOF&#39; | sudo tee /etc/greenboot/check/required.d/tailscale_status.sh<br>#!/bin/bash<br><br>function tailscale_status {<br>        vpn_state=$(test -d /proc/sys/net/ipv4/conf/tailscale0)<br><br>        if [ $? -eq 0 ]; then<br>                tailscale_out=$(tailscale status)<br><br>                if [ $? -eq 0 ]; then<br>                        echo &quot;Tailscale up&quot;<br>                        exit 0<br>                fi<br>        fi<br><br>        echo &quot;Tailscale DOWN&quot;<br>        exit 1<br>}<br><br>tailscale_status<br>EOF</pre><p>This is a basic script that should cover most of the cases. You can improve it by adding a few retries if you notice that Tailscale takes a couple of seconds to start.</p><p>Next, ensure the script is executable:</p><pre>$ sudo chmod +x /etc/greenboot/check/required.d/tailscale_status.sh</pre><p>Test the script with Tailscale up to ensure it works as designed:</p><pre>$ /etc/greenboot/check/required.d/tailscale_status.sh<br>Tailscale up</pre><p>You can now reboot your system and log back in. When you log in to the system, the prompt displays Greenboot health check status:</p><pre>[local] $ ssh fiotts04<br>Boot Status is GREEN — Health Check SUCCESS</pre><h3>What’s Next?</h3><p>You have configured Tailscale exit node on a Fedora IoT Linux device. You can use this device to secure your internet access when working from untrusted networks.</p><p>You’re also using Fedora IoT’s feature such as atomic updates, immutability, and Greenboot to ensure the device runs reliably and handles typical issues automatically even when you need it.</p><p>In the next article, I will show you how to tune the device and Tailscale for increased performance, security, and reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a684824cb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Fedora IoT Configuration on a Raspberry Pi 4 with Ansible]]></title>
            <link>https://medium.com/pragmatic-programmers/automate-fedora-iot-configuration-on-a-raspberry-pi-4-with-ansible-4b78d7a9aa0f?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b78d7a9aa0f</guid>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[home-automation]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 11:26:55 GMT</pubDate>
            <atom:updated>2023-12-28T11:26:55.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m6zlizpqlnANj-nk" /></figure><h4>Creating a Reusable Playbook</h4><figure><img alt="https://pragprog.com/newsletter/" src="https://cdn-images-1.medium.com/max/1024/0*x5eFIiXuy6jV3ofM.png" /><figcaption><a href="https://pragprog.com/newsletter/">https://pragprog.com/newsletter/</a></figcaption></figure><pre>In this article:<br>* <a href="#c06f">Test Connectivity with Raspberry Pi</a><br>* <a href="#f1aa">Create the Ansible Playbook</a><br>* <a href="#3c3c">Execute the Playbook</a><br>* <a href="#ba87">What&#39;s Next?</a></pre><p>Create an Ansible playbook that sets the hostname, adds a new user, layers additional packages, and more on your Fedora IoT-based Raspberry Pi.</p><p>In <a href="https://medium.com/pragmatic-programmers/how-to-install-fedora-iot-on-raspberry-pi-4-872bfbdbf16f">Install Fedora IoT on Raspberry Pi 4</a>, I explained how to install Fedora IoT. If you followed along with the article, you have a functional <a href="https://opensource.com/tags/raspberry-pi?intcmp=701f20000012ngPAAQ">Raspberry Pi</a> 4 system with the latest updates but no configuration.</p><p>In this article, I’ll use <a href="https://www.redhat.com/en/technologies/management/ansible/ansible-vs-red-hat-ansible-automation-platform?intcmp=701f20000012ngPAAQ">Ansible</a> to automate the device configuration by creating a playbook that sets the hostname, adds a new user, layers additional packages, and more.</p><p>By default, <a href="https://docs.fedoraproject.org/en-US/iot/?intcmp=701f20000012ngPAAQ">Fedora IoT</a> comes with Python preinstalled. Together with Secure Shell (<a href="https://www.redhat.com/sysadmin/access-remote-systems-ssh">SSH</a>), it has everything needed to support Ansible automation as a client. To follow along with this example, you need <a href="https://www.redhat.com/sysadmin/ansible-quick-start">Ansible installed</a> in a “control” machine that has access to the Raspberry Pi.</p><h3>Test Connectivity with Raspberry Pi</h3><p>Before working on the playbook, ensure Ansible can talk to the Raspberry Pi. To do this, first create an inventory file with connection details. You’ll use this inventory file again later to execute the playbook.</p><p>Create the inventory file inventory.yaml with this content, replacing the IP address and SSH key with the ones appropriate for your environment:</p><pre>all:<br>  children:<br>    edge:<br>      vars:<br>        ansible_ssh_private_key_file: /home/ricardo/.ssh/id_rsa<br>        ansible_ssh_user: root<br>      hosts:<br>        rpi4iot:<br>          ansible_host: 192.168.10.152</pre><p>Then run ansible with the ping module to test connectivity:</p><pre>$ ansible edge -i inventory.yaml -m ping<br>rpi4iot | SUCCESS =&gt; {<br>    &quot;ansible_facts&quot;: {<br>        &quot;discovered_interpreter_python&quot;: &quot;/usr/bin/python3&quot;<br>    },<br>    &quot;changed&quot;: false,<br>    &quot;ping&quot;: &quot;pong&quot;<br>}</pre><h3>Create the Ansible Playbook</h3><p>Ansible is highly flexible and you can use it to configure every aspect of your Raspberry Pi, including deploying the applications you want to run on it. For this example, I’m starting with the basic configuration.</p><p>This playbook has four goals:</p><ol><li>Adding a new unprivileged user with sudo access to avoid using root to connect to the system.</li><li>Configure the system hostname.</li><li>Deploy additional required packages layered on top of the base image: tmux<br>htop<br>cockpit<br>cockpit-podman</li><li>Enable Cockpit to start on boot</li></ol><p>You can use this playbook as a starting point to add your own configurations later.</p><p>In addition to the builtin collection, you need to install two additional collections to enable Ansible to support these goals: ansible.posix to update firewall rules and community.general to manage sudoers files and layer new packages to ostree. Install them using ansible-galaxy:</p><pre>$ ansible-galaxy collection install ansible.posix community.general</pre><p>Then create the playbook playbook.yaml with this content. Replace the variables with values that are appropriate for your environment:</p><pre>---<br>- name: Configure Fedora IoT on Raspberry Pi<br>  hosts: edge<br>  gather_facts: true<br>  vars:<br>    user_name: ricardo<br>    user_full_name: Ricardo<br>    user_ssh_pub_key: /home/ricardo/.ssh/id_rsa.pub<br>  tasks:<br>    - name: Define hostname<br>      ansible.builtin.hostname:<br>        name: &quot;{{ inventory_hostname }}&quot;<br><br>    - name: Add unprivileged user<br>      ansible.builtin.user:<br>        name: &quot;{{ user_name }}&quot;<br>        comment: &quot;{{ user_full_name }}&quot;<br>        uid: 1000<br>        group: wheel<br>        state: present<br><br>    - name: Set authorized key for new user<br>      ansible.posix.authorized_key:<br>        user: &quot;{{ user_name }}&quot;<br>        state: present<br>        key: &quot;{{ lookup(&#39;file&#39;, user_ssh_pub_key) }}&quot;<br><br>    - name: Allow group wheel sudo access no password<br>      community.general.sudoers:<br>        name: wheel-all<br>        group: wheel<br>        commands: ALL<br>        nopassword: true<br><br>    - name: Ensure packages tmux, htop, and cockpit are available<br>      community.general.rpm_ostree_pkg:<br>        name:<br>          - tmux<br>          - htop<br>          - cockpit<br>          - cockpit-podman<br>        state: present<br>      register: ostree_results<br><br>    - name: Reboot system to enable new packages<br>      ansible.builtin.reboot:<br>        reboot_timeout: 600<br>      when:<br>        - ostree_results is changed<br><br>    - name: Ensure Cockpit socket is started and enabled<br>      ansible.builtin.systemd:<br>        name: cockpit.socket<br>        state: started<br>        enabled: true<br><br>    - name: Allow access to Cockpit<br>      ansible.posix.firewalld:<br>        service: cockpit<br>        permanent: true<br>        state: enabled<br>        immediate: true</pre><p>Notice that I added a when condition to the &quot;Reboot&quot; task to execute only if the previous task makes a change to the system. This enables the playbook to be <a href="https://docs.ansible.com/ansible/latest/reference_appendices/glossary.html#term-Idempotency?intcmp=701f20000012ngPAAQ">idempotent</a>, ensuring the system reboots only if needed.</p><h3>Execute the Playbook</h3><p>Now, run the playbook using the inventory file inventory.yaml that you created before:</p><pre>$ ansible-playbook -i inventory.yaml playbook.yaml <br><br>PLAY [Configure Fedora IoT on Raspberry Pi] ***********************************<br><br>TASK [Gathering Facts] ********************************************************<br>ok: [rpi4iot]<br><br>TASK [Define hostname] ********************************************************<br>changed: [rpi4iot]<br><br>TASK [Add unprivileged user] **************************************************<br>changed: [rpi4iot]<br><br>TASK [Set authorized key for new user] ****************************************<br>changed: [rpi4iot]<br><br>TASK [Allow group wheel sudo access no password] ******************************<br>changed: [rpi4iot]<br><br>TASK [Ensure packages tmux, htop, and cockpit are available] ******************<br>changed: [rpi4iot]<br><br>TASK [Reboot system to enable new packages] ***********************************<br>changed: [rpi4iot]<br><br>TASK [Ensure Cockpit socket is started and enabled] ***************************<br>changed: [rpi4iot]<br><br>TASK [Allow access to Cockpit] ************************************************<br>changed: [rpi4iot]<br><br>PLAY RECAP ********************************************************************<br>rpi4iot  : ok=9    changed=3    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   </pre><p>Now you can access the Raspberry Pi with the regular user you created instead of root:</p><pre>$ ssh -i /home/ricardo/.ssh/id_rsa 192.168.10.152<br>Boot Status is GREEN - Health Check SUCCESS<br>Web console: https://rpi4iot:9090/ or https://192.168.10.152:9090/<br><br>Last login: Thu Mar  9 05:28:28 2023 from 192.168.10.122<br>[ricardo@rpi4iot ~]$ </pre><p>Notice that the hostname is updated and Cockpit is available.</p><h3>What’s Next?</h3><p>Your Fedora IoT on Raspberry Pi looks much better now — even with a basic configuration. Use this Ansible automation playbook as a starting point and add remaining configurations according to your requirements. The best part is that it’s reproducible. If you have an issue or need to reinstall the system, you can use the same playbook and, in a few minutes, your Raspberry Pi will be ready again.</p><p>Now the system is ready to run workloads like the container-based home automation application I want to run on mine. But before that, in the next article, I’ll show how to use Greenboot to run health checks and ensure the system runs smoothly and resiliently.</p><p>Check out <a href="https://pragprog.com/search/?q=ricardo">Ricardo’s books</a>, published by The Pragmatic Bookshelf</p><ul><li><a href="https://pragprog.com/titles/gohome/automate-your-home-using-go/">Automate Your Home Using Go</a></li><li><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GzopYiqyg5Y2URBf.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dXkoAxSLsylfKWBQ.jpg" /><figcaption>Covers for <a href="https://pragprog.com/titles/gohome/automate-your-home-using-go/">Automate Your Home Using Go</a> and <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command Line Applications in Go</a></figcaption></figure><p><em>Originally published at </em><a href="https://www.redhat.com/sysadmin/ansible-automate-fedora-iot-config"><em>https://www.redhat.com</em></a><em> on March 29, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b78d7a9aa0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/automate-fedora-iot-configuration-on-a-raspberry-pi-4-with-ansible-4b78d7a9aa0f">Automate Fedora IoT Configuration on a Raspberry Pi 4 with Ansible</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Install Fedora IoT on Raspberry Pi 4]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/pragmatic-programmers/https-medium-com-pragmatic-programmers-fedora-iot-on-raspberry-pi-4-872bfbdbf16f?source=rss-e464162308a9------2"><img src="https://cdn-images-1.medium.com/max/1200/0*yjtiGuaUBS2uoZz7" width="1200"></a></p><p class="medium-feed-snippet">Transform Your Raspberry Pi into an Edge Computing Device with Fedora IoT</p><p class="medium-feed-link"><a href="https://medium.com/pragmatic-programmers/https-medium-com-pragmatic-programmers-fedora-iot-on-raspberry-pi-4-872bfbdbf16f?source=rss-e464162308a9------2">Continue reading on The Pragmatic Programmers »</a></p></div>]]></description>
            <link>https://medium.com/pragmatic-programmers/https-medium-com-pragmatic-programmers-fedora-iot-on-raspberry-pi-4-872bfbdbf16f?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/872bfbdbf16f</guid>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[fedora-linux]]></category>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[home-automation]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Tue, 05 Dec 2023 12:31:51 GMT</pubDate>
            <atom:updated>2023-12-05T12:31:51.615Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Find anything you need with fzf, the Linux fuzzy finder tool]]></title>
            <link>https://medium.com/pragmatic-programmers/find-anything-you-need-with-fzf-the-linux-fuzzy-finder-tool-f48dfd0092b4?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f48dfd0092b4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[linux]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Mon, 24 Jul 2023 10:31:54 GMT</pubDate>
            <atom:updated>2023-07-28T19:47:01.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2O5c8ToqHpq8XKX3l0GFPA.png" /><figcaption>Image of the text on page 79 of <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command Line Applications in Go</a></figcaption></figure><h3>Find Anything You Need with fzf</h3><h4>The Linux Fuzzy Finder Tool</h4><blockquote>I’m thankful for the Linux fuzzy finder tool because it superpowers the command line by making it fast to find whatever I’m looking for.</blockquote><figure><img alt="https://pragprog.com/newsletter/" src="https://cdn-images-1.medium.com/max/1024/0*x5eFIiXuy6jV3ofM.png" /><figcaption><a href="https://pragprog.com/newsletter/">https://pragprog.com/newsletter/</a></figcaption></figure><pre>In this article:<br>* <a href="#1287">What Is fzf?</a><br>* <a href="#4d0a">Install fzf</a><br>* <a href="#f0eb">Get Started Using fzf</a><br>* <a href="#9a1d">Preview File Content</a><br>* <a href="#b145">Change the Default Search Command</a><br>* <a href="#f343">Use Autocompletion</a><br>* <a href="#ec58">Superpower Your Command Line with fzf Key Bindings</a><br>* <a href="#795b">Other Ways to Use This Powerful Tool</a></pre><blockquote><strong><em>🎥 Note: </em></strong><em>The terminal session recordings in this article use </em><a href="https://asciinema.org/about"><em>asciinema</em></a><em>. When you click on one of them it will open in a new tab for you to play the recording. Medium does not yet support playing the recordings from within an article.</em></blockquote><p>One of the aspects of the open source community that excites me the most is having the opportunity to interact with people from different backgrounds, learn, and share experiences with them. During these interactions, I often learn about new ideas, improved ways to perform my job, and new technologies and tools.</p><p>Some of these tools can break paradigms and change the way you work. For me, one of these tools is fzf, a command-line &quot;fuzzy finder&quot; developed in <a href="https://medium.com/pragmatic-programmers/how-to-get-started-programming-in-go-4122f8e48e7a">Go</a>.</p><p>If you’ve seen some of my other <a href="https://medium.com/@ricardo.gerardi">articles</a>, then you’re probably aware that I’m a big fan of using the Linux command-line environment. The fzf command significantly improves your terminal experience and increases your productivity. fzf is so versatile and powerful that I often say it gives your command line magic powers.</p><h3>What Is fzf?</h3><p>In its most basic form, fzf works as a filter, processing text from standard input (stdin), then outputting a matching selection to standard output (stdout). In a way, fzf is similar to <a href="https://sysadminsignal.com/2023/05/22/find-text-in-files-using-the-linux-grep-command/">grep</a>, but it adds features that make it more suitable for interactive searches, including:</p><ul><li>Fuzzy finding capabilities allow approximate searches by any part of the match in any order.</li><li>Super-fast processing speed.</li><li>Interactive match selection lets the user select the desired match after initial filtering.</li><li>Single- or multi-text selection.</li><li>File content previews.</li><li>A comprehensive set of features and customization options.</li></ul><p>Due to these features, fzf is a fantastic option when you&#39;re searching anything on the terminal, for scripts, and to develop pseudo user interfaces for command-line programs.</p><p>When I think about it, I am still in awe that I have access to such a fantastic tool from the open source community. I am grateful that <a href="https://github.com/junegunn">Junegunn Choi</a> and other contributors made it available for others to benefit.</p><h3>Install fzf</h3><p>Because fzf is developed in Go, you install it by downloading the binary application straight from the project&#39;s <a href="https://github.com/junegunn/fzf/releases">Releases</a> webpage. However, to experience its full benefits, you should also download the shell extension files to add new key bindings and autocompletion for your shell. Alternatively, you can install the package version that contains everything from your distribution&#39;s repository. For example, for Fedora, install it using dnf:</p><pre>$ sudo dnf -y install fzf</pre><p>I also recommend you install two additional tools that will improve your experience with fzf: fd-find, a faster and improved version of the find command, and bat to preview file contents. For more information about bat, take a look at Seth Kenlon&#39;s article, <a href="https://www.redhat.com/sysadmin/linux-bat-command">Drop the Linux cat command for bat</a>.</p><p>Install these packages in Fedora using dnf:</p><pre>$ sudo dnf -y install fd-find bat</pre><p>Now that you have fzf and those prerequisites installed, take a look at how it can improve your terminal experience.</p><h3>Get Started Using fzf</h3><p>To start with fzf, run it without any arguments. By default, fzf searches all files under the current directory, allows you to filter and search interactively, and then prints the result to standard output. For example, to search for the default Pipewire configuration file without knowing where it&#39;s located, you can use fzf starting from your root directory:</p><figure><a href="https://asciinema.org/a/yTnjwqwmMNr3swXvjJIma16jb"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ASYon7JbBtN-4uugptOviw.png" /></a></figure><p>Notice that fzf updates the matches dynamically while you type the search terms in any order.</p><p>Also, because fzf prints the selection into standard output, it gives you unlimited flexibility on how to use its output. For example, imagine you want to edit the file above with Vim. You could use fzf to obtain the file name and pass it like this:</p><pre>$ vim $(fzf)</pre><figure><a href="https://asciinema.org/a/GQIsKoCEQTJXZXeOzslx8hxGv"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0dhcegQNF_FE6qrmsQsX9Q.png" /></a></figure><p>Or you could use fzf to copy the file to a different location:</p><pre>$ cp $(fzf) ~/.config/pipewire</pre><figure><a href="https://asciinema.org/a/YEvtMk8s17eCgMgkHAUIYBnKp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HH_7ww3xLiEMWfcoXuv5WQ.png" /></a></figure><p>The possibilities are endless, but fzf adds more niceties to improve your productivity even more.</p><h3>Preview File Content</h3><p>Another nice fzf feature is the ability to preview each file as you navigate the interactive selector. Previewing files as you search gives you an extra chance to find what you&#39;re looking for, particularly if you&#39;re not sure which file you want.</p><p>You can use any command you want to preview. You can also use scripts to make it smarter and change it according to the selected item. For example, to use bat to preview files, call fzf using the --preview command line flag:</p><pre>$ fzf --preview &#39;bat --color=always {}&#39;</pre><figure><a href="https://asciinema.org/a/sZHXOwJUX0xZtG75BAikqNPPu"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-B9ccyYKkKNjPXMrFFt9g.png" /></a></figure><p>To avoid typing this option every time, you can set the environment variable FZF_DEFAULT_OPTS to apply it automatically every time you run fzf:</p><pre>$ export FZF_DEFAULT_OPTS=&quot;--preview &#39;bat --color=always {}&#39;&quot;</pre><p>You can also set this environment variable on your shell initialization script, such as .bashrc for Bash, to make it permanent.</p><h3>Change the Default Search Command</h3><p>By default, when you execute fzf with no arguments, it uses the find command to search for files. For faster and more feature-rich searches, you can replace the default search command with <a href="https://opensource.com/article/20/6/modern-linux-command-line-tools">fd</a> by setting the environment variable FZF_DEFAULT_COMMAND like this:</p><pre>$ export FZF_DEFAULT_COMMAND=&quot;fd --type f&quot;</pre><p>fd is quicker and smarter than find, ignoring directories like .git and using your .gitignore options while searching. fdconsiderably improves the experience.</p><p>For permanent changes, set this environment variable in your shell initialization script.</p><h3>Use Autocompletion</h3><p>Another fzf feature that helps improve your terminal productivity is context-aware autocompletion. To enable this feature, you either need to install fzf using the package or download the corresponding completion file from the repository and enable it.</p><p>If you installed fzf using the Fedora package, autocompletion is automatically enabled. Restart your terminal after installation to ensure it loads the autocompletion options.</p><p>To use autocompletion, type ** and press <strong>Tab</strong> in front of a command to launch fzf with a list of context-relevant suggestions. For example, if you use it in front of a command that expects a file, such as vim, fzf lists files. On the other hand, if you use it with ssh, then fzf lists possible remote systems to connect to from your hosts or SSH config files.</p><pre>$ vim ** &lt;TAB&gt;</pre><figure><a href="https://asciinema.org/a/srkGSzAaxxPwRvFAglEXc9i67"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPshzYc2NgdPcc_dXGxq_g.png" /></a></figure><p>For SSH:</p><figure><a href="https://asciinema.org/a/xvFT3zy2ASvjQhtnl0Z5Kuemp"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiS_zYN_jf-j4idZ36x1Eg.png" /></a></figure><p>You can also use fzf autocompletion to complete environment variables or to find processes in the context of the kill command:</p><figure><a href="https://asciinema.org/a/so9vDT9USXCLCSKO81FZA4k6n"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PibS6Z4PAmtKFG3rn5Zqng.png" /></a></figure><p>For more examples of how to use and customize this feature, take a look at the project’s <a href="https://github.com/junegunn/fzf#fuzzy-completion-for-bash-and-zsh">documentation.</a></p><h3>Superpower Your Command Line with fzf Key Bindings</h3><p>Using fzf directly or via autocompletion is great, but adding key bindings makes it even better. To enable key bindings, source the corresponding file for your shell. For example, for Bash, source /usr/share/fzf/shell/key-bindings.bash:</p><pre>$ source /usr/share/fzf/shell/key-bindings.bash</pre><p>You can also add this line to your shell initialization file to make it permanent. If you don’t have this file, download it directly from the project’s <a href="https://github.com/junegunn/fzf/tree/master/shell">repository.</a></p><p>Once you load this file, you can use three key bindings to quickly trigger fzf:</p><ul><li><strong>Ctrl+t</strong>: To select files, similar to autocompletion but with fewer keystrokes</li><li><strong>Alt+c</strong>: To quickly switch into a selected subdirectory</li></ul><p>For example, imagine you want to switch to the directory dnsmasq.d under /etc/NetworkManager, starting from the root directory:</p><figure><a href="https://asciinema.org/a/H8d027jpxq7KnwXJhz3VFdZMd"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkEhzCKTB1W0eLRpDFuKtw.png" /></a></figure><ul><li><strong>Ctrl+r</strong>: For smart searching your command history</li></ul><p>This is one of the most useful fzf applications. This key binding replaces the default history search with a smart search that makes you more efficient at retrieving previously executed commands.</p><p>For example, using the standard history search, you need to type exactly what you&#39;re looking for, or the search fails. It&#39;s hard to find long previous commands this way. Using fzf gets where you want with a few keystrokes:</p><figure><a href="https://asciinema.org/a/xVNL2TBVWRRUgSlP4Q5f4vmaA"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ww7OqenigefTc15cCIlfA.png" /></a></figure><p>Using these key bindings and fzf&#39;s blazing-fast search, you can move around your command line much more efficiently, as well as find and execute previous commands in no time. With a bit of practice, it feels like you have new superpowers.</p><h3>Other Ways to Use This Powerful Tool</h3><p>fzf is a powerful and versatile tool that helps me improve my command-line efficiency dramatically. I am grateful to have access to such a tool.</p><p>fzf can do much more than what I explored in this article. It follows the <a href="https://opensource.com/article/18/11/revisiting-unix-philosophy-2018">Unix philosophy</a> of doing one thing and doing it well. But this one thing allows you to use fzf in different ways.</p><p>In my next article, I will show how to use fzf for other useful purposes, like filtering packages or as a pseudo user interface for scripts. You can also customize fzf to change its appearance, colors, position, and more. If you can&#39;t wait, take a look at the project&#39;s <a href="https://github.com/junegunn/fzf/wiki">wiki page</a> for more ideas and examples from the community.</p><p>Check out <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Ricardo’s book</a>, published by The Pragmatic Bookshelf.</p><p><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></p><p>Write your own fast, reliable, and cross-platform command-line tools with the Go programming language.</p><figure><img alt="Book cover featuring shadow hands with tools on a streaked blue background" src="https://cdn-images-1.medium.com/max/250/0*MhgIu3kJZj3-_AxX.jpg" /><figcaption>This article was originally published at https://redhat.com/sysadmin/fzf-linux-fuzzy-finder on November 25, 2022.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f48dfd0092b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/find-anything-you-need-with-fzf-the-linux-fuzzy-finder-tool-f48dfd0092b4">Find anything you need with fzf, the Linux fuzzy finder tool</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Tips for Technical Certification Exams]]></title>
            <link>https://medium.com/pragmatic-programmers/five-tips-for-technical-certification-exams-9fee6fb24cdd?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fee6fb24cdd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[certification]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[tips]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Tue, 30 May 2023 12:04:59 GMT</pubDate>
            <atom:updated>2023-05-30T12:04:59.806Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*v1ZPoRww-Uy8YD2Y" /><figcaption><em>Photo by </em><a href="https://www.pexels.com/@magda-ehlers-pexels?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>Magda Ehlers</em></strong></a><em> from </em><a href="https://www.pexels.com/photo/numbers-wall-decor-1329292/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels"><strong><em>Pexels</em></strong></a></figcaption></figure><h4>Prepare Yourself and Take the Exam with Confidence</h4><blockquote>Five ways you can better prepare yourself for hands-on, technical certification exams.</blockquote><figure><img alt="https://pragprog.com/newsletter/" src="https://cdn-images-1.medium.com/max/1024/1*KvVW4vtyKwkcPUgF1SVFIA.png" /><figcaption><a href="https://pragprog.com/newsletter/">https://pragprog.com/newsletter/</a></figcaption></figure><pre>In this article:<br>* <a href="#079f">Be Informed</a><br>* <a href="#e940">Be Prepared</a><br>* <a href="#c9e8">Manage Your Time</a><br>* <a href="#e1fd">Understand the Environment</a><br>* <a href="http://f7da/">Use the Documentation</a><br>* <a href="#cb76">What&#39;s Next?</a></pre><p>As a sysadmin and a consultant, I’m constantly looking for ways to learn new things and keep updated with the latest technologies. In addition to training and self-learning, completing a technical certification program is a good way to learn, sharpen, and demonstrate your skills.</p><p>A technical certification can:</p><ul><li>Help you find new opportunities or get promoted.</li><li>Help you get a new job.</li><li>When just starting out, demonstrate that you have a set of technical skills in the absence of experience.</li><li>Demonstrate your commitment to a goal, dedication, and willingness to learn.</li></ul><p>I recently completed a technical certification program. It was a great experience and I learned a lot during the process. In this article, I’ll share some of this experience and provide a few tips to help aspiring candidates obtain their certifications. This article focuses on practical certifications that require you to demonstrate your skills by completing a set of tasks instead of answering questions.</p><p>Due to their hands-on nature, these technical certification programs are usually demanding. However, with the necessary experience and correct preparation, you should be able to pass the exam. Following these tips doesn’t guarantee passing it, but they will help you understand the expectations and assist you with your preparation.</p><h3>1. Be Informed</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2XrdYltHeqBJMpRnjfEjw.jpeg" /></figure><p>This point may sound trivial, but it’s important. Read and understand the certification requirements and rules before you start your preparation so you know where to focus your efforts. Even if you’re an experienced professional, understand exactly what the certification expects you to demonstrate, as you may not use some of these skills frequently in your day job.</p><p>A few days before the exam, re-read all the rules and requirements to ensure you have everything covered.</p><p>For remote exams, you’ll need to use your own computer. Verify that all the exam’s hardware and software requirements are met to ensure that your computer is ready for the exam. If the certification platform provides a compatibility test tool, run it a few days in advance, allowing you time to address any incompatibilities or reschedule your test if necessary. Don’t leave this task to the last minute or you may be unable to take or even reschedule the test.</p><h3>2. Be Prepared</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*aryo4nLE6rCkuwZBhMU8xw.jpeg" /></figure><p>For hands-on exams, instead of answering questions, you need to demonstrate the required skills by completing a set of tasks in a given amount of time. Some of these tasks might not be complex but, combined with the time component, they make the exams challenging.</p><p>Study the domains and skills required to pass the exam as listed on the certification information page. Remember that you might not have time to research a topic or attempt to solve it by trial and error due to time constraints during the exam.</p><p>In general, to demonstrate a skill, it’s not enough to have a general idea about it. You need to complete a task by creating, managing, editing or deleting required objects, manipulating command line tools, dealing with configuration files, APIs, and so on. If possible, spin up your own lab environment to practice these skills until you’re comfortable with them. Then, practice with a timer to gauge how long you take to complete them.</p><p>When spinning up your lab environment to practice, be sure to use the same Linux distribution and other required software versions listed on your exam’s information page. Exams may change software versions frequently to align with the latest release available. Always look for the correct software requirements in the confirmation email or exam’s Frequently Asked Questions (FAQ) page.</p><h3>3. Manage Your Time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*jOL0Yie2ln2KH1pHduC9-A.png" /></figure><p>If you’re taking the test in a test center, plan to arrive there at least 30 minutes to one hour in advance. Don’t give yourself more reasons to stress.</p><p>If you’re taking a test remotely using your computer, reboot it 30 minutes before starting the exam to ensure you have a stable environment. In general, you can join the exam 15 minutes prior to the scheduled time. Use that time to review the interface and go over the admission process with your proctor.</p><p>Remember, you have a limited time to complete the exam. The amount of time varies for each test, but usually — it’s not a lot. Manage your time wisely during the test. If you have doubts about a particular task, flag it and return to it later. Don’t spend a long time in the beginning investigating a task you’re unsure about or you may not have time to complete the remaining tasks. Complete the tasks you’re certain of and then come back to the ones you flagged and invest some additional time on them.</p><p>Read the tasks completely before attempting to solve them. It’s worth investing a few seconds more to read rather than having to re-do a task due to a missed detail.</p><p>Be sure you go back and complete all the flagged tasks before finishing your exam.</p><p>During your exam, you can ask for a break, but the timer continues to run. For short exams — one or two hours — use the restroom before starting your exam. For longer exams — three or four hours — it might be a good idea to ask for a five-minute break just to rest your mind and stretch your legs.</p><h3>4. Understand the Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Wq7wU3iWnEj2hQ9foIoIXw.jpeg" /></figure><p>Certification testing centers use different test environments. Some provide access to one or more virtual machines that you can connect to; some provide access to a command line terminal; and some require that you do everything in a browser. Regardless of which environment they offer, it will be different from what you’re used to working with. Keep in mind that there will be limitations compared to doing the same tasks in your home lab. Understanding these differences is critical to helping you perform well.</p><p>Check details about the exam environment on their information page. Take one or two minutes at the beginning of the test to get acquainted with the environment. Learn how to navigate the tasks, flag them to return, access the required command line terminal, browser, and how to ask for help.</p><p>A few extra tips:</p><ul><li>If you’re using a terminal on a browser, some text editors such as Vim might not work well — for example, typing keys like <strong>ESC</strong> may not work. Practice using a simpler terminal editor such as Nano.</li><li>Copy and paste keys such as <strong>Ctrl-C</strong> and <strong>Ctrl+V</strong> might not work in the test environment. Review the supported ways to copy and paste information for the specific test.</li><li>When using a browser, do not use <strong>Ctrl+W</strong> as it closes your browser tab, and it could cause delays with the test.</li><li>Generally speaking, the tasks contain copyable text such as resource names, file names, port numbers, or other relevant values. Copy then paste them on the terminal to avoid mistyping a required value when executing a task.</li></ul><p>Overall, keep in mind you might not be able to type in the exam environment with the same speed you do on your own systems. Account for that during your preparation.</p><h3>5. Use the Documentation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tKG0QtEBTLkXL0P6HVFMxA.jpeg" /></figure><p>Many certifications allow you to consult authorized documentation during the exam. Always check what you’re allowed to consult on the exam’s information page.</p><p>If you’re allowed to use documentation, it’s usually your responsibility to ensure that you don’t navigate to any pages outside of the ones that are authorized, even if it’s a link in one of them.</p><p>Since you have access to the documentation, you’re not required to memorize everything, but you also don’t have time to research something you’re not familiar with. Be prepared for the test, and make sure you know how to navigate the documentation to find the resources you need during the exam.</p><h3>What’s Next?</h3><p>Now it’s your turn. Put these tips into practice, prepare yourself, and take the exam with confidence. Good luck on your tests, and I hope you’re soon a Certified Professional.</p><p>Check out <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Ricardo’s book</a>, published by The Pragmatic Bookshelf.</p><p><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></p><p>Write your own fast, reliable, and cross-platform command-line tools with the Go programming language.</p><figure><img alt="Book cover featuring shadow hands with tools on a streaked blue background" src="https://cdn-images-1.medium.com/max/250/0*MhgIu3kJZj3-_AxX.jpg" /><figcaption>Book cover image by The Pragmatic Programmers. This article was originally published at <a href="https://www.redhat.com/sysadmin/5-tips-certification-exams">https://www.redhat.com</a> on March 31, 2021.</figcaption></figure><p>Note: Images in this article, other than those otherwise noted, were licensed via Shutterstock.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fee6fb24cdd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/five-tips-for-technical-certification-exams-9fee6fb24cdd">Five Tips for Technical Certification Exams</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Guide to tmux]]></title>
            <link>https://medium.com/pragmatic-programmers/a-beginners-guide-to-tmux-7e6daa5c0154?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e6daa5c0154</guid>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[tmux]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Wed, 17 May 2023 10:32:17 GMT</pubDate>
            <atom:updated>2023-05-17T10:32:17.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIaS5C_mAbJugCtd5J-H6Q.png" /><figcaption>Logo by Jason Long, <a href="http://www.isc.org/downloads/software-support-policy/isc-license">ISC</a>, via Wikimedia Commons</figcaption></figure><h4>Make the Most of Your Terminal Sessions</h4><blockquote>Make your Linux terminal more useful with tmux, a terminal multiplexer that allows you to run multiple Linux programs over a single connection.</blockquote><figure><img alt="https://pragprog.com/newsletter/" src="https://cdn-images-1.medium.com/max/1024/1*KvVW4vtyKwkcPUgF1SVFIA.png" /><figcaption><a href="https://pragprog.com/newsletter/">https://pragprog.com/newsletter/</a></figcaption></figure><pre>In this article:<br>- <a href="#d56e">Install tmux</a><br>- <a href="#9bd0">Get Started with tmux</a><br>- <a href="#9321">Basic tmux Keybindings</a><br>- <a href="#9321">Use the Mouse</a><br>- <a href="#658b">Configure tmux</a><br>- <a href="#00f4">Customize the Status Bar</a><br>- <a href="#95bd">What&#39;s Next?</a></pre><p>Tmux is a terminal multiplexer; it allows you to create several “pseudo terminals” from a single terminal. This is very useful for running multiple programs with a single connection, such as when you’re remotely connecting to a machine using <a href="https://www.redhat.com/sysadmin/access-remote-systems-ssh">Secure Shell (SSH)</a>.</p><p>Tmux also decouples your programs from the main terminal, protecting them from accidentally disconnecting. You can detach tmux from the current terminal, and all your programs will continue to run safely in the background. Later, you can reattach tmux to the same or a different terminal.</p><p>In addition to its benefits with remote connections, tmux’s speed and flexibility make it a fantastic tool to manage multiple terminals on your local machine, similar to a window manager. I’ve been using tmux on my laptops for over eight years. Some of tmux’s features that help me and increase my productivity include:</p><ul><li>Fully customizable status bar</li><li>Multiple window management</li><li>Splitting window in several panes</li><li>Automatic layouts</li><li>Panel synchronization</li><li>Scriptability, which allows me to create custom tmux sessions for different purposes</li></ul><p>Here’s an example of a customized tmux session:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I60A-ZDfCZcIm8UnalKe8w.png" /></figure><p>Tmux offers some of the same functionality found in <a href="https://www.gnu.org/software/screen/">Screen</a>, which has been deprecated in some Linux distributions. Tmux has a more modern code base than Screen and offers additional customization capabilities.</p><p>Now that you know some of tmux’s benefits, I’ll show you how to install and use it.</p><h3>Install tmux</h3><p>Tmux is available in the standard repositories with Fedora and Red Hat Enterprise Linux (RHEL) starting with RHEL 8. You can install it using dnf:</p><pre>$ sudo dnf -y install tmux</pre><p>It’s also available with many other Linux distributions, and you should be able to install it by using your favorite distribution package manager. For other operating systems, consult the <a href="https://github.com/tmux/tmux/wiki/Installing">tmux installation guide</a>.</p><h3>Get Started with tmux</h3><p>To start using tmux, type tmux on your terminal. This command launches a tmux server, creates a default session (number 0) with a single window, and attaches to it.</p><pre>$ tmux</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*6kgMlgQnu-0Vp5Ec7UAXeg.png" /></figure><p>Now that you’re connected to tmux, you can run any commands or programs as you normally would. For example, to simulate a long-running process:</p><pre>$ c=1<br><br>$ while true; do echo &quot;Hello $c&quot;; let c=c+1; sleep 1; done<br>Hello 1<br>Hello 2<br>Hello 3</pre><p>You can detach from your tmux session by pressing <strong>Ctrl+B</strong> then <strong>D</strong>. Tmux operates using a series of keybindings (keyboard shortcuts) triggered by pressing the “prefix” combination. By default, the prefix is <strong>Ctrl+B</strong>. After that, press <strong>D</strong> to detach from the current session.</p><pre>[detached (from session 0)]</pre><p>You’re no longer attached to the session, but your long-running command executes safely in the background. You can list active tmux sessions with tmux ls:</p><pre>$ tmux ls<br><br>0: 1 windows (created Sat Aug 27 20:54:58 2022)</pre><p>You can disconnect your SSH connection at this point, and the command will continue to run. When you’re ready, reconnect to the server and reattach to the existing tmux session to resume where you left off:</p><pre>$ tmux attach -t 0<br>Hello 72<br>Hello 73<br>Hello 74<br>Hello 75<br>Hello 76<br>^C</pre><p>As you can see, the command continued to run and print messages on the screen. You can type <strong>Ctrl+C</strong> to cancel it.</p><p>All tmux commands can also be abbreviated, so, for example, you can enter tmux a , and it will work the same as tmux attach.</p><p>This functionality alone makes tmux a great tool, but it has even more to offer, including its default keybindings.</p><h3>Basic tmux Keybindings</h3><p>Tmux provides several keybindings to execute commands quickly in a tmux session. Here are some of the most useful ones.</p><p>First, create a new tmux session if you’re not already in one. You can name your session by passing the parameter -s {name} to the tmux new command when creating a new session:</p><pre>$ tmux new -s Session1</pre><pre>+=========================+=============================================+<br>|       <strong>Keybinding</strong>        |                 <strong>Description</strong>                 |<br>+=========================+=============================================+<br>| <strong>Ctrl+B D </strong>               | Detach from current session                 |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B %</strong>                | Split window into 2 panes horizontally      |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B &quot;</strong>                | Split window into 2 panes vertically        |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B Arrow Key</strong>        | Move between panes                          |<br>|  (LEFT,RIGHT,UP,DOWN)   |                                             |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B X</strong>                | Close pane                                  |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B C</strong>                | Create a new window                         |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B N</strong> (or <strong>P</strong>)         | Move to next or previous window             |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B 0 (1,2...)</strong>       | Move to specific window by number           |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B :</strong>                | Enter command line to type commands.        |<br>|                         | Tab completion available                    |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B ?</strong>                | View all key bindings. Press &quot;Q&quot; to exit    |<br>+-------------------------+---------------------------------------------+<br>| <strong>Ctrl+B W</strong>                | Open a panel to navigate across windows     |<br>|                         | in multiple sessions                        |<br>+-------------------------+----------------------------------------------<br></pre><p>For additional keybindings, consult tmux man pages.</p><h3>Use the Mouse</h3><p>Tmux is most often used with the keyboard, and it provides many keybindings to make it easier to execute commands, create new panes, and resize them. If you prefer using the mouse, tmux also allows that, although the mouse is disabled by default. To enable it, first enter command mode by typing <strong>Ctrl+B :</strong>, then toggle the mouse on (or off) with the command set -g mouse.</p><p>Now you can use the mouse to switch between panes and windows and resize them. Starting with tmux version 3, you can also right-click with the mouse and open a context menu:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*uze3D6etVzSHTcpkm8QbbQ.png" /></figure><p>This menu changes according to what’s on the screen under the mouse cursor when clicked.</p><h3>Configure tmux</h3><p>You can change the tmux configuration permanently by modifying the tmux configuration file. By default, this file is located at $HOME/.tmux.conf.</p><p>For example, the default prefix key combination is <strong>Ctrl+B</strong>, but sometimes this combination is a little awkward to press, and it requires both hands. You can change it to something different by editing the configuration file. I like to set the prefix key to <strong>Ctrl+A</strong>. To do this, create a new configuration file and add these lines to it:</p><pre>$ vi $HOME/.tmux.conf<br><br># Set the prefix to Ctrl+a<br>set -g prefix C-a<br><br># Remove the old prefix<br>unbind C-b<br><br># Send Ctrl+a to applications by pressing it twice<br>bind C-a send-prefix<br><br>:wq</pre><p>When you start a tmux session on this machine, you can execute the commands listed above by pressing <strong>Ctrl+A</strong>first. Use the configuration file to change or add other tmux keybindings and commands.</p><h3>Customize the Status Bar</h3><p>Tmux’s status bar is fully customizable. You can change the colors of each section and what is displayed. There are so many options that it would require another article to cover them, so I’ll start with the basics.</p><p>The standard green color for the entire status bar makes it difficult to see the different sections. It’s particularly difficult to see how many windows you have open and which one is active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*tozNKjEmrV88wzystZcGFw.png" /></figure><p>You can change that by updating the status bar colors. First, enter command mode by typing <strong>Ctrl+B :</strong> (or <strong>Ctrl+A :</strong> if you made the prefix configuration change above). Then change the colors with these commands:</p><ul><li>Change the status bar background color: set -g status-bg cyan</li><li>Change inactive window color: set -g window-status-style bg=yellow</li><li>Change active window color: set -g window-status-current-style bg=red,fg=white</li></ul><p>Add these commands to your configuration file for permanent changes.</p><p>With this configuration in place, your status bar looks nicer and it’s much easier to see which window is active:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*djAKWXBKQ5xZd8bS-VeXbg.png" /></figure><h3>What’s Next?</h3><p>Tmux is a fantastic tool to safeguard your remote connections and is useful when you spend a long time using the terminal. This article covers only the basic functionality, and there is much more to explore. For additional information about tmux, consult its official <a href="https://github.com/tmux/tmux/wiki">wiki page</a>.</p><p>You can also expand tmux’s functionality with extra-official plugins. These plugins add more commands, integrate with applications such as Vim, and add new functionality to the status bar. For more information, consult the <a href="https://github.com/tmux-plugins/list">tmux plugins project</a>.</p><p>Check out <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Ricardo’s book</a>, published by The Pragmatic Bookshelf.</p><p><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></p><p>Write your own fast, reliable, and cross-platform command-line tools with the Go programming language.</p><figure><img alt="Book cover featuring shadow hands with tools on a streaked blue background" src="https://cdn-images-1.medium.com/max/250/0*MhgIu3kJZj3-_AxX.jpg" /><figcaption>This article was originally published at <a href="https://www.redhat.com/sysadmin/introduction-tmux-linux">https://www.redhat.com</a> on September 13, 2022.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e6daa5c0154" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/a-beginners-guide-to-tmux-7e6daa5c0154">A Beginner’s Guide to tmux</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eight Git Aliases That Make Me More Efficient]]></title>
            <link>https://medium.com/pragmatic-programmers/8-git-aliases-that-make-me-more-efficient-9150eb637061?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9150eb637061</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[command-line]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Sat, 29 Apr 2023 16:50:08 GMT</pubDate>
            <atom:updated>2023-05-22T16:07:01.892Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/520/0*uWhqpYbIlX7nZkQx.jpg" /><figcaption><em>Image by </em><a href="https://pixabay.com/en/users/iradaturrahmat-3964359/"><em>iradaturrahmat </em></a><em>via </em><a href="https://pixabay.com/en/ubuntu-computer-program-interface-3145957/"><em>Pixabay</em></a><em>, CC0</em></figcaption></figure><h4>Learn to Shorten and Simplify Your Commands</h4><blockquote>Use aliases to create shortcuts for your most-used or complex Git commands.</blockquote><figure><img alt="https://pragprog.com/newsletter/" src="https://cdn-images-1.medium.com/max/1024/1*KvVW4vtyKwkcPUgF1SVFIA.png" /><figcaption>Image by: <a href="https://pixabay.com/en/users/iradaturrahmat-3964359/">iradaturrahmat</a> via <a href="https://pixabay.com/en/ubuntu-computer-program-interface-3145957/">Pixabay</a>, CC0</figcaption></figure><pre>In this article:<br>* <a href="#1538">How to Define and Use Aliases</a><br>* <a href="#cac8">Eight Useful Git Aliases</a><br>     1. <a href="#bd83">Git status</a><br>     2. <a href="#49c4">Git log in one line</a><br>     3. <a href="#39bd">Git last commit</a><br>     4. <a href="#f545">Git commit</a><br>     5. <a href="#f269">Git remote</a><br>     6. <a href="#a862">Git diff</a><br>     7. <a href="#2936">Git config list</a><br>     8. <a href="#c76a">Git search commit</a><br>* <a href="#77f0">Auto-Correct Your Aliases</a><br>* <a href="#f35a">Optimize Git Commands</a></pre><p>The excellent article <a href="https://opensource.com/article/20/10/advanced-git-tips"><em>7 Git tricks that changed my life</em></a> inspired me to write about another Git feature that’s had a major impact on my experience using Git on the command line: <em>aliases</em>.</p><p>Defining Git aliases to serve as substitutes for commands provides two major benefits:</p><ul><li>It simplifies long commands that have many options, making them shorter and easier to remember.</li><li>It shortens frequently used commands so that you can work more efficiently.</li></ul><h3>How to Define and Use Aliases</h3><p>To define a Git alias, use the git config command with the alias and the command you want to substitute. For example, to create the alias p for git push:</p><pre>$ git config --global alias.p &#39;push&#39;</pre><p>You can use an alias by providing it as an argument to git, just like any other command:</p><pre>$ git p</pre><p>To see all your aliases, list your configuration with git config:</p><pre>$ git config --global -l<br>user.name=ricardo<br>user.email=ricardo@example.com<br>alias.p=push</pre><p>You can also define aliases with your favorite shell, such as Bash or Zsh. However, defining aliases using Git offers several features that you don’t get using the shell. First, it allows you to use aliases across different shells with no additional configuration. It also integrates with Git’s autocorrect feature, so Git can suggest aliases as alternatives when you mistype a command. Finally, Git saves your aliases in the user configuration file, allowing you to transfer them to other machines by copying a single file.</p><p>Regardless of the method you use, defining aliases improves your overall experience with Git. For more information about defining Git aliases, take a look at the <a href="https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases">Git Book</a>.</p><h3>Eight Useful Git Aliases</h3><p>Now that you know how to create and use an alias, take a look at some useful ones.</p><h4>1. Git status</h4><p>Git command line users often use the status command to see changed or untracked files. By default, this command provides verbose output with many lines, which you may not want or need. You can use a single alias to address both of these components: Define the alias st to shorten the command with the option -sb to output a less verbose status with branch information:</p><pre>$ git config --global alias.st &#39;status -sb&#39;</pre><p>If you use this alias on a clean branch, your output looks like this:</p><pre>$ git st <br>## No commits yet on main</pre><p>Using it on a branch with changed and untracked files produces this output:</p><pre>$ git st <br>## main<br> M test2<br>?? test3</pre><h4>2. Git log in one line</h4><p>Create an alias to display your commits as single lines for more compact output:</p><pre>$ git config --global alias.ll &#39;log --oneline&#39;</pre><p>Using this alias provides a short list of all commits:</p><pre>$ git ll<br>33559c5 (HEAD -&gt; main) Another commit<br>17646c1 test1</pre><h4>3. Git last commit</h4><p>This command shows details about the most recent commit you made. The following extends an example in the Git Book’s chapter on <a href="https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases">Aliases</a>:</p><pre>$ git config --global alias.last &#39;log -1 HEAD --stat&#39;</pre><p>Use it to see the last commit:</p><pre>$ git last<br>commit f3dddcbaabb928f84f45131ea5be88dcf0692783 (HEAD -&gt; branch1)<br>Author: ricardo &lt;ricardo@example.com&gt;<br>Date:   Tue Nov 3 00:19:52 2020 +0000<br><br>    Commit to branch1<br><br> test2 | 1 +<br> test3 | 0<br> 2 files changed, 1 insertion(+)</pre><h4>4. Git commit</h4><p>You use git commit a lot when you&#39;re making changes to a Git repository. Make the git commit -m command more efficient with the cm alias:</p><pre>$ git config --global alias.cm &#39;commit -m&#39;</pre><p>Because Git aliases expand commands, you can provide additional parameters during their execution:</p><pre>$ git cm &quot;A nice commit message&quot;<br>[branch1 0baa729] A nice commit message<br> 1 file changed, 2 insertions(+)</pre><h4>5. Git remote</h4><p>The git remote -v command lists all configured remote repositories. Shorten it with the alias rv:</p><pre>$ git config --global alias.rv &#39;remote -v&#39;</pre><h4>6. Git diff</h4><p>The git diff command displays differences between files in different commits or between a commit and the working tree. Simplify it with the d alias:</p><pre>$ git config --global alias.d &#39;diff&#39;</pre><p>The standard git diff command works fine for small changes. But for more complex ones, an external tool such as vimdiff makes it more useful. Create the alias dv to display diffs using vimdiff and use the -y parameter to skip the confirmation prompt:</p><pre>$ git config --global alias.dv &#39;difftool -t vimdiff -y&#39;</pre><p>Use this alias to display file1 differences between two commits:</p><pre>$ git dv 33559c5 ca1494d file1</pre><figure><img alt="Display file differences in Git using vimdiff" src="https://cdn-images-1.medium.com/max/769/1*ZsoIcxIO5HNW-KUlC5l_HA.png" /></figure><h4>7. Git config list</h4><p>The gl alias makes it easier to list all user configurations:</p><pre>$ git config --global alias.gl &#39;config --global -l&#39;</pre><p>Now you can see all defined aliases (and other configuration options):</p><pre>$ git gl<br>user.name=ricardo<br>user.email=ricardo@example.com<br>alias.p=push<br>alias.st=status -sb<br>alias.ll=log --oneline<br>alias.last=log -1 HEAD --stat<br>alias.cm=commit -m<br>alias.rv=remote -v<br>alias.d=diff<br>alias.dv=difftool -t vimdiff -y<br>alias.gl=config --global -l<br>alias.se=!git rev-list --all | xargs git grep -F</pre><h4>8. Git search commit</h4><p>Git alias allows you to define more complex aliases, such as executing external shell commands, by prefixing them with the ! character. You can use this command to execute custom scripts or more complex commands, including shell pipes.</p><p>For example, define the se alias to search within your commits:</p><pre>$ git config --global alias.se &#39;!git rev-list --all | xargs git grep -F&#39;</pre><p>Use this alias to search for specific strings in your commits:</p><pre>$ git se test2<br>0baa729c1d683201d0500b0e2f9c408df8f9a366:file1:test2<br>ca1494dd06633f08519ec43b57e25c30b1c78b32:file1:test2</pre><h3>Auto-Correct Your Aliases</h3><p>A cool benefit of using Git aliases is its native integration with the auto-correct feature. If you make a mistake, by default Git suggests commands that are similar to what you typed, including aliases. For example, if you type ts instead of st for status, Git will suggest the correct alias:</p><pre>$ git ts<br>git: &#39;ts&#39; is not a git command. See &#39;git --help&#39;.<br><br>The most similar command is<br>        st</pre><p>If you have auto-correct enabled, Git will automatically execute the correct command:</p><pre>$ git config --global help.autocorrect 20<br>$ git ts<br>WARNING: You called a Git command named &#39;ts&#39;, which does not exist.<br>Continuing in 2.0 seconds, assuming that you meant &#39;st&#39;.<br>## branch1<br>?? test4</pre><h3>Optimize Git Commands</h3><p>Git alias is a useful feature that improves your efficiency by optimizing the execution of common and repetitive commands. Git allows you to define as many aliases as you want, and some users define many. I prefer to define aliases for just my most used commands. Defining too many aliases makes it harder to memorize them and may require me to look them up to use them.</p><p>For more about aliases, including other useful ones, see the <a href="https://git.wiki.kernel.org/index.php/Aliases">Git Wiki’s Aliases page</a>.</p><p>Check out <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Ricardo’s book</a>, published by The Pragmatic Bookshelf.</p><p><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></p><p>Write your own fast, reliable, and cross-platform command-line tools with the Go programming language.</p><figure><img alt="Book cover featuring shadow hands with tools on a streaked blue background" src="https://cdn-images-1.medium.com/max/250/0*MhgIu3kJZj3-_AxX.jpg" /><figcaption>This article was originally published at <a href="https://opensource.com/article/20/11/git-aliases">https://opensource.com</a> on November 30, 2020.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9150eb637061" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/8-git-aliases-that-make-me-more-efficient-9150eb637061">Eight Git Aliases That Make Me More Efficient</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Get Started Programming in Go]]></title>
            <link>https://medium.com/pragmatic-programmers/how-to-get-started-programming-in-go-4122f8e48e7a?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/4122f8e48e7a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Thu, 10 Nov 2022 10:02:18 GMT</pubDate>
            <atom:updated>2023-05-04T13:36:14.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Al1UeA53yPumn1vV" /><figcaption><em>Photo by Eliobed Suarez on </em><a href="https://unsplash.com/photos/PN-YnI5stdQ"><em>Unsplash</em></a></figcaption></figure><blockquote>Go is an open source programming language that combines a dynamic language’s ease of use with the reliability and performance of a statically typed, compiled language.</blockquote><figure><img alt="https://pragprog.com/newsletter/" src="https://cdn-images-1.medium.com/max/1024/1*KvVW4vtyKwkcPUgF1SVFIA.png" /><figcaption><a href="https://pragprog.com/newsletter/">https://pragprog.com/newsletter/</a></figcaption></figure><pre>In this article:<br>- <a href="#e127">Benefits of the Go Programming Language</a><br>- <a href="#7513">Install Go</a><br>- <a href="#d97b">Initialize a Go Project</a><br>- <a href="#97bd">Use Packages and Imports in Go</a><br>- <a href="#5272">Use the main Function</a><br>- <a href="#2526">Run a Go Application</a><br>- <a href="#1acb">Compile a Go Application</a><br>- <a href="#7f96">What&#39;s Next?</a></pre><p>If you’re a sysadmin, you probably write a lot of scripts to perform everyday tasks or automate some of your administration work. You probably accomplish this through a <a href="https://www.redhat.com/sysadmin/learn-bash-scripting">shell script</a> using a scripting language such as <a href="https://www.redhat.com/sysadmin/bash-navigation">Bash</a>, or a programming language like <a href="https://www.redhat.com/sysadmin/python-scripting-intro">Python</a> or <a href="https://opensource.com/article/22/2/perl-cheat-sheet">Perl</a>.</p><p>Python and Perl are interpreted languages, which have limitations. Some of these limitations include:</p><ul><li>A particular version of an interpreter must be available both when writing and executing code.</li><li>Dependencies must be available, both at write time and execution time.</li><li>Many errors are seen only at runtime, causing your program to stop or break.</li><li>There can be resource utilization and performance issues for some workloads.</li></ul><p>A few years ago, I was working on a project, and I couldn’t use Perl due to these limitations. I needed a new language. That’s when I found <a href="https://go.dev/">Go</a>.</p><h3>Benefits of the Go Programming Language</h3><p>Go is an open source programming language combining the ease of use provided by dynamic languages with the reliability and performance provided by statically typed, compiled languages. Even though Go is statically typed (meaning variable types are predefined and known at compile time), the Go compiler can infer those for you, so it often feels like you’re programming in a dynamic language like Python. This makes Go relatively easy to get started with, but it provides the reliability of type validation, which prevents many common runtime errors seen in dynamic languages.</p><p>Compiled Go programs provide resource utilization and performance similar to those written in C, but you don’t have to deal with low-level issues like memory management. In addition, Go programs compile to static binaries requiring no dependencies or interpreters at runtime. You can compile your program in your development machine, copy the resulting file to the execution machines, and run it.</p><p>Go provides other features, including:</p><ul><li>A mature and comprehensive standard library and third-party packages</li><li>Cross-compilation that lets you write and compile programs for different platforms from a single environment</li><li>Built-in concurrency, so you can use the resources available on your system</li><li>A complete set of tools, including testing, linting, code validation, and completion</li></ul><p>Go is the language of choice for many modern tools, including container management tools such as <a href="https://www.redhat.com/en/topics/containers/what-is-podman?intcmp=701f20000012ngPAAQ">Podman</a>, <a href="https://www.redhat.com/en/topics/containers/what-is-kubernetes?intcmp=701f20000012ngPAAQ">Kubernetes</a>, and <a href="https://www.redhat.com/en/technologies/cloud-computing/openshift?intcmp=701f20000012ngPAAQ">OpenShift</a>.</p><p>Due to these features and benefits, Go fills a gap for people who don’t program all the time but require a powerful and flexible programming language. Go is a great choice of language for network engineers and sysadmins.</p><h3>Install Go</h3><p>On Linux, use your distribution’s package manager to install Go (often named golang):</p><pre>$ sudo dnf install golang</pre><p>Alternatively, you can download and install it from the official <a href="https://go.dev/dl/">Go download webpage</a>. At the time I’m writing this article, the latest version of Go is 1.19.1. To download this specific version, use curl:</p><pre>$ curl -sLO https://go.dev/dl/go1.19.1.linux-amd64.tar.gz \ <br>    --output-dir /tmp/</pre><p>Then unarchive this file under /usr/local. If you&#39;ve installed Go previously this way, delete the existing installation first:</p><pre>$ sudo rm -rf /usr/local/go<br>$ sudo tar -xzvf /tmp/go1.19.1.linux-amd64.tar.gz -C /usr/local/</pre><p>Finally, add /usr/local/go/bin to your PATH by adding the following line to your shell&#39;s profile. For example, for Bash, add it to ~/.bash_profile:</p><pre>export PATH=/usr/local/go/bin/:$PATH</pre><p>Reload your terminal profile, open another terminal, or log out and back in to make this setting effective. When the variable is set, test Go by running the go version command:</p><pre>$ go version<br>go version go1.19.1 linux/amd64</pre><p>Now you’re ready to start developing your programs in Go.</p><h3>Initialize a Go Project</h3><p>To start writing your first Go program, create a folder for your project, and change directory into it:</p><pre>$ mkdir greet <br>$ cd greet</pre><p>Go uses <a href="https://go.dev/blog/using-go-modules">modules </a>to manage a project’s dependencies. Generally, a module name has to be unique, so by convention, many developers use the name of their source code repository as the module name. For this example, use the module name example/greet.</p><p>Initialize your new module:</p><pre>$ go mod init example/greet<br>go: creating new go.mod: module example/greet</pre><h3>Use Packages and Imports in Go</h3><p>Go organizes projects into packages, where each package is a set of related functionalities. To create an executable program, define a package named main with a function called main(). This defines the starting point of your program.</p><p>Here’s the start of a common Go program:</p><pre>package main<br><br>import (<br>        &quot;fmt&quot;<br>        &quot;os&quot;<br>        &quot;os/user&quot;<br>)</pre><p>The import keyword imports functionality from other packages. In this example, you import three packages from the standard library:</p><ul><li>fmt provides input and output functions, including functions to print values onscreen.</li><li>os provides an interface to your operating system, providing appropriate exit codes.</li><li>os/user allows you to manage system users.</li></ul><h3>Use the main Function</h3><p>This sample Go program gets the current user by calling the function user.Current() from the os/user package and stores the result in a variable called u. Then it verifies whether the function call returns an error. If so, it prints an error message and terminates the program. If there&#39;s no error, then it prints a greeting message to the current user (by name, thanks to u.Username).</p><p>Here’s the code:</p><pre>func main() {<br>        u, err := user.Current()<br>        if err != nil {<br>                fmt.Println(&quot;Cannot get current user:&quot;, err)<br>                os.Exit(1)<br>        }<br><br>        fmt.Printf(&quot;Hello %s, welcome!\n&quot;, u.Username)<br>}</pre><h3>Run a Go Application</h3><p>Save the file and run the program dynamically by using the Go tool go run:</p><pre>$ go run .<br>Hello ricardo, welcome!</pre><h3>Compile a Go Application</h3><p>You can also compile a Go module into a single executable binary with go build:</p><pre>$ go build</pre><p>Then run your greet program by calling it directly:</p><pre>$ ./greet<br>Hello ricardo, welcome!</pre><h3>What’s Next?</h3><p>You’ve written, compiled, and executed your first Go program! There is much more you can do. Go is a programming language with clear benefits and features targeted for network engineers and sysadmins. It’s a great choice for developing command-line tools and automation solutions.</p><p>I’ve been using Go for many years now, developing several command-line applications, such as log file processing, API clients and servers, network management tools, monitoring tools, data collection, and more. I think Go fits sysadmin work so well that I wrote a book about developing command-line applications with Go. If you’re interested in learning more about Go, take a look at <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/"><strong><em>Powerful Command-Line Applications in Go</em></strong></a>.</p><p>In the next article in this series, I’ll explore some additional concepts from the Go programming language.</p><p>If you enjoyed this article, you might also enjoy <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Ricardo’s book</a>, published by The Pragmatic Bookshelf.</p><p><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></p><p>Write your own fast, reliable, and cross-platform command-line tools with the Go programming language.</p><figure><img alt="Book cover featuring shadow hands with tools on a streaked blue background" src="https://cdn-images-1.medium.com/max/250/0*MhgIu3kJZj3-_AxX.jpg" /><figcaption>This article was originally published at <a href="https://www.redhat.com/">https://www.redhat.com</a> on November 10, 2022.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4122f8e48e7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/how-to-get-started-programming-in-go-4122f8e48e7a">How to Get Started Programming in Go</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What's New in Go 1.18]]></title>
            <link>https://medium.com/pragmatic-programmers/whats-new-in-go-1-18-e7773a110202?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7773a110202</guid>
            <category><![CDATA[language]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rggo]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Fri, 25 Feb 2022 11:32:44 GMT</pubDate>
            <atom:updated>2023-04-28T17:57:59.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*YFGCnQTkFcGioPUGxZaAoA.jpeg" /><figcaption>The Go gopher by <a href="http://reneefrench.blogspot.com/">Renee French</a> — <a href="https://creativecommons.org/licenses/by/3.0/">CC 3.0</a>.</figcaption></figure><h4>Generics, Test Fuzzing, Optimization for AMD64, Workspace Mode, and More</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbJT2UyhVRU1USDMcBxaUQ.png" /><figcaption><a href="https://pragprog.com/newsletter/">https://pragprog.com/newsletter/</a></figcaption></figure><p>It is that time of the year again: a new Go release is around the corner. The Go team has just made <a href="https://tip.golang.org/doc/go1.18">Go 1.18 release candidate 1</a> (go1.18rc1) available, with the expectation of releasing Go 1.18 by the end of February 2022.</p><p>Go 1.18 is one of the most anticipated Go releases in a long time, and for good reasons. Go 1.18 implements initial support for generic types and functions, which is the most wanted — and perhaps the most debated — feature by the Go community.</p><p>In addition to Generics, Go 1.18 packs many other great features such as support for testing fuzzing, micro-architecture support and optimization for AMD64 CPU&#39;s, changes to the go tool including support for &quot;workspace&quot; mode, several updates to the core libraries, and many bug fixes and minor updates to the standard library.</p><p>Let&#39;s take a look at some of the main updates.</p><h3>Support for Generics</h3><p>Generics is the most anticipated feature in this release. Go 1.18 supports an initial implementation of generic types and functions according to the <a href="https://go.googlesource.com/proposal/+/refs/heads/master/design/43651-type-parameters.md">Generics proposal</a>. With this new addition, the language supports declaring parameterized types and functions that can be later instantiated with different arguments types.</p><p>The use of generics improves general code re-usability by allowing you to consolidate sets of functions or types that have similar implementation but operate on different input types into single entities that are easier to test and maintain.</p><p>For example, it&#39;s common for some libraries to have code similar to this:</p><pre>func SumInt(a, b int) int {<br>        return a + b<br>}</pre><pre>func SumFloat32(a, b float32) float32 {<br>        return a + b<br>}</pre><pre>func SumFloat64(a, b float64) float64 {<br>        return a + b<br>}</pre><pre>//func sum...</pre><p>By using a generic function, you can consolidate all these functions into a single function:</p><pre>func Sum[T constraints.Ordered]  (a, b T) T {<br>        return a + b<br>}</pre><p>Because this is a major change in the language and it&#39;s a brand new feature, there are some limitations, potentially some performance impacts, and possibly unknown issues. Be mindful of these uncertainties when deploying generic code in production.</p><p>For more information about generics, take a look at the <a href="https://tip.golang.org/doc/go1.18#generics">release notes</a> and the updated <a href="https://tip.golang.org/ref/spec">language specification</a>.</p><h3>Test Fuzzing</h3><p>Another welcome addition to Go 1.18 is the support for test fuzzing. <a href="https://en.wikipedia.org/wiki/Fuzzing">Fuzzing</a> is a software testing strategy that involves providing a large number of random input parameters, including many edge cases, to the code being tested with the goal of catching errors, exposing bugs, triggering exceptions, and discovering vulnerabilities that are otherwise hard for humans to detect.</p><p>Go test fuzzing adds a new type to the testing package testing.F and expands Go&#39;s current features and strategies such as Table Driven Testing. Prior to this release, you could use external libraries to perform test fuzzing but the addition of fuzzing to the standard tooling will provide better support and easier access to more developers.</p><p>🌟 Be aware — the Go team alerts us that the current fuzzing implementation uses a lot of system resources and may impact your system&#39;s performance during execution.</p><p>For additional details, consult the <a href="https://go.dev/doc/fuzz/">Go Fuzzing documentation</a>.</p><h3>Micro-Architecture Optimization for AMD64 CPUs</h3><p>Go 1.18 introduces micro-architecture optimization for AMD64 processors. You can now use the new Go environment variable GOAMD64 to select one of four micro-architecture targets v1, v2, v3, or v4 to instruct the compiler to optimize the resulting binary for specific CPU features. It results in optimized binary instructions that are incompatible with processors that don&#39;t have those features.</p><p>The default value for the variable GOAMD64=v1 results in binary instructions that are compatible with all 64-bit x86 processors.</p><p>For more details about this feature, consult the Architecture section of the <a href="https://github.com/golang/go/wiki/MinimumRequirements#microarchitecture-support">minimum requirements page</a>.</p><h3>Go Workspace Mode</h3><p>Finally, for the last highlighted update, Go 1.18 introduces a new <em>workspace mode</em> support for the go command, which allows you to work on multiple modules at the same time. Previously, working with multiple modules was not easy and could cause issues with the tooling and IDEs. This new feature solves these issues, bringing along changes to other tools, such as gopls, to streamline working with multiple modules.</p><p>With this change, if the go command or tooling finds a file named go.work in the current or a parent directory, it will run in workspace aware mode. It then uses the content of this file to determine which modules to use for dependency resolution instead of using go.mod file.</p><p>In Go 1.18 you can use the go work command to create and manage go.work files. For more information consult its <a href="https://pkg.go.dev/cmd/go@master#hdr-Workspace_maintenance">documentation</a>.</p><p>For a more detailed explanation of the workspace feature and a rundown on many other Go 1.18 improvements, check <a href="https://changelog.com/gotime/217">episode 217 of the Go Time podcast</a>.</p><h3>What&#39;s Next?</h3><p>This article is a quick summary of the main updates coming with Go 1.18, but there are many additional bug fixes and minor improvements to the tooling, compiler, and the standard library. For a complete list, take a look at the <a href="https://tip.golang.org/doc/go1.18">Go 1.18 release notes</a>.</p><p>If you can&#39;t wait for the final release in a couple of weeks and you want to start testing Go 1.18 right now without installing it on your machine, visit the <a href="https://go.dev/play/">Go Playground</a> and select <strong>Go Dev Branch</strong> from the <strong>Go release</strong> drop-down. You can also run it as a container using Podman or Docker.</p><p>If you prefer to have it installed on your machine so you can test with some of your code, download Go 1.18 RC1 to your local machine by following the instructions on the <a href="https://go.dev/dl/#go1.18rc1">download page</a>.</p><p>If you enjoyed this article, you might also enjoy Ricardo’s book, published by The Pragmatic Bookshelf:</p><p><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></p><p>Write your own fast, reliable, and cross-platform command-line tools with the Go programming language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*MhgIu3kJZj3-_AxX.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7773a110202" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/whats-new-in-go-1-18-e7773a110202">What&#39;s New in Go 1.18</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Floating Point Numbers in Go]]></title>
            <link>https://medium.com/pragmatic-programmers/testing-floating-point-numbers-in-go-9872fe6de17f?source=rss-e464162308a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9872fe6de17f</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rggo]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[command-line]]></category>
            <dc:creator><![CDATA[Ricardo Gerardi]]></dc:creator>
            <pubDate>Tue, 21 Dec 2021 11:31:04 GMT</pubDate>
            <atom:updated>2021-12-21T11:31:04.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2rdppmUzxcnkm8zh583g4g.png" /><figcaption>Image by Codekaizen, <a href="https://creativecommons.org/licenses/by-sa/4.0">CC BY-SA 4.0</a> via Wikimedia Commons</figcaption></figure><h4>A Helper Function to Calculate Relative Difference Between Input Numbers</h4><p><strong>📚 Connect with us. </strong><em>Want to hear what’s new at The Pragmatic Bookshelf? </em><a href="https://pragprog.com/newsletter/"><em>Sign up for our newsletter</em></a><em>. You’ll be the first to know about author speaking engagements, books in beta, new books in print, and promo codes that give you discounts of up to 40 percent.</em></p><p>The reason we need <a href="https://floating-point-gui.de/formats/fp/">floating point numbers</a> is that memory of computers is limited, so we can’t store numbers to an infinite number of places. Floating point notation, based on the <a href="https://en.wikipedia.org/wiki/IEEE_754">IEEE-754</a> standard, is a way to represent real numbers using 32 or 64 bits encoding. However, even using 64-bit precision it’s impossible to store an infinite number of digits, which means these numbers are rounded at some point, making them inherently imprecise.</p><p>This imprecision is usually small and, for many cases, it can be ignored. For other cases, it can cause problems, like when you need to calculate time from these numbers — as happened with the <a href="https://www.iro.umontreal.ca/~mignotte/IFT2425/Disasters.html">Patriot Missile software failure</a>. Make sure you understand the trade-offs of using floating point numbers according to your requirements. We aren’t going to cover cases where the imprecision matters in this article.</p><p>In chapter 5 of <a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/"><em>Powerful Command-Line Applications in Go</em></a> we develop a command-line tool that performs calculations on data extracted from comma separated value (CSV) files that contain floating-point number values.</p><p>To unit test the functions developed in that program, we perform a direct comparison between floating point numbers, which works well for the example in the book. However, comparing two floating point numbers is unreliable due to their imprecision.</p><p>For this article let&#39;s assume we can ignore the small imprecision for floating point numbers. Even where the imprecision is acceptable for the application, it could still lead to flaky tests — let’s look at an example case.</p><h3>Finding the Test Failure: A Decimal Place</h3><p>To visualize the potential issue when testing code that uses floating point numbers, consider the following example. We have a small Go package, shapes, that defines a new exported type, Rectangle, which implements a single method, Perimeter:</p><pre>package shapes</pre><pre>// Rectangle represents a rectangle shape<br>type Rectangle struct {<br>    L, W float64<br>}</pre><pre>// Perimeter calculates the perimeter of a shape<br>func (r Rectangle) Perimeter() float64 {<br>    return 2 * (r.L + r.W)<br>}</pre><p>Type Rectangle defines two <strong>float64</strong> fields <em>L</em> and <em>W</em>, representing the length and width of the rectangle. The Perimeter method calculates the rectangle perimeter and returns it as a <strong>float64</strong> value.</p><p>Now, let’s define a test case for this package:</p><pre>package shapes</pre><pre>import (<br>    “testing”<br>)</pre><pre>func TestPerimeter(t *testing.T) {<br>    r := Rectangle{L: 2.03, W: 3.5}</pre><pre>    exp := 11.06<br>    p := r.Perimeter()</pre><pre>    if exp != p {<br>        t.Errorf(“Expected %f, got %f”, exp, p)<br>    }<br>}</pre><p>Execute this test case using go test -v to see that it fails:</p><pre>$ go test -v</pre><pre>=== RUN TestPerimeter<br> rectangle_int_test.go:14: Expected 11.060000, got 11.060000<br> — — FAIL: TestPerimeter (0.00s)<br>FAIL<br>exit status 1<br>FAIL github.com/rgerardi/shapes 0.004s</pre><p>Notice that, although the test failed, the message seems to indicate that the two values are the same. You need to increase the number of decimal digits to see the difference by modifying the line in the test that generates the error from this:</p><pre>t.Errorf(“Expected %f, got %f”, exp, p)</pre><p>to this:</p><pre>t.Errorf(“Expected %.18f, got %.18f”, exp, p)</pre><p>Then, execute the test again. Notice that the output displays the two numbers with a small difference:</p><pre>$ go test -v</pre><pre>=== RUN TestPerimeter<br> shapes_test.go:12: Expected <strong>11.060000000000000497, got 11.059999999999998721</strong><br> — — FAIL: TestPerimeter (0.00s)<br>FAIL<br>exit status 1<br>FAIL shapes 0.001s</pre><p>The difference takes place only on the sixteenth decimal place. For this case, the difference is negligible, but it&#39;s still enough to cause a test failure. Let&#39;s address this issue by developing a test helper function.</p><h3>Writing a Test Helper for Floating Comparison</h3><p>To overcome the issue with testing floating point numbers, we can introduce a small tolerance when comparing two numbers. The goal is no longer ensuring the numbers are the same, but rather testing whether that small difference we noticed in the previous section is negligible.</p><p>Let&#39;s create a test helper function by taking some inspiration from Go&#39;s standard library.</p><p>Create a function that takes three floating numbers as input: <em>a</em>,<em>b</em>, and <em>e</em> where <em>a</em> and <em>b</em> represent the two numbers you&#39;re testing, and <em>e</em> is the tolerance required for the test. This tolerance is usually known as <a href="https://en.wikipedia.org/wiki/Machine_epsilon"><em>epsilon</em></a>. This function returns a boolean value representing whether or not the difference falls within the tolerance:</p><pre>func withinTolerance(a, b, e float64) bool {</pre><p>First, handle the case where a direct comparison works. If the two numbers are equal, return true:</p><pre>    if a == b {<br>        return true<br>    }</pre><p>Now, calculate the absolute difference between the two input numbers:</p><pre>    d := math.Abs(a - b)</pre><p>Now, you could compare the absolute difference with the tolerance directly. However, this comparison is not ideal since an absolute number that is small for two large input numbers could still be large for two small inputs, resulting in a wrong outcome. Instead, you need to calculate the relative difference between the input numbers by dividing their difference by the second input, <em>b</em>.</p><p>To avoid an invalid result when <em>b</em> is zero, return the result of the direct comparison:</p><pre>    if b == 0 {<br>        return d &lt; e<br>    }</pre><p>For other cases, return the result of the relative difference with the tolerance:</p><pre>    return (d / math.Abs(b)) &lt; e<br>}</pre><p>Next, use the helper function in the test case instead of a direct comparison:</p><pre>func TestPerimeter(t *testing.T) {<br>    r := Rectangle{L: 2.03, W: 3.5}</pre><pre>    exp := 11.06<br>    p := r.Perimeter()</pre><pre>   if !withinTolerance(exp, p, 1e-12) {<br>        t.Errorf(“Expected %.18f, got %.18f”, exp, p)<br>    }<br>}</pre><p>For this test, we&#39;re using a tolerance of &quot;1e-12,&quot; meaning if the relative difference is smaller than 12 decimal places, the test passes. Now, run the test to see the result:</p><pre>$ go test -v</pre><pre>=== RUN TestPerimeter<br>— — PASS: TestPerimeter (0.00s)<br>PASS<br>ok shapes 0.002s</pre><p>This time the test passes because the difference between the two input numbers is smaller than the specified tolerance.</p><h3>Conclusion</h3><p>When using floating point numbers in your programs, make sure to understand their benefits and their pitfalls.</p><p>Using tolerances to compare floating point numbers may not work for all cases, but for cases where the error is negligible, using this helper function strategy helps improve your test&#39;s reliability.</p><p>If you enjoyed this article, you might also enjoy Ricardo’s book, published by The Pragmatic Bookshelf:</p><p><a href="https://pragprog.com/titles/rggo/powerful-command-line-applications-in-go/">Powerful Command-Line Applications in Go</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*Uc__RLs5uVGC1ua_.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9872fe6de17f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/pragmatic-programmers/testing-floating-point-numbers-in-go-9872fe6de17f">Testing Floating Point Numbers in Go</a> was originally published in <a href="https://medium.com/pragmatic-programmers">The Pragmatic Programmers</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>