# TIL

> Today I Learned

Things I Learned today, found on [Simon's Blog](https://simonwillison.net/2020/Apr/20/self-rewriting-readme/), and repo can be found here: [Repo](https://github.com/jbranchaud/til)

***192 TILs so far.***

***

## Recently Added/Updated TILs

* [Clear Journald Logs](/linux/journalctl/clear-journalctl-logs)
* [Run Docker using Colima in MacBook](/macos/run-docker-using-colima)
* [Run MTR on MacOS without sudo](/macos/run-mtr-without-sudo)
* [Docker Exec (docker exec)](/docker/docker-exec)
* [Docker Publish Port](/docker/docker-publish-port)

***

## Categories

* [Linux](#linux)
* [Ansible](#ansible)
* [Caddy](#caddy-server)
* [Cheatsheets](#cheatsheets)
* [Docker](#docker)
* [Git](#git)
* [Github](#github)
* [Go](#go)
* [Learning Resources](#learning-resources)
* [MacOS](#macos)
* [Miscellaneous](#miscellaneous)
* [Python](#python)
* [Rclone](#rclone)
* [ReactJS](#reactjs)
* [Vagrant](#vagrant)
* [VSCode](#vscode)
* [WSL](#wsl)

***

## [Linux](/linux)

* [Add Swap Space To System](/linux/add-swap-space-to-system)
* [Add User To System](/linux/add-user-to-system)
* [Beautify Logs](/linux/beautify-logs)
* [Benchmark System](/linux/benchmark-system)
* [Ccze Scrolling Output](/linux/ccze-scrolling-output)
* [Change Default Shell](/linux/change-default-shell)
* [Change Hostname Of A system](/linux/change-hostname-of-a-system)
* [Changing User Password In Shell Script](/linux/changing-user-password-in-shell-script)
* [Check Group Of A User](/linux/check-group-of-a-user)
* [Check If A Package Is Installed Or Not](/linux/check-if-a-package-is-installed-or-not)
* [Check If A Port Is In Use](/linux/check-if-a-port-is-in-use)
* [Check If A User Exists](/linux/check-if-a-user-exists)
* [Check Open Port](/linux/check-open-port)
* [CMake Parallel Build with All Cores](/linux/cmake-parallel-build-with-all-cores)
* [Create Symbolic Links](/linux/create-symbolic-links)
* [Determine Which Process Is Using a File](/linux/determine-which-process-is-using-a-file)
* [Enable SSH Server](/linux/enable-ssh-server)
* [Fix Permission For Newly Created Partitions](/linux/fix-permission-for-newly-created-partitions)
* [Fix Windows And Linux Different Time Issue](/linux/fix-windows-and-linux-different-time-issue)
* [Get Arch Of System](/linux/get-arch-of-system)
* [Increase Limit of Inotify Watchers](/linux/increase-limit-of-inotify-watchers)
* [Install Latest NodeJS In Linux](/linux/install-latest-nodejs-in-linux)
* [Install Pavucontrol](/linux/install-pavucontrol)
* [Install Postman](/linux/install-postman)
* [Kill A Process In Linux](/linux/kill-a-process-in-linux)
* [Mount Partition On System Startup](/linux/mount-partition-on-system-startup)
* [OpenVPN Server](/linux/openvpn-server)
* [Ping over TCP](/linux/ping-over-tcp)
* [Pipe Password to Sudo](/linux/pipe-password-to-sudo)
* [Remove PPA From System](/linux/remove-ppa-from-system)
* [Remove User Password](/linux/remove-user-password)
* [Root Check in Scripts](/linux/root-check)
* [Run Go Binaries Without Installing Go](/linux/run-go-binaries-without-installing-go)
* [Set Different Time Zone](/linux/set-different-time-zone)
* [Show Disk Usage By Directories](/linux/show-disk-usage-by-directories)
* [Show Public IP](/linux/show-public-ip)
* [Show Size of Current Directory](/linux/show-size-of-current-directory)
* [System Ugprade](/linux/system-upgrade)
* [Tar Exclude Directories](/linux/tar-exclude-directories)
* [Tar Retain File Permissions](/linux/tar-retain-file-permissions)
* [Why All Users Can Write to /tmp](/linux/why-all-users-can-write-to-tmp)

### [Alpine Linux](/linux/alpine)

* [Adding User On Alpine](/linux/alpine/adding-user-on-alpine)
* [Chaning Timezone On Alpine](/linux/alpine/changing-timezone-on-alpine)
* [Installing Ansible On Alpine](/linux/alpine/installing-ansible-on-alpine)
* [Installing Dig On Alpine](/linux/alpine/installing-dig-on-alpine)
* [Installing Pip On Alpine](/linux/alpine/installing-pip-on-alpine)
* [Installing Python2 On Alpine](/linux/alpine/installing-python2-on-alpine)

### [Apt](/linux/apt)

* [APT Fix Broken Packages](/linux/apt/apt-fix-broken-packages)
* [APT Hold Packages From Upgrade](/linux/apt/apt-hold-packages-from-upgrades)

### [Arch Linux](/linux/arch)

* [Install Docker Compose](/linux/arch/install-docker-compose)
* [Install Docker](/linux/arch/install-docker)
* [Install Pip](/linux/arch/install-pip)

### [Bash](/linux/bash)

* [Bash List Only Directories](/linux/bash/bash-list-only-directories)
* [BashTOP Resource Monitor](/linux/bash/bashtop-resource-monitor)
* [Case Statements](/linux/bash/case-statements)
* [Concatenate Strings](/linux/bash/concatenate-strings)
* [Custom Shell Prompt](/linux/bash/custom-shell-prompt)
* [Length of String in Variable](/linux/bash/length-of-string-in-variable)
* [Test Regular Expression Against A String](/linux/bash/test-regular-expression-against-a-string)
* [Pass Arguments while Piping](/linux/bash/pass-arguments-while-piping)
* [Read Command Output In Reverse Order](/linux/bash/read-command-output-in-reverse-order)
* ["set -e" In Scripts](/linux/bash/set-e-in-scripts)
* [Set MacOS Like Terminal Font](/linux/bash/set-macos-like-terminal-font)
* [Set Unlimited Bash History](/linux/bash/set-unlimited-bash-history)
* [Shell Formatter](/linux/bash/shell-formatter)
* [Yes](/linux/bash/yes)

### [Curl](/linux/curl)

* [Fix Failed Writing Body While Piping](/linux/curl/fix-failed-writing-body-while-piping)
* [Use Proxy Server in cURL](/linux/curl/use-proxy-server-in-curl)

### [Fedora](/linux/fedora)

* [Fix Clear Command Not Found](/linux/fedora/fix-clear-command-not-found)
* [Install RPM Packages in Fedora](/linux/fedora/install-rpm-packages-in-fedora)

### [GPG](/linux/gpg)

* [Fix "Inappropriate ioctl for device" Error](/linux/gpg/fix-inappropriate-ioctl-for-device-error)
* [GPG Import Keys](/linux/gpg/gpg-import-keys)
* [GPG Test](/linux/gpg/gpg-test)
* [GPG Trust Key](/linux/gpg/gpg-trust-key)
* [GPG Verify Signature](/linux/gpg/gpg-verify-signature)

### [Grep](/linux/grep)

* [Grep Case Insensitive Search](/linux/grep/grep-case-insensitive-search)
* [Grep Count Occurance](/linux/grep/grep-count-matches)
* [Grep Exact Match](/linux/grep/grep-exact-match)
* [Grep Invert Search](/linux/grep/grep-invert-search)
* [Grep On Continous Stream](/linux/grep/grep-on-continous-stream)
* [Grep Quiet Mode](/linux/grep/grep-quiet-mode)
* [Grep Search For Multiple Strings](/linux/grep/grep-search-for-multiple-strings)
* [Remove Empty Lines](/linux/grep/remove-empty-lines)

### [Journalctl](/linux/journalctl)

* [Clear Journald Logs](/linux/journalctl/clear-journalctl-logs)
* [Get Errors in Running Services using Journalctl](/linux/journalctl/get-errors-in-running-services-using-journalctl)

### [Networking](/linux/networking)

* [Install Dig](/linux/networking/install-dig)
* [Install MTR](/linux/networking/install-mtr)
* [Set Metric For A Network Using nmcli](/linux/networking/set-metric-for-a-network-using-nmcli)
* [WireGuard Server](/linux/networking/wireguard-server)

### [Raspberry Pi](/linux/raspberry-pi)

* [Disable Swap Memory on SD Card](/linux/raspberry-pi/disable-swap-memory-on-sd-card)

### [SSH](/linux/ssh)

* [Reconnect To a Disconnected SSH Session](/linux/ssh/reconnect-to-a-disconnected-ssh-session)
* [Run A Local Script On Remote SSH Server](/linux/ssh/run-a-local-script-on-remote-ssh-server)
* [Screen](/linux/ssh/screen)
* [Tmux](/linux/ssh/tmux)

### [Systemd](/linux/systemd)

* [Create A Service](/linux/systemd/create-a-service)
* [Create A Systemd Timer](/linux/systemd/create-a-systemd-timer)
* [List Systemd Services Of A User](/linux/systemd/list-services-of-a-user)
* [Prevent Systemd Timers From Overlapping](/linux/systemd/prevent-systemd-timers-from-overlapping)
* [Watch Systemd Service Status](/linux/systemd/watch-systemd-service-status)

### [Tcpdump](/linux/tcpdump)

* [Capture ICMP Packets](/linux/tcpdump/capture-icmp-packets)
* [Capture Traffic By IP Or A Network](/linux/tcpdump/capture-traffic-by-an-ip-address-or-a-network)

### [Ubuntu Linux](/linux/ubuntu)

* [Get Clipboard History](/linux/ubuntu/get-clipboard-history)
* [Install HMAC256 On Ubuntu](/linux/ubuntu/install-hmac256-on-ubuntu)
* [Obtaining a List of Ubuntu Repository Mirror Servers](/linux/ubuntu/obtaining-a-list-of-ubuntu-repository-mirror-servers)

### [Wget](/linux/wget)

* [Basic Authentication](/linux/wget/basic-auth)

## [Ansible](/ansible)

* [Add Authorized SSH Key to User using Ansible](/ansible/add-ssh-key-to-user-using-ansible)
* [Ansible Add User to System](/ansible/add-user-to-system)
* [Ansible Configure Default Inventory File](/ansible/ansible-configure-default-inventory-file)
* [Ansible Disable Python Interpreter Warnings](/ansible/ansible-disable-python-interpreter-warnings)
* [Ansible Pause Playbook Execution](/ansible/ansible-pause-playbook-execution)
* [Ansible Test Connection](/ansible/ansible-test-connection)
* [Run Ansible Playbook Locally](/ansible/run-ansible-playbook-locally)
* [Setting a Password in Ansible Inventory File](/ansible/setting-a-password-in-ansible-inventory-file)

## [Caddy Server](/caddy)

* [Caddy Write Logs to a File](/caddy/caddy-write-logs-to-a-file)
* [Return Client IP Address As Plain Text](/caddy/return-client-ip-address-as-plain-text)

## [Cheatsheets](/cheatsheets)

* [Bash Cheatsheet](/cheatsheets/bash-cheatsheet)
* [Grep Cheatsheet](/cheatsheets/grep-cheatsheet)
* [Markdown Cheatsheet](/cheatsheets/markdown-cheatsheet)
* [MongoDB Cheatsheet](/cheatsheets/mongodb-cheatsheet)
* [Networking Cheatsheet](/cheatsheets/networking-cheatsheet)
* [Python Cheatsheet](/cheatsheets/python-cheatsheet)
* [ReactJS Cheatsheet](/cheatsheets/reactjs-cheatsheet)
* [Regex Cheatsheet](/cheatsheets/regex-cheatsheet)

## [Docker](/docker)

* [Docker Build Multiple Tags At Once](/docker/docker-build-multiple-tags-at-once)
* [Docker Exec](/docker/docker-exec)
* [Docker Publish Port](/docker/docker-publish-port)
* [Docker Run Without Cache](/docker/docker-run-without-cache)
* [Docker Run](/docker/docker-run)
* [Fix UFW Security Flaw](/docker/fix-ufw-security-flaw)
* [Install Docker](/docker/install-docker)
* [Install Ping in Docker](/docker/install-ping-in-docker)
* [Pass Build Time Arguments To Docker Build](/docker/pass-build-time-arguments-to-docker-build)
* [Remove Container When It Exits](/docker/remove-container-when-it-exits)
* [Remove Unused Data](/docker/remove-unused-data)
* [Run Docker without root](/docker/run-docker-without-root)
* [Setup Docker Buildx For Multi Arch Builds](/docker/setup-docker-buildx-for-multi-arch-builds)

## [Git](/git)

* [Change Last Commit Message](/git/change-last-commit-message)
* [Delete Tag](/git/delete-tag)
* [Get Tag Names in Git](/git/get-tag-names-in-git)
* [Save Credentials for Remotes in Git](/git/save-credentials-for-remotes)
* [Show Commit Only From One Author](/git/show-commit-only-from-one-author)
* [View Git Commit Changes](/git/view-git-commit-changes)

## [GitHub](/github)

### [GitHub Actions](/github/actions)

* [Setting An Environment Variable](/github/actions/setting-an-environment-variable)
* [Running Jobs in a Container](/github/actions/running-jobs-in-a-container)

## [Go](/go)

* [Convert String To Uppercase in Go](/go/convert-string-to-uppercase)
* [List All Possible GOOS And GOARCH](/go/list-all-possible-goos-and-goarch)
* [Print Go Version](/go/print-go-version)
* [Resolve Hostname To IP Address](/go/resolve-hostname-to-ip-address)
* [Trim Whitespaces From String](/go/trim-whitespaces-from-string)
* [Update Project Libraries To Latest](/go/update-project-libraries-to-latest)

## [Learning Resources](/learning-resources)

* [Algorithms](/learning-resources/algorithms)
* [DevOps](/learning-resources/devops)
* [Git](/learning-resources/git)
* [Linux](/learning-resources/linux)
* [Networking](/learning-resources/networking)
* [Programming Languages](/learning-resources/programming-languages)

## [MacOS](/macos)

* [Run Docker using Colima](/macos/run-docker-using-colima)
* [Run MTR without sudo](/macos/run-mtr-without-sudo)

## [Miscellaneous](/miscellaneous)

* [Good Reads](/miscellaneous/good-reads)
* [Must Read Sites](/miscellaneous/must-read-sites)
* [Useful Sites](/miscellaneous/useful-sites)

## [Python](/python)

* [Add An Item To Dictionary](/python/add-an-item-to-dictionary)
* [Check If A Key Exists In Dictionary](/python/check-if-a-key-exists-in-dictionary)
* [Check If a String is Empty](/python/check-if-a-string-is-empty)
* [Check Image Size](/python/check-image-size)
* [Check Python Version Programmatically](/python/check-python-version-programmatically)
* [Convert List To Tuple](/python/convert-list-to-tuple)
* [Execute Python Code in Command Shell](/python/execute-python-code-in-command-shell)
* [Formatted Strings](/python/formatted-strings)
* [Get IP Address From Hostname](/python/get-ip-address-from-hostname)
* [Limit Floating Point To Two Decimal Places](/python/limit-floating-point-to-two-decimal-places)
* [Measure Latency Using TCP](/python/measure-latency-using-tcp)
* [Pass List as Argument to a Function](/python/pass-list-as-argument-to-a-function)
* [Print Tabular Data](/python/print-tabular-data)
* [Python Padding Strings](/python/python-padding-strings)
* [Read A File Line By Line](/python/read-a-file-line-by-line)
* [Remove A File](/python/remove-a-file)
* [Remove Trailing Spaces And New Lines From A String](/python/remove-trailing-spaces-and-new-lines-from-a-string)
* [Run Python Script in Background](/python/run-python-script-in-background)
* [Split String with Delimiter](/python/split-string-with-delimiter)
* [Validate IP Address](/python/validate-ip-address)

### [Pipenv](/python/pipenv)

* [Install Dependencies System Wide](/python/pipenv/install-dependencies-system-wide)
* [Remove Virtualenv](/python/pipenv/remove-virtualenv)

## [Rclone](/rclone)

* [Limit Upload Download Speeds in Rclone](/rclone/limit-upload-download-speeds)

## [ReactJS](/reactjs)

* [ReactJS Resources](/reactjs/reactjs-resources)

## [Vagrant](/vagrant)

* [Increase RAM And CPU On Vagrant Machine](/vagrant/increase-ram-and-cpu-on-vagrant-machine)
* [Vagrant Specify Disk Size](/vagrant/vagrant-specify-disk-size)

## [VSCode](/vscode)

* [Fix Icons Not Displaying in Terminal](/vscode/fix-icons-not-displaying-in-terminal)
* [Install VS Code on a Linux Server](/vscode/install-vs-code-on-a-linux-server)

## [WSL](/wsl)

* [Convert WSL1 to WSL2](/wsl/convert-wsl1-to-wsl2)
* [Enable Systemd Support in WSL2](/wsl/enable-systemd-support-in-wsl2)


# Ansible

> ansible - run a command somewhere else

Ansible is an IT automation tool. It can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero downtime rolling updates.

Ansible’s main goals are simplicity and ease-of-use. It also has a strong focus on security and reliability, featuring a minimum of moving parts, usage of OpenSSH for transport (with other transports and pull modes as alternatives), and a language that is designed around auditability by humans–even those not familiar with the program.

### [Official Documentation](https://docs.ansible.com/ansible/latest/index.html)

## TIL(s)

* [Add Authorized SSH Key to User using Ansible](/ansible/add-ssh-key-to-user-using-ansible)
* [Ansible Add User to System](/ansible/add-user-to-system)
* [Ansible Configure Default Inventory File](/ansible/ansible-configure-default-inventory-file)
* [Ansible Disable Python Interpreter Warnings](/ansible/ansible-disable-python-interpreter-warnings)
* [Ansible Pause Playbook Execution](/ansible/ansible-pause-playbook-execution)
* [Ansible Test Connection](/ansible/ansible-test-connection)
* [Run Ansible Playbook Locally](/ansible/run-ansible-playbook-locally)
* [Setting a Password in Ansible Inventory File](/ansible/setting-a-password-in-ansible-inventory-file)


# Add Authorized SSH Key to User using Ansible

Some examples of Ansible Playbooks for adding/updating authorized keys for SSH login.

## 1. Set Authorized Key(s) from URL

```yaml
- name: Set Authorized Key(s) from an URL
  ansible.posix.authorized_key:
      user: charlie
      state: present
      key: https://github.com/crazyuploader.keys
```

***Reference:*** [***Add or Remove SSH Authorized Key - Ansible Documentation***](https://docs.ansible.com/ansible/latest/collections/ansible/posix/authorized_key_module.html)


# Add User to System using Ansible

In Ansible we can use `ansible.builtin.user` module to add a user to the system.

## Example(s)

### 1. Add user 'jungle'

```yaml
- name: Add the user 'jungle'
  ansible.builtin.user:
      name: jungle
      comment: Jungle
```

### 2. Add a user with specific attributes

```yaml
- name: Add the user 'jungle' with specific attributes
  ansible.builtin.user:
      name: jungle
      comment: Jungle
      home: /home/jungle
      shell: /bin/bash
      password: "{{ 'password' | password_hash('sha512') }}"
```

### 3. Adding groups to the user

```yaml
- name: Add the user 'jungle' and assign to groups
  ansible.builtin.user:
      name: jungle
      groups: sudo,users
      append: yes
```

***Reference:*** [***Manage User Accounts - Ansible Documention***](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/user_module.html)


# Ansible Configure Default Inventory File

By default, Ansible would attempt to read the default configuration file at `/etc/ansible/hosts`, we can specify the default configuration file to use by creating an Ansible configuration file.

## Procedure

1. Create `ansible.cfg` file in home directory, or project directory.
2. Configure the `ansible.cfg` file in home directory, & add `[defaults]` section:

```ini
[defaults]
inventory = ~/.ansible/hosts
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/63413958)

***Reference(s):***

* [Working with Inventory - Ansible Documentation](https://docs.ansible.com/ansible/2.7/user_guide/intro_inventory.html)
* [Ansible Configuration Settings - Ansible Documentation](https://docs.ansible.com/ansible/latest/reference_appendices/config.html)


# Ansible Disable Python Interpreter Warnings

Latest Ansible started displaying Python interpreter warnings, such as -

```
[WARNING]: Platform linux on host Server02 is using the discovered Python interpreter at /usr/bin/python3.12, but future installation of another Python interpreter could change the meaning of that path. See
https://docs.ansible.com/ansible-core/2.17/reference_appendices/interpreter_discovery.html for more information.
```

To disable these Python interpreter warnings, we can add the following to the Ansible configuration file.

```ini
# Disable Python interpreter warnings
interpreter_python = auto_silent
```

***Source:*** [***Interpreter Discovery - Ansible Core Documentation***](https://docs.ansible.com/ansible-core/2.17/reference_appendices/interpreter_discovery.html)


# Ansible Pause Playbook Execution

Sometimes, we need to pause the execution of an Ansible Playbook to allow for manual intervention or to give users time to perform necessary actions. The ansible.builtin.pause module is useful in such scenarios. Below are examples of how to use it effectively.

### Example 1: Prompt the User to Close Applications

```yaml
- name: A reminder to make sure the user has closed all the apps before continuing
  ansible.builtin.pause:
      prompt: "Make sure there is no application running on the server!"
```

### Example 2: Pause for a Fixed Duration

```yaml
- name: Pause for 5 minutes to let the database server settle
  ansible.builtin.pause:
      minutes: 5
```

### Example 3: Pause and Await User Confirmation

```yaml
- name: Wait for user confirmation before proceeding with the next step
  ansible.builtin.pause:
      prompt: "Have you backed up all necessary data? Type 'yes' to continue."
      echo: true
```

***Reference:*** [***Pause Module - Ansible Documentation***](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/pause_module.html)


# Ansible Test Connection

We can use `ping` module of Ansible to test whether or not Ansible is able to log onto the configured server(s).

```bash
ansible all -m ping
```

This will ping every server.

***Source:*** [***Ping Module - Ansible Documentation***](https://docs.ansible.com/ansible/2.3/ping_module.html)


# Run Ansible Playbook Locally

At times, we require an Ansible Playbook to run locally on the host server. Few examples are given below -

### 1. Using Ansible Commandline

```bash
ansible-playbook --connection=local --inventory 127.0.0.1, playbook_name.yml
```

### 2. Using Ansible Inventory File

We can also, add the host in an inventory file such as -

```ini
127.0.0.1 ansible_connection=local
```

### 3. Using Ansible Configuration File

```code
[defaults]
transport = local
```

### 4. Using Playbook Header

```yaml
- hosts: 127.0.0.1
    connection: local
```

***Source:*** [***GitHub Gist - Ansible playbook Locally***](https://gist.github.com/alces/caa3e7e5f46f9595f715f0f55eef65c1)

***Reference(s):***

* [Configuring Ansible - Ansible Documentation](https://docs.ansible.com/ansible/latest/installation_guide/intro_configuration.html)
* [Implicit 'localhost' - Ansible Documentation](https://docs.ansible.com/ansible/latest/inventory/implicit_localhost.html)


# Setting a Password in Ansible Inventory File

Generally, we shouldn't be needing this, as one should have a SSH key pair to access remote servers for enhanced security, and convenience, but there might be scenarios where you need to use password authentication. This can be be useful in development or testing environments, but it's prudent to avoid this practice in production.

## Example Inventory File

```toml
[vm]
vagrant ansible_host=10.0.0.2 ansible_user=vagrant ansible_ssh_pass=vagrant
```

***Source:*** [***Serverfault***](https://serverfault.com/a/742382)


# Caddy

> Caddy 2 is a powerful, enterprise-ready, open source web server with automatic HTTPS written in Go

Caddy is a powerful, extensible platform to serve your sites, services, and apps, written in Go. If you're new to Caddy, the way you serve the Web is about to change.

### [Official Documentation](https://caddyserver.com/docs/)

## TIL(s)

* [Caddy Write Logs to a File](/caddy/caddy-write-logs-to-a-file)
* [Return Client IP Address As Plain Text](/caddy/return-client-ip-address-as-plain-text)


# Caddy Write Logs to a File

We can write log files to a file using `log` directive in Caddyfile. Example is given below -

```
mywebsite.com {
    log {
        output file /var/log/caddy/mywebsite.com-access.log
    }
}
```

***Source:*** [***Future Studio***](https://futurestud.io/tutorials/caddy-configure-logging-and-access-logs)

***Reference:*** [***Log Caddyfile Directive - Caddy Server Documentation***](https://caddyserver.com/docs/caddyfile/directives/log)


# Return Client IP Address As Plain Text

In Caddy Server, we can use [Template(s)](https://caddyserver.com/docs/json/apps/http/servers/errors/routes/handle/templates/) to return Client IP Address as plain text, using `.RemoteIP`, Caddyfile example is given below -

Caddyfile:

```
example.com {
    templates
    header Content-Type text/plain
    respond "Hello from IPv6, your IPv6 is -> {{.RemoteIP}}"
    encode zstd gzip
}
```

***Source:*** [***Caddy Community***](https://caddy.community/t/caddy-server-that-returns-only-ip-address-as-text/6928)


# Cheatsheet(s)

> Cheatsheet(s) of various types, be it Programming Languages, or Operating Systems that I've collected so far.

## List of Cheatsheets

* [Bash Cheatsheet](/cheatsheets/bash-cheatsheet)
* [Dnf Cheatsheet](/cheatsheets/dnf-cheatsheet)
* [Grep Cheatsheet](/cheatsheets/grep-cheatsheet)
* [Markdown Cheatsheet](/cheatsheets/markdown-cheatsheet)
* [MongoDB Cheatsheet](/cheatsheets/mongodb-cheatsheet)
* [Networking Cheatsheet](/cheatsheets/networking-cheatsheet)
* [Python Cheatsheet](/cheatsheets/python-cheatsheet)
* [ReactJS Cheatsheet](/cheatsheets/reactjs-cheatsheet)
* [Regex Cheatsheet](/cheatsheets/regex-cheatsheet)


# Bash Cheatsheet

* [Bash Reference Manual](https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html)
* [DevHints](https://devhints.io/bash)
* [The Art of Command Line](https://github.com/jlevy/the-art-of-command-line)


# Dnf Cheatsheet

* [25+ dnf command examples in Linux \[Cheat Sheet\]](https://www.golinuxcloud.com/dnf-command-in-linux/)


# Grep Cheatsheet

* [Cheatography](https://cheatography.com/tme520/cheat-sheets/grep-english/)
* [Ryans Tutorials](https://ryanstutorials.net/linuxtutorial/cheatsheetgrep.php)


# Markdown Cheatsheet

* [DevHints](https://devhints.io/markdown)
* [Markdown Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)
* [Markdown Syntax](https://dotcms.com/docs/latest/markdown-syntax)


# MongoDB Cheatsheet

* [MongoDB Cheat Sheet](https://developer.mongodb.com/quickstart/cheat-sheet/)
* [MongoDB Cheat Sheet - GitHub Gists](https://gist.github.com/bradtraversy/f407d642bdc3b31681bc7e56d95485b6)


# Networking Cheatsheet

* [Cisco](https://ipcisco.com/cheat-sheets/)
* [Linux-Networking Cheat Sheet](https://lzone.de/cheat-sheet/Linux-Networking)
* [Packet Life](https://packetlife.net/library/cheat-sheets/)
* [THE NETWORK PROTOCOL CHEATSHEET](https://www.exploit-db.com/docs/48120)


# Python Cheatsheet

* [DevHints](https://devhints.io/python)
* [Python Cheatsheet](https://www.pythoncheatsheet.org/)
* [Python Crash Course](https://ehmatthes.github.io/pcc/cheatsheets/README.html)
* [Python Programming](https://pythonprogramming.net/)


# ReactJS Cheatsheet

* [DevHints](https://devhints.io/react)


# Regex Cheatsheet

* [DevHints](https://devhints.io/regexp)
* [Regex Cheatsheet](https://ihateregex.io/cheatsheet)


# Docker

> docker - Docker image and container command line interface

Docker is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure so you can deliver software quickly.

### [Official Documentation](https://docs.docker.com/get-started/overview/)

## TIL(s)

* [Docker Build Multiple Tags At Once](/docker/docker-build-multiple-tags-at-once)
* [Docker Exec](/docker/docker-exec)
* [Docker Publish Port](/docker/docker-publish-port)
* [Docker Run Without Cache](/docker/docker-run-without-cache)
* [Docker Run](/docker/docker-run)
* [Fix UFW Security Flaw](/docker/fix-ufw-security-flaw)
* [Install Docker](/docker/install-docker)
* [Install Ping in Docker](/docker/install-ping-in-docker)
* [Pass Build Time Arguments To Docker Build](/docker/pass-build-time-arguments-to-docker-build)
* [Remove Container When It Exits](/docker/remove-container-when-it-exits)
* [Remove Unused Data](/docker/remove-unused-data)
* [Run Docker without root](/docker/run-docker-without-root)
* [Setup Docker Buildx For Multi Arch Builds](/docker/setup-docker-buildx-for-multi-arch-builds)


# Docker Build Multiple Tags At Once

We can add multiple tags at once on build by:

```bash
docker build --tag test-image:tag01 --tag test-image:tag02 .
```

Now that the image is built with multiple tags, we can push all tags at once using `--all-tags` flag.

## Example

```bash
docker build --tag test-image:tag01 --tag test-image:tag02 .
docker push test-image --all-tags
```

***Source(s):***

* [StackOverFlow](https://stackoverflow.com/a/35565384)
* [StackOverFlow](https://stackoverflow.com/a/56905333)


# Docker Exec (docker exec)

`docker exec`

> Run a command in a running container

**Usage**

```bash
docker exec {options} {container} {command} {ARG...}
```

**Example**

```bash
root@ip-172-31-36-54:~# docker exec -it 0ce6bc8abc43 /bin/bash
root@0ce6bc8abc43:~# whoami
root
```

***Source:*** [***Docker Docs***](https://docs.docker.com/engine/reference/commandline/exec/)


# Docker Publish Port

By default Docker does not expose Container's Port to the Host, to do so we can `--publish` or `-p` flag, which exposes Container's Port(s) to Host.

## Example

```bash
docker run -d -it \
           -p 43210:43210/udp \
           --name bombsquad \
           crazyuploader/bombsquad
```

Here, we're exposing `UDP Port 43210` to the Host.

***Source:*** [***Docker Docs***](https://docs.docker.com/config/containers/container-networking/#published-ports)


# Docker Run Without Cache

Sometimes, we don't need Docker build cache, and for those cases we can use `--no-cache` option.

## Example

```bash
docker build --no-cache --tag test .
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/35595021)


# Docker Run (docker run)

`docker run`

> Run a command in a new container

## Usage

```bash
docker run {options} {image} {command} {ARG...}
```

## Example

```bash
azureuser@Azure:~$ docker run ubuntu echo "Hi there!"
Hi there!
```

***Source:*** [***Docker Docs***](https://docs.docker.com/engine/reference/commandline/run/)


# Docker Fix UFW Security Flaw

It's been a while since I've started using Docker and while running containers with port binding such "8888:8888" may have made perfect sense to be accessible from anywhere, I was under this impression that UFW should take care of that, and not allow access to Docker Containers from outside unless I've created a rule to allow anyway. But, guess what? Sneaky Docker bypasses UFW just like that using iptables, and voila, end result is you can still access the container. To fix this, we can apply the following fix from [ufw-docker](https://github.com/chaifeng/ufw-docker#solving-ufw-and-docker-issues).

## Fix

Edit the `/etc/ufw/after.rules` file, and add the following content to it, followed by `sudo ufw reload` or `sudo systemctl restart ufw` command.

```
# BEGIN UFW AND DOCKER
*filter
:ufw-user-forward - [0:0]
:ufw-docker-logging-deny - [0:0]
:DOCKER-USER - [0:0]
-A DOCKER-USER -j ufw-user-forward

-A DOCKER-USER -j RETURN -s 10.0.0.0/8
-A DOCKER-USER -j RETURN -s 172.16.0.0/12
-A DOCKER-USER -j RETURN -s 192.168.0.0/16

-A DOCKER-USER -p udp -m udp --sport 53 --dport 1024:65535 -j RETURN

-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 192.168.0.0/16
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 10.0.0.0/8
-A DOCKER-USER -j ufw-docker-logging-deny -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -d 172.16.0.0/12
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 192.168.0.0/16
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 10.0.0.0/8
-A DOCKER-USER -j ufw-docker-logging-deny -p udp -m udp --dport 0:32767 -d 172.16.0.0/12

-A DOCKER-USER -j RETURN

-A ufw-docker-logging-deny -m limit --limit 3/min --limit-burst 10 -j LOG --log-prefix "[UFW DOCKER BLOCK] "
-A ufw-docker-logging-deny -j DROP

COMMIT
# END UFW AND DOCKER
```

***Source:*** [***ufw-docker***](https://github.com/chaifeng/ufw-docker)


# Install Docker

We can install `docker` by using its shell script.

### Easy Install (Using Script)

```bash
curl -sL https://get.docker.com | bash -
```

### Manual Install

Setup Official Repositories

```bash
sudo apt-get update
sudo apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common \
    lsb-release
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo add-apt-repository \
    "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
    $(lsb_release -cs) \
    stable"
```

Installing Docker

```bash
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io
```

**Reference(s)**

* [Docker Docs](https://docs.docker.com/engine/install/ubuntu/)


# Install Ping in Docker

`ping` command can be installed in a Docker container using:

```bash
apt-get install -y iputils-ping
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/39901446)


# Pass Build Time Arguments To Docker Build

While building Dockerfile(s) we can pass and use Environment variables such as -

```dockerfile
ARG VARIABLE1
ARG VARIABLE2

RUN echo "Value of first Variable = ${VARIABLE1}" && \
    echo "Value of second Variable = ${VARIABLE2}"
```

And running `docker build` command as following -

```bash
docker build -t {IMAGE_NAME}:{IMAGE_TAG} \
                --build-arg {VARIABLE1}="Some value" \
                --build-arg {VARIABLE2}="Some other value"
```

***Source:*** [***Bits and Picces***](https://blog.bitsrc.io/how-to-pass-environment-info-during-docker-builds-1f7c5566dd0e)


# Remove Container When It Exists

By default, Docker doesn't remove containers when they exit, this can lead storage getting full. To remove a container as soon as it exits, we can pass `--rm` argument in `docker run` command.

## Usage

```bash
docker run --rm ubuntu echo "Hello Docker"
```

***Source:*** [***Docker Docs***](https://docs.docker.com/engine/reference/run/#clean-up---rm)


# Remove Unused Data

`docker system prune` frees up storage by deleting unused data.

> Remove all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes.

```bash
docker system prune

WARNING! This will remove:
        - all stopped containers
        - all networks not used by at least one container
        - all dangling images
        - all build cache
Are you sure you want to continue? [y/N] y
```


# Run Docker without Root

To run Docker as non-root user, we can add our user to "docker" group, to do run this -

```bash
sudo usermod -aG docker ${USER}
```

**Reference(s)**

* <https://docs.docker.com/engine/install/linux-postinstall/>


# Setup Docker Buildx For Multi Arch builds

By default `buildx` plugin is availabe on Docker Desktop, and if Docker was installing using [deb](https://docs.docker.com/engine/install/) packages. In case it is not installed, we can get it from [Docker buildx - GitHub](https://github.com/docker/buildx/releases/latest) and put it to `~/.docker/cli-plugins` directory, and make it executable using the following command -

```bash
chmod +x ~/.docker/cli-plugins/docker-buildx
```

To be able to build Multi-Arch Docker Images -

```bash
docker run --privileged --rm tonistiigi/binfmt --install all
docker buildx create --name multibuilder
docker buildx use multibuilder
docker buildx inspect --bootstrap
```

And that's it! Now we can run `docker buildx` on our Dockerfile(s) to build them for Multi Architecture.

**Source(s)**

* [Cirrus CI Documentation](https://cirrus-ci.org/guide/docker-builder-vm/#multi-arch-builds)
* [Docker Docs](https://docs.docker.com/buildx/working-with-buildx/)


# Git

> git - the stupid content tracker

Git is a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

Git is easy to learn and has a tiny footprint with lightning fast performance. It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.

### [Official Documentation](https://git-scm.com/doc)

## TIL(s)

* [Change Last Commit Message](/git/change-last-commit-message)
* [Delete Tag](/git/delete-tag)
* [Get Tag Names in Git](/git/get-tag-names-in-git)
* [Save Credentials for Remotes in Git](/git/save-credentials-for-remotes)
* [Show Commit Only From One Author](/git/show-commit-only-from-one-author)
* [View Git Commit Changes](/git/view-git-commit-changes)


# Change Last Commit Message

We can use `git commit --amend` command to change the most recent commit message.

## Usage

### For Local Commits

```bash
git commit --amend -m "{NEW_MESSAGE}
```

### For Already Pushed Commits

In this case, we can only edit the most recent commit message and force push it to remote -

```bash
git commit --amend -m "{NEW_MESSAGE}"
git push --force
```

**Note:** Force Pushes can break things, so warnings ahead!

***Source:*** [***Linuxize***](https://linuxize.com/post/change-git-commit-message/)


# Delete Tag

Following command be used to delete a tag on remote:

```bash
git push --delete {REMOTE_NAME} {TAG_NAME}
```

To also delete the local tag, use:

```bash
git tag --delete {TAG_NAME}
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/5480292)


# Get Tag Names in Git

To get tag name in a git repository, we can use `git describe` command.

## Example: Get Latest Tag Name

```
git describe --tag
v0.5
```

## Example: Get All Tags Sorted by Commit Date

```
git tag --sort=committerdate
v0.1
v0.2
v0.3
v0.4
v0.5
```

***Source(s):***

* [StackOverFlow](https://stackoverflow.com/a/7261049)
* [GitHub Gist](https://gist.github.com/rponte/fdc0724dd984088606b0)


# Save Credentials for Remotes in Git

SSH Key based login for Git works most of the times, except for the time when we add a HTTPS based remote (obviously with access token!), then it's annoying to put in your access token every single time, and that we can fix with [Git Credential Storage](https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage), example given below -

## Setup Git Credential Storage Globally

```bash
git config --global credential.helper store
```

**Note:** `--global` argument tells Git to set this globally; credential file is stored `~/.git-credentials`.

## Setup Git Credential Storage on a Single Repository

```bash
cd /path/to/the/respository
git config credential.helper store
```

***Source:*** [***Sentry Answers***](https://sentry.io/answers/save-credentials-for-remotes-in-git/)

***Reference:*** [***Git Book***](https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage)


# Show Commit Only From One Author

Sometimes we just want to show only commits from one author, we can use `git log --author` argument in that case.

## Example

```bash
git log --author="49350241+crazyuploader@users.noreply.github.com"
```

***Reference(s)***

* [Man7](https://man7.org/linux/man-pages/man1/git-log.1.html)


# View Git Commit Changes

In order to see changes in a commit, we can make use of either `git diff` or `git show` commands. Below are examples to illustrate their usage -

## Check Changes with `git show`

The `git show` command show the changes introduced in a specific commit. To use it, specify the commit hash:

```bash
git show <commit-hash>
```

## Check Changes with `git diff`

The `git diff` command allows us to compare changes between commits or with the working directory.

### Compare the last commit:

```bash
git diff HEAD~1 HEAD
```

### Compare two specific commits:

```bash
git diff <commit-hash-1> <commit-hash-2>
```

### Show changes between the working directory & the last commit:

```bash
git diff
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/17563740)


# GitHub

> A provider of Internet hosting for software development and version control using Git.

## Subcategories

* [Actions](/github/actions)


# GitHub Actions

> A CI/CD platform for GitHub

## TIL(s)

* [Setting An Environment Variable](/github/actions/setting-an-environment-variable)
* [Running Jobs in a Container](/github/actions/running-jobs-in-a-container)


# Running Jobs in a Container

We can run jobs in a container in the following way -

## 1. Running a job within a container

```yaml
name: My CI
on:
    push:
        branches: [main]
jobs:
    container-job:
        runs-on: ubuntu-latest
        container:
            image: crazyuploader/minimal_ubuntu:latest
            env:
                IS_PRODUCTION: true
```

If no other options are specified, we can simply write -

```yaml
jobs:
    container-job:
        runs-on: ubuntu-latest
        container: crazyuploader/minimal_ubuntu:latest
```

## 2. Defining credentials for a container registry

```yaml
container:
    image: crazyuploader/private_container
    credentials:
        username: ${{ secrets.USERNAME }}
        password: ${{ secrets.PASSWORD }}
```

***Reference:*** [***GitHub Actions - GitHub Docs***](https://docs.github.com/en/actions/writing-workflows/choosing-where-your-workflow-runs/running-jobs-in-a-container)


# Setting An Environment Variable

Environment Variables can be specified in the following format:

```bash
echo "{environment_variable_name}={value}" >> $GITHUB_ENV
```

## Example

```yaml
steps:
    - name: Setting the environment variable
    run: |
        echo "GIT_VERSION=$(git --version)" >> $GITHUB_ENV

    - name: Check Git version
    run: |
        echo "${GIT_VERSION}"
```

**Note:** Can also use `${{ env.GIT_VERSION }}` format to get the environment variable value.

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/57969570)


# Go

> Build fast, reliable, and efficient software at scale

Go is an open source programming language supported by Google.

### [Official Documentation](https://go.dev/doc/)

## TIL(s)

* [Convert String To Uppercase in Go](/go/convert-string-to-uppercase)
* [List All Possible GOOS And GOARCH](/go/list-all-possible-goos-and-goarch)
* [Print Go Version](/go/print-go-version)
* [Resolve Hostname To IP Address](/go/resolve-hostname-to-ip-address)
* [Trim Whitespaces From String](/go/trim-whitespaces-from-string)
* [Update Project Libraries To Latest](/go/update-project-libraries-to-latest)


# Convert String To Uppercase in Go

To convert a string to uppercase, we can take advantage of `strings` module of Golang.

## Example

```go
package main

import (
    "fmt"
    "strings"
)

func main() {
    myString := "Hello!"
    fmt.Println(strings.ToUpper(myString))
}
```

***Source:*** [***GeeksForGeeks***](https://www.geeksforgeeks.org/how-to-convert-a-string-in-uppercase-in-golang/)


# List All Possible GOOS And GOARCH In Go

We can list all possible GOOS and GOARCH in Go using the following command -

```bash
go tool dist list
aix/ppc64
android/386
android/amd64
android/arm
android/arm64
darwin/amd64
darwin/arm64
dragonfly/amd64
freebsd/386
freebsd/amd64
freebsd/arm
freebsd/arm64
freebsd/riscv64
illumos/amd64
ios/amd64
ios/arm64
js/wasm
linux/386
linux/amd64
linux/arm
linux/arm64
linux/loong64
linux/mips
linux/mips64
linux/mips64le
linux/mipsle
linux/ppc64
linux/ppc64le
linux/riscv64
linux/s390x
netbsd/386
netbsd/amd64
netbsd/arm
netbsd/arm64
openbsd/386
openbsd/amd64
openbsd/arm
openbsd/arm64
plan9/386
plan9/amd64
plan9/arm
solaris/amd64
wasip1/wasm
windows/386
windows/amd64
windows/arm
windows/arm64
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/30068222)


# Print Go Version

We can use [`runtime.Version`](https://pkg.go.dev/runtime#Version) function to print Go Version.

## Example

```go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    fmt.Println("Go version: " + runtime.Version())
}
```

***Source:*** [***GopherSnippets***](https://gophersnippets.com/how-to-print-go-version)


# Resolve Hostname To IP Address

[`net.LookupHost`](https://pkg.go.dev/net#LookupHost) can be used to resolve hostnames to IP addresses.

## Example

```go
addresses, err := net.LookupHost("google.com")
if err != nil {
    fmt.Println("Unkown Host")
} else {
    fmt.Println("Addresses:", addresses)
}
```

***Source:*** [***I Spy Code***](https://ispycode.com/GO/Network/Get-ipaddress-from-hostname)


# Trim Whitespaces From String

To remove whitespaces from a string, we can use [`strings.TrimSpace`](https://pkg.go.dev/strings#TrimSpace) function. It would remove leading and trailing spaces from the string.

## Example

```go
myString := strings.TrimSpace(" Hello World! ") // "Hello World!"
```

***Source:*** [***YourBasic***](https://yourbasic.org/golang/trim-whitespace-from-string/)


# Update Project Libraries To Latest

In a Go project, you can upgrade latest dependencies by running following command -

```bash
go get -u
go mod tidy
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/67202539)


# Learning Resource(s)

> Collection of learning resources that I've came across so far.

## List of Learning Resources

* [Algorithms](/learning-resources/algorithms)
* [DevOps](/learning-resources/devops)
* [Git](/learning-resources/git)
* [Linux](/learning-resources/linux)
* [Networking](/learning-resources/networking)
* [Programming Languages](/learning-resources/programming-languages)


# Algorithms

* [Visualgo](https://visualgo.net/)


# DevOps

* [90 Days of DevOps](https://github.com/crazyuploader/90DaysOfDevOps)
* [DevOps Exercises](https://github.com/bregman-arie/devops-exercises)
* [DevOps Roadmap](https://devopslifecycle.com/roadmaps)
* [DevOps Tutorial](https://www.guru99.com/devops-tutorial.html)

## AWS

* [AWS Tutorial](https://www.guru99.com/aws-tutorial.html)

## Cloud Computing

* [Cloud Computing Tutorial for Beginners: What is & Architecture](https://www.guru99.com/cloud-computing-for-beginners.html)

## Docker

* [Docker 101 Tutorial](https://www.docker.com/101-tutorial/)
* [Docker Curriculum](https://docker-curriculum.com/)
* [The Docker Handbook – Learn Docker for Beginners](https://www.freecodecamp.org/news/the-docker-handbook/)


# Git

* [GitKraken - Git Tutorials](https://www.gitkraken.com/learn/git/tutorials)
* [Learning Git Branching](https://learngitbranching.js.org/)

## Cheatsheet(s)

* [GitLab](https://about.gitlab.com/images/press/git-cheat-sheet.pdf)
* [Atlassian](https://www.atlassian.com/git/tutorials/atlassian-git-cheatsheet)


# Linux

* [Guru99 Linux Tutorial](https://www.guru99.com/unix-linux-tutorial.html)
* [Linux Journey](https://linuxjourney.com/)
* [TechMint](https://www.tecmint.com/free-online-linux-learning-guide-for-beginners/)
* [The Linux Commands Handbook](https://www.freecodecamp.org/news/the-linux-commands-handbook/)
* [The Linux Command Line for Beginners](https://ubuntu.com/tutorials/command-line-for-beginners#1-overview)
* [iximiuz Labs](https://labs.iximiuz.com/)

## DNF Command(s)

* [Appendix A. DNF commands list](https://docs.redhat.com/en/documentation/red_hat_enterprise_linux/9/html/managing_software_with_the_dnf_tool/assembly_yum-commands-list_managing-software-with-the-dnf-tool)


# Networking

* [FreeCodeCamp Computer Network Posts](https://www.freecodecamp.org/news/tag/computer-networking/)
* [Guru99 Computer Network Tutorial](https://www.guru99.com/data-communication-computer-network-tutorial.html)

## YouTube

* [Computer Network Course - FreeCodeCamp](https://www.youtube.com/watch?v=qiQR5rTSshw)


# Programming Languages

* [Learn C++](https://learn-cpp.org/)
* [Learn Go](https://www.learn-golang.org/)
* [Learn Java](https://learnjavaonline.org/)
* [Learn JavaScript](https://learn-js.org/)
* [Learn Shell](https://learnshell.org/)

## Python

* [Byte of Python](https://python.swaroopch.com/)
* [Learn Python](https://learnpython.org/)
* [Programiz](https://www.programiz.com/python-programming)
* [Python Tutorials](https://www.guru99.com/python-tutorials.html)
* [The Python Handbook](https://www.freecodecamp.org/news/the-python-handbook/)

## Go

* [Essential Go](https://www.programming-books.io/essential/go/)
* [Go Development](https://tutorialedge.net/golang/)
* [Go from the beginning](https://softchris.github.io/golang-book/)
* [Golang Docs](https://golangdocs.com/)
* [Golang Programs](https://www.golangprograms.com/)
* [GOSAMPLES](https://gosamples.dev/)
* [Learn Go](https://learn-go.org/)
* [Learn Go With Tests](https://github.com/quii/learn-go-with-tests)
* [The Little Go Book](https://www.openmymind.net/The-Little-Go-Book/)
* [Your Basic](https://yourbasic.org/golang)


# Linux

> Linux is a family of open-source Unix-like operating systems based on the Linux kernel.

## Subcategories

* [Alpine Linux](/linux/alpine)
* [Apt](/linux/apt)
* [Arch Linux](/linux/arch)
* [BASH](/linux/bash)
* [Curl](/linux/curl)
* [GPG](/linux/gpg)
* [Grep](/linux/grep)
* [Journalctl](/linux/journalctl)
* [Networking](/linux/networking)
* [Raspberry Pi](/linux/raspberry-pi)
* [SSH](/linux/ssh)
* [Systemd](/linux/systemd)
* [Tcpdump](/linux/tcpdump)
* [Ubuntu Linux](/linux/ubuntu)
* [Wget](/linux/wget)

## TIL(s)

* [Add Swap Space To System](/linux/add-swap-space-to-system)
* [Add User To System](/linux/add-user-to-system)
* [Beautify Logs](/linux/beautify-logs)
* [Benchmark System](/linux/benchmark-system)
* [Ccze Scrolling Output](/linux/ccze-scrolling-output)
* [Change Default Shell](/linux/change-default-shell)
* [Change Hostname Of A system](/linux/change-hostname-of-a-system)
* [Changing User Password In Shell Script](/linux/changing-user-password-in-shell-script)
* [Check Group Of A User](/linux/check-group-of-a-user)
* [Check If A Package Is Installed Or Not](/linux/check-if-a-package-is-installed-or-not)
* [Check If A Port Is In Use](/linux/check-if-a-port-is-in-use)
* [Check If A User Exists](/linux/check-if-a-user-exists)
* [Check Open Port](/linux/check-open-port)
* [CMake Parallel Build with All Cores](/linux/cmake-parallel-build-with-all-cores)
* [Create Symbolic Links](/linux/create-symbolic-links)
* [Determine Which Process Is Using a File](/linux/determine-which-process-is-using-a-file)
* [Enable SSH Server](/linux/enable-ssh-server)
* [Fix Permission For Newly Created Partitions](/linux/fix-permission-for-newly-created-partitions)
* [Fix Windows And Linux Different Time Issue](/linux/fix-windows-and-linux-different-time-issue)
* [Get Arch Of System](/linux/get-arch-of-system)
* [Increase Limit of Inotify Watchers](/linux/increase-limit-of-inotify-watchers)
* [Install Latest NodeJS In Linux](/linux/install-latest-nodejs-in-linux)
* [Install Pavucontrol](/linux/install-pavucontrol)
* [Install Postman](/linux/install-postman)
* [Kill A Process In Linux](/linux/kill-a-process-in-linux)
* [Mount Partition On System Startup](/linux/mount-partition-on-system-startup)
* [OpenVPN Server](/linux/openvpn-server)
* [Ping over TCP](/linux/ping-over-tcp)
* [Pipe Password to Sudo](/linux/pipe-password-to-sudo)
* [Remove PPA From System](/linux/remove-ppa-from-system)
* [Remove User Password](/linux/remove-user-password)
* [Root Check in Scripts](/linux/root-check)
* [Run Go Binaries Without Installing Go](/linux/run-go-binaries-without-installing-go)
* [Set Different Time Zone](/linux/set-different-time-zone)
* [Show Disk Usage By Directories](/linux/show-disk-usage-by-directories)
* [Show Public IP](/linux/show-public-ip)
* [Show Size of Current Directory](/linux/show-size-of-current-directory)
* [System Ugprade](/linux/system-upgrade)
* [Tar Exclude Directories](/linux/tar-exclude-directories)
* [Tar Retain File Permissions](/linux/tar-retain-file-permissions)
* [Why All Users Can Write to /tmp](/linux/why-all-users-can-write-to-tmp)


# Add Swap Space To System

We can add swap space to the system by following method -

## Check for existing swap space

```bash
sudo swapon --show
```

## Create a new swap space

```bash
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
```

## Enable swap space

```bash
sudo mkswap /swapfile
sudo swapon /swapfile
```

## Verify that the swap space exists

```bash
sudo swapon --show
```

## Make swap persistent upon restart

```bash
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
```

***Source:*** [***DigitalOcean***](https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-ubuntu-20-04)


# Add User To System

To add a new user to the system, we can use `useradd` command.

## Create A User

### Step 1

```bash
sudo useradd -m {USER_NAME}
```

**Note:** `-m` or `--create-home` argument here creates home directory as well.

### Step 2

To be able to login into the new user, we need to set password first.

```bash
sudo passwd {USER_NAME}
```

## Create A User with specific login shell

To create a user with specific login shell, we can pass `-s` or `--shell` argument.

```bash
sudo useradd -s /usr/bin/zsh {USER_NAME}
```

## Add User to sudo group

In order to run commands as root, we can add user to `sudo` group by using `usermod` command.

```bash
usermod -aG sudo {USER_NAME}
```

***Source(s)***

* [Linuxize](https://linuxize.com/post/how-to-create-users-in-linux-using-the-useradd-command/)
* [Linuxize](https://linuxize.com/post/how-to-create-a-sudo-user-on-ubuntu/)


# Beautify Logs

We can use `ccze` command to beautify/prettify logs of different types. Usage given below.

## Installation

On Debian based systems, we can install it by running the following command -

```bash
apt-get install -y ccze
```

## Examples

We can pipe differnet logs through standard output such as -

```
cat /var/log/auth.log | ccze
```

***Source:*** [***CentOS Blog***](https://www.centosblog.com/command-line-tool-day-ccze-prettify-logs-colours/)


# Benchmark System

`sysbench` can be used to benchmark CPU, command is given below.

```bash
sysbench cpu --threads=$(nproc --all) run
```

### More Scripts: -

* [bench.sh](https://raw.githubusercontent.com/teddysun/across/master/bench.sh) [(Across)](https://github.com/teddysun/across)
* [nench.sh](http://wget.racing/nench.sh) [(Nench)](https://github.com/n-st/nench)
* [yabs.sh](https://raw.githubusercontent.com/masonr/yet-another-bench-script/master/yabs.sh) [(Yet Another Bench Script)](https://yabs.sh)

***Source:*** [***AskUbuntu***](https://askubuntu.com/questions/634513/cpu-benchmarking-utility-for-linux)


# Ccze Scrolling Output

Scrolling output is not possible with `ccze` by default, use `--mode=ansi` to disable this behavior.

## Example

```bash
cat /var/log/auth.log | ccze --mode=ansi
```

***Source:*** [***Unix - StackExchange***](https://unix.stackexchange.com/a/278283)


# Change Default Shell

Default shell can be changed by using `chsh` command.

## Usage

To see available shells -

```bash
cat /etc/shells
```

To see current shell -

```bash
echo $SHELL
```

To **finally** change shell -

```bash
chsh -s /path/to/shell
```

To see your new shell -

```bash
echo $SHELL
```

It should be changed now, in case `chsh` throws something like `you may not change the shell for ${USER}`, follow along!

## Using `usermod`

To see current shell -

```bash
grep ${USER} /etc/passwd
```

To change shell -

```bash
sudo usermod --shell /bin/bash nameofuser
```

Verify it by running -

```bash
grep ${USER} /etc/passwd
```

***Source:*** [***Unix - StackExchange***](https://unix.stackexchange.com/a/558971)


# Change Hostname Of A System

Typically, hostname of a system is stored in `/etc/hostname`, and we can change that by writing a new hostname in `/etc/hostname` file.

## Method 1

1. Edit `/etc/hostname` with any text editor such as nano or vim, and replace the existing hostname -

```bash
sudo nano /etc/hostname
```

2. Save and reboot -

```bash
sudo reboot
```

## Method 2

Using `hostnamectl` command we can also set hostname, following is an example -

```
sudo hostnamectl set-hostname Dell-G15-5515
sudo reboot
```

To display current hostname, we can use `hostname` command.

***Source:*** [***CyberCiti***](https://www.cyberciti.biz/faq/ubuntu-change-hostname-command/)


# Changing User Password In Shell Script

In order to change in shell scripts, we have two options which are given below.

## Option 1

Using `passwd`

```bash
echo -e "{NEW_PASSWORD}\n{NEW_PASSWORD} | passwd {USER}
```

## Option 2

Using `chpasswd`

```bash
echo "{USER}:{NEW_PASSWORD} | chpasswd
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/11787889)


# Check Group Of A User

We can check group(s) a user is part of by following methods -

## Checking `/etc/group` File

```bash
cat /etc/group
```

## Using `groups` Command

```bash
group {USER_NAME}
```

Example -

```bash
jungle@Server01:~$ groups jungle
jungle : jungle sudo docker
```

***Source:*** [***GeeksForGeeks***](https://www.geeksforgeeks.org/how-to-check-the-groups-a-user-belongs-to-in-linux/)


# Check If A Package Is Installed Or Not

To check whether or not a package is installed, we can test with `dpkg` command.

## Usage

```bash
dpkg --status {PACKAGE_NAME}
```

## Example

```bash
dpkg --status sudo
Package: sudo
Status: install ok installed
Priority: important
Section: admin
Installed-Size: 2204
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Architecture: amd64
Version: 1.8.31-1ubuntu1.2
Replaces: sudo-ldap
Depends: libaudit1 (>= 1:2.2.1), libc6 (>= 2.27), libpam0g (>= 0.99.7.1), libselinux1 (>= 2.0.65), libpam-modules, lsb-base
Conflicts: sudo-ldap
Conffiles:
 /etc/pam.d/sudo aa40f755f85bb33c9e79bd537e2979be
 /etc/sudoers edcf6528783ecffd3f248c8089dc298e
 /etc/sudoers.d/README 8d3cf36d1713f40a0ddc38e1b21a51b6
Description: Provide limited super user privileges to specific users
 Sudo is a program designed to allow a sysadmin to give limited root
 privileges to users and log root activity.  The basic philosophy is to give
 as few privileges as possible but still allow people to get their work done.
 .
 This version is built with minimal shared library dependencies, use the
 sudo-ldap package instead if you need LDAP support for sudoers.
Homepage: http://www.sudo.ws/
Original-Maintainer: Bdale Garbee <bdale@gag.com>
```

***Source:*** [***CyberCiti***](https://www.cyberciti.biz/faq/find-out-if-package-is-installed-in-linux/)


# Check If A Port Is In Use

We can check if a port is in use or not, by following ways in Linux.

## Option 1

`lsof`

```bash
sudo lsof -i -P -n | grep LISTEN
```

Also, we can check a specific port by running -

```bash
sudo lsof -i:{PORT_NUMBER}
```

## Option 2

`netstat`

```bash
sudo netstat -tulpn | grep LISTEN
```

## Option 3

`nmap`

```bash
sudo nmap -sTU -O {IP_ADDRESS}
```

***Source:*** [***CyberCiti***](https://www.cyberciti.biz/faq/unix-linux-check-if-port-is-in-use-command/)


# Check If A User Exists

We can check if a user exists on Linux System by `id` command.

> id - print real and effective user and group IDs

## Example

```bash
id -u jungle
1000
```

If a user does not exists on system, it throws an error. For example -

```bash
id -u unknown
id: ‘unknown’: no such user
```

***Source:*** [***StackOverFlow***](https://stackoverflow.com/a/14811915)


# Check Open Port

Command `nmap` can be used to scan an IP for open ports. The syntax for the same is given below -

```bash
nmap -Pn {IP_ADDRESS}
```

Replace `IP_ADDRESS` with the IP to be scanned.


# CMake Parallel Build with All Cores

Recently, while trying to compile Traffic Server, came across very poor performance issues, turns out the build was only taking one core, and so in order to use all the cores on the system, we can use `-j` or `--parallel` to specify the number of jobs to run in parallel.

## Example

```bash
cmake --build build -j $(nproc --all)

# or

cmake --build build --parallel $(nproc --all)
```

**Note:** This will use up all the cores/threads on the system, which may mean the system becomes very slow, and laggy. So, one may choose to free up a CPU by using following command.

```bash
cmake --build build --parallel $(($(nproc --all) - 1))
```

***Source(s):***

* [StackOverFlow](https://stackoverflow.com/a/70552553)
* [StackOverFlow](https://stackoverflow.com/a/41691009)

***Reference:*** [***CMake - Documentation***](https://cmake.org/cmake/help/latest/manual/cmake.1.html#cmdoption-cmake-build-j)


# Create Symbolic Links

> ln - make links between files

`ln` command is used to create a symbolic link. By default `ln` creates a hard link, but we can use `-s` option to create a symbolic link.

## Usage

### Adding Symbolic Links

```bash
ln -s {ORIGINAL_FILE} {LINKED_FILE}
```

This will create a symbolic link.

```bash
ln -sf {ORIGINAL_FILE} {LINKED_FILE}
```

**Note:** `-f` option overwrites the exisiting symbolic link.

### Adding Symbolic Links Between Directories

```bash
ln -s {ORIGINAL_DIRECTORY} {DIRECTORY_TO_BE_LINKED}
```

This creates a symbolic link link between two directories.

### Deleting Symbolic Links

To remove a symbolic link, we can either remove the linked file by using `rm` or use `unlink` to do the same thing.

```bash
rm {LINKED_FILE}
unlink {LINKED_FILE}
```

***Source:*** [***phoenixNAP***](https://phoenixnap.com/kb/symbolic-link-linux)


# Determine Which Process Is Using a File

We can use `lsof` command to determine which process is using a file.

## Usage

```bash
lsof file/path
```

***Source:*** [***Unix - StackExchange***](https://unix.stackexchange.com/a/13791)


# Enable SSH Server

Sometimes, we need to access our machine remotely, and that is where SSH (Secure Shell) comes into play. Enabling SSH Server on Ubuntu is straightforward, we just need to have `openssh-server` package installed which we can install by -

### Install SSH Server

```bash
sudo apt-get update
sudo apt-get install -y openssh-server
```

To check whether or not the SSH Server is running run -

```bash
sudo systemctl status ssh
```

### Open port for SSH Server in Firewall

```bash
sudo ufw allow ssh
```

## Connecting to SSH Server

```bash
ssh {USER}@{MACHINE_IP}
```

**Note:** In case `ssh` command is not available, one need to install `openssh-client` package.

***Source:*** [***Linuxize***](https://linuxize.com/post/how-to-enable-ssh-on-ubuntu-20-04/)


# Fix Permission For Newly Created Partitions

For an `ext4` like file system, we need to change permissions before an user is able to access it, we can do so by running -

```bash
sudo chown -R $USER:$USER /data
```

Where `/data` is the location of the mounted drive.

***Source:*** [***AskUbuntu***](https://askubuntu.com/a/703676)


# Fix Windows And Linux Different Time Issue

While dual booting `Windows` and `Linux` there is time difference between both of the OSes, this arises because of the fact that while `Linux` saves time on motherboard's clock in *UTC*, `Windows` save it in *Local Time*, this makes one of Operating System to have a different/wrong time than it actually is (Windows for me personally).

This can be fixed by either setting `Linux` to use *Local Time* instead of *UTC* or setting `Windows` to use *UTC* time. Since setting this on `Windows` can be a little complicated, we can simply run one command on `Linux` and we're good to go!

## Process

We can set `Linux` to use *Local Time* by running -

```bash
timedatectl set-local-rtc 1 --adjust-system-clock
```

Check current settings by running -

```
timedatectl
```

***Source:*** [***HowToGeek***](https://www.howtogeek.com/323390/how-to-fix-windows-and-linux-showing-different-times-when-dual-booting/)


# Get Arch Of System

An alternative to `uname -m` to see what is the architecture of the system is `arch`, which is short and self-explaining.

## Example

```bash
arch
x86_64
```

***Source:*** [***RedHat***](https://www.redhat.com/sysadmin/5-linux-commands)


# Increase Limit of Inotify Watchers

To check current limit of inotify watchs:

```bash
cat /proc/sys/fs/inotify/max_user_watches
```

To change Inotify watch limit:

```bash
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf
sudo sysctl -p
```

***Source:*** [***GitHub***](https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers#the-technical-details)


# Install Latest NodeJS In Linux

We can get latest version of NodeJS by -

## Setup

### Setting APT Repositories

```bash
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
```

**Note:** This will setup NodeJS 16 on the system.

### Installing NodeJS

```bash
sudo apt-get install -y nodejs
```

This will install NodeJS and NPM.

***Source:*** [***JoshTronic***](https://joshtronic.com/2020/10/25/how-to-install-nodejs-15-on-ubuntu/)

**Reference(s)**

* [NodeSource Distributions - GitHub](https://github.com/nodesource/distributions)


# Install Pavucontrol

> pavucontrol - A volume control for the PulseAudio sound server

## Ubuntu

```bash
sudo apt-get install pavucontrol
```

Or QT Version

```
sudo apt-get install pavucontrol-gt
```

## Arch

```bash
sudo pacman -S pavucontrol
```

Or QT Version

```bash
sudo pacman -S pavucontrol-gt
```

## Fedora

```bash
sudo dnf install pavucontrol
```

Or QT Version

```bash
sudo dnf install pavucontrol-gt
```

## OpenSUSE

```bash
sudo zypper install pavucontrol
```

Or QT Version

```bash
sudo zypper install pavucontrol-gt
```

***Source:*** [***AddictiveTips***](https://www.addictivetips.com/ubuntu-linux-tips/manage-audio-devices-on-linux-pavucontrol/)


# Install Postman

We can use `snap` to install Postman in Ubuntu using snappy.

### Install Postman

```bash
sudo snap install postman
```

***Source:*** [***Linuxize***](https://linuxize.com/post/how-to-install-postman-on-ubuntu-20-04/)


# Kill A Process In Linux

To kill a process, first we need to know its process ID (PID), to do that we can use `pidof` command.

## Find PID of a Process

```bash
pidof {PROCESS_NAME}
```

## Kill a Process

```bash
kill {PROCESS_ID}
```

### Kill all the process with a program name

```bash
killall {PROGRAM_NAME}
```

### Using htop

We can also kill a process interactively using `htop` command.

**Reference(s)**

* [StackOverFlow](https://askubuntu.com/questions/104903/how-do-i-kill-processes-in-ubuntu)
* [Man7](https://man7.org/linux/man-pages/man1/htop.1.html)


# Mount Partition On System Startup

We can mount a partition at system startup by using `disks` program, which can automatically edit `/etc/fstab` for us. Launch it by running `gnome-disks` in terminal, go to desire partition, click on "Edit Mount Options".

***Step By Step GUI Guide:*** [***AskUbuntu***](https://askubuntu.com/a/375319)


# OpenVPN Server

OpenVPN Server easy installer for Linux.

**Usage**

Get script and make it executable:

```bash
curl -O https://raw.githubusercontent.com/angristan/openvpn-install/master/openvpn-install.sh
chmod +x openvpn-install.sh
```

To install OpenVPN, run:

```bash
./openvpn-install.sh
```

***Source:*** [***GitHub***](https://github.com/angristan/openvpn-install)


# Ping over TCP

`ping` can't do TCP ping so in order to run ping for TCP we can use `tcpping`.

## Installation

Firstly we have to make sure `tcptraceroute` is installed by running -

```bash
apt-get install -y tcptraceroute
```

Then to install tcpping, run -

```bash
wget http://www.vdberg.org/~richard/tcpping -O /usr/bin/tcping
chmod 755 /usr/bin/tcping
```

***Note:*** I am saving `tcpping` as `tcping` here

### Example

```bash
jungle@DESKTOP-B73I3A0:~$ tcping -x 5 google.com
seq 0: tcp response from del11s07-in-f14.1e100.net (216.58.200.206) [open]  60.454 ms
seq 1: tcp response from del11s07-in-f14.1e100.net (216.58.200.206) [open]  78.215 ms
seq 2: tcp response from del11s07-in-f14.1e100.net (216.58.200.206) [open]  55.457 ms
seq 3: tcp response from del11s07-in-f14.1e100.net (216.58.200.206) [open]  53.049 ms
seq 4: tcp response from del11s07-in-f14.1e100.net (216.58.200.206) [open]  48.375 ms
```

***Source:*** [***GitHub Gist***](https://gist.github.com/cnDelbert/5fb06ccf10c19dbce3a7)


# Pipe Password to Sudo

So while trying to create an automated script for Docker to start running my container, I need to pass root's password to sudo in order to run `docker start _containerID_`. The way to do is given below -

```bash
echo "YOUR_PASSWORD_HERE" | sudo -S {COMMAND_TO_RUN_AS_ROOT}
```

The command to start Docker service was -

```bash
echo "SECRET" | sudo -S service docker start
```

And that was all, for me to pass the password to `sudo` without actually writing the password again!

Thing to note here is that passing `-S` makes `sudo` to read password from *stdin*.

***Original Question on*** [***Unix - StackExchange***](https://unix.stackexchange.com/questions/391796/pipe-password-to-sudo-and-other-data-to-sudoed-command)


# Remove PPA From System

To remove PPA from system, we can use either of the following methods -

## Method 1

We can use `--remove` flag in `add-apt-repository` command

```bash
sudo add-apt-repository --remove ppa:example/ppa
```

## Method 2

We can use `ppa-purge`

```bash
sudo apt-get install ppa-purge
sudo ppa-purge ppa:example/ppa
```

***Source:*** [***ItsFoss***](https://itsfoss.com/how-to-remove-or-delete-ppas-quick-tip/)


# Remove User Password

### Background

Since, I recently removed my dual boot setup, I started using Ubuntu in Windows 10 WSL 2. Initially had setup password for the same, and now since I run some Docker images in it (Docker is supported in WSL 2), and due to the lack of "systemd" in WSL for Windows, I needed some way to run Docker at system boot, one way of doing was to use `systemd` which manages services for various Linux Distros at boot, but while trying to run `sudo systemctl enable docker`, I had the following error -

```
System has not been booted with systemd as init system (PID 1). Can't operate.
```

Turns out WSL doesn't have `systemd` yet, so the only way to run Docker service is to use `service` command which is given below -

```bash
sudo service docker start
```

The only way for now I see Docker running as soon as I open Ubuntu in WSL is to put the above command in `~/.bashrc` file, and for Windows to run WSL upon login is simple, using Task Scheduler. Dirty tricks indeed, but as long as my work is done nothig else matters. The command I had to put in `~/.bashrc` file was -

```bash
sudo service docker start
```

### Solution

To properly remove the password of the current user, and making sure `sudo` works with no password, we need to enable `NOPASSWORD` first. Without it, sudo will ask for password even if we don't have one.

> To do so, open the sudoers configuration file with `sudo visudo`, and add the following line to the file, replacing jungle with your username:

```
jungle ALL=(ALL) NOPASSWD:ALL
```

And what's left for us to remove the password of the current user is to run:

```bash
sudo passwd -d `whoami`
```

***Original Question on*** [***StackOverFlow here***](https://askubuntu.com/questions/281074/can-i-set-my-user-account-to-have-no-password)


# Root Check

While trying to add a script which would install [`tmate`](https://github.com/tmate-io/tmate/), but for me to be able to put executables under `bin` folder would require a root permission. So, before trying to put the executables in the `bin`, permission check was a must. Though, checking if running as root isn't that hard using `whoami` command.

```bash
if [[ "${USER}" -ne "root" ]]; then
    echo "Can only run as root"
    exit 1
fi
```

I would've used this approach, but as an answer on StackOverFlow stated

> "As a **warning**, do not check if a user is root by using the root username. Nothing guarantees that the user with ID 0 is called `root`. It's a very strong convention that is broadly followed but anybody could rename the superuser another name."

which I think does makes sense. So, that's why the other way around do the same is to check EUID variable, which is, in fact, read-only variable initialized at shell start-up.

```bash
if [[ "${EUID}" -ne "0" ]]; then
    echo "Can only run as root"
    exit 1
fi
```

Which pretty much worked for me the way I intended it to.

***See the original question on*** [***StackOverFlow here***](https://stackoverflow.com/questions/18215973/how-to-check-if-running-as-root-in-a-bash-script)


# Run Go Binaries Without Installing Go

We can run Go binaries without installing Go, by using [GoBinaries](https://gobinaries.com/) which allows Go programs to be installed from command line only.

## Example

```bash
curl -sf https://gobinaries.com/rakyll/hey | sh
```

### Limitations

* The package must compile within 100 seconds
* The package must have at least on tag

***Source:*** [***GoBinaries***](https://gobinaries.com/)


# Set Different Time Zone

We can change time zone temporarily by using `TZ` Environment Variable but for permanent change we can use following ways to set different time zone in linux.

## Using timedatectl

```bash
sudo timedatectl set-timezone {TIME_ZONE}
```

**Example**

```bash
sudo timedatectl set-timezone Asia/Kolkata
```

## Using symbolic link

Firstly, we to remove current symbolic link by -

```bash
sudo rm -rf /etc/localtime
```

Then subtitute your time zone in following command

```bash
sudo ln -s /usr/share/zoneinfo/Asia/Kolkata /etc/localtime
```

Verify it by running `date` command

***Source:*** [***Linuxize***](https://linuxize.com/post/how-to-set-or-change-timezone-in-linux/)


# Show Disk Usage By Directories

We can use `ncdu` to see disk usage interactively in command-line only.

> ncdu (NCurses Disk Usage) is a curses-based version of the well-known 'du', and provides a fast way to see what directories are using your disk space.

**Usage**

```bash
ncdu {OPTIONS} {DIRECTORY}
```

**Example**

```
ncdu -x /
```

Will show usage of `/` (root) directory.

***Source:*** [***AskUbuntu***](https://askubuntu.com/a/305057)


# Show Public IP

Public IP Address using `dig` can be obtained using command:

```bash
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com
```

Alternate using `curl`:

```bash
curl ifconfig.me
```


# Show Size of Current Directory

Size of current directory can be seen by using `du` command.

## Usage

To see size of current directory -

```bash
du -sh
```

To see size of a different directory -

```bash
du -sh /var
```

`/var` is the path to the directory you want to see the size of

***Source:*** [***Linuxize***](https://linuxize.com/post/how-get-size-of-file-directory-linux/)




---

[Next Page](/llms-full.txt/1)

