<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Everything is Broken</title>
	<atom:link href="https://play.datalude.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>https://play.datalude.com/blog</link>
	<description>Efficiency vs. Inefficiency, in a no-holds barred fight.</description>
	<lastBuildDate>Mon, 30 Nov 2026 02:18:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.5</generator>
	<item>
		<title>Using restic for mysql backups</title>
		<link>https://play.datalude.com/blog/2026/11/using-restic-for-mysql-backups/</link>
					<comments>https://play.datalude.com/blog/2026/11/using-restic-for-mysql-backups/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Mon, 30 Nov 2026 02:14:36 +0000</pubDate>
				<category><![CDATA[Bash Script]]></category>
		<category><![CDATA[General IT]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=825</guid>

					<description><![CDATA[I had previously set up a bash script to backup a mysql database. It created daily dumps, gzipped them, and retained 7 daily, 4 weekly and 3 monthly backups via a system of symlinking. That all worked fine for a few years, but I revisited it more recently as we now wanted to keep an ... <a title="Using restic for mysql backups" class="read-more" href="https://play.datalude.com/blog/2026/11/using-restic-for-mysql-backups/" aria-label="Read more about Using restic for mysql backups">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">I had previously set up a bash script to backup a mysql database. It created daily dumps, gzipped them, and retained 7 daily, 4 weekly and 3 monthly backups via a system of symlinking. That all worked fine for a few years, but I revisited it more recently as we now wanted to keep an offsite copy of the backups, and that would require encrypting them. The problem is gzip doesn't do encryption, so we needed to explore a few options, so I went through gpg, zip with password, etc, and then came to restic. </p>



<span id="more-825"></span>



<p class="wp-block-paragraph">I've used restic in many other backup scenarios, but I figured it wouldn't be good with database backups. An sql dump file, I reasoned, would have a few tables that had changed, and many that hadn't. So I was thinking that maybe the answer was to loop through the database, dump each table, and then send those to a restic repo. But then I asked my friendly (too friendly) AI and it told me that I had misunderstood how restic does backups, and it actually uses "Content Defined Chunking" to address the exact problem I was facing. Its a bit math-y, but TLDR: go ahead and do a single dump, and content defined chunking will figure out the bits that are the same, and you'll still get a space efficient incremental backup. (And encrypted of course as that was the original aim). </p>



<p class="wp-block-paragraph">Too good to be true? I'd have to test that out.  So I took two consecutive days files and added them to a restic test repo. Wow. The .sql dump file was the same size of course, but the first restic backup was smaller than the gzipped file. And then adding the second, only increased the total data size by 10%. So I re-wrote the script, and now I've been running that for a few days, here are the results. </p>



<p class="wp-block-paragraph"><strong>Before: </strong>Database dump 4.5Gb. Gzipped file ~ 650Mb. Retaining 14 of them costs 9Gb.</p>



<p class="wp-block-paragraph"><strong>After 5 days of running the new script:</strong> Database dump 4.5Gb. Restic backup actual disk size ~750Gb with 5 incremental backups, so maybe around 1Gb for 14 of them? I'll update this post later when the results are in.</p>



<p class="wp-block-paragraph">So looks like we're on for a substantial space saving. In addition, </p>



<ul class="wp-block-list">
<li>the backup now takes half the time, down from 113 sec to 60.</li>



<li>Server load is better during the backup as dumping mysql through gzip seemed quite CPU heavy, whereas dump to plain file in a temporary folder, then let restic compress it seems lighter. </li>



<li>the script is a lot smaller and cleaner, as restic does all the backup rotation for me with restic forget &#8211;prune. </li>



<li>Encrypted, incremental backups achieved. </li>
</ul>



<pre class="wp-block-code"><code>#!/bin/bash

set -Eeuo pipefail

## Configuration

DB_USER="databaser"
DB_HOST="localhost"

DATABASES="mysql database2 database3"

MAX_DAILY_BACKUPS=7
MAX_WEEKLY_BACKUPS=4
MAX_MONTHLY_BACKUPS=3

# Restic configuration
export RESTIC_REPOSITORY="/data/database-backups/"
export RESTIC_PASSWORD="adfadfasdfasdfasdf"

# Directories
LOG_DIR="/data/database-backups/backup-logs"
TEMP_DUMP_DIR="/data/db-backup-temp"

## Initialisation

LOG_FILE="$LOG_DIR/$(date +%F)_dbbackup.log"

# Send stdout and stderr to log
exec >> "$LOG_FILE" 2>&amp;1

# Remove logs older than 30 days
find "$LOG_DIR" -maxdepth 1 -type f -name '*_dbbackup.log' -mtime +30 -delete


# Error handling

send_alert() {
    local MESSAGE="$1"

    # add your mail, webhook etc here. 
}

error_handler() {
    local exit_code=$1
    local line_number=$2
    local failed_command=$3

    # Prevent error handler from triggering itself
    trap - ERR

    MESSAGE="Database backup FAILED on $(hostname). Exit code: $exit_code. Line: $line_number"

    echo
    echo "=========================================="
    echo "ERROR: $MESSAGE"
    echo "Failed command: $failed_command"
    echo "Time: $(date)"
    echo "=========================================="

    send_alert "$MESSAGE"

    exit "$exit_code"
}

trap 'error_handler "$?" "$LINENO" "$BASH_COMMAND"' ERR


# Backup process

SECONDS=0

echo "=========================================="
echo "Starting mysql backup: $(date)"
echo "=========================================="

# Clean up SQL files from previous runs
echo
echo "Removing previous SQL dumps..."

find "$TEMP_DUMP_DIR" -maxdepth 1 -type f -name '*.sql' -print -delete

# Dump databases
for DB in $DATABASES; do

    echo
    echo "Dumping database: $DB at $SECONDS seconds"

    DUMP_FILE="$TEMP_DUMP_DIR/${DB}_$(date +%F).sql"

    mysqldump -h "$DB_HOST" -u "$DB_USER" \
        --single-transaction --quick --routines --events --triggers \
        "$DB" > "$DUMP_FILE"

    echo "Successfully dumped $DB ($(du -h "$DUMP_FILE" | cut -f1))"

    # Give database a break between dumps
    sleep 10

done

# Restic backup and rotate

echo
echo "Adding SQL dumps to restic repository..."

restic backup "$TEMP_DUMP_DIR" \
    --tag mysql \
    --host "$(hostname -f)"
echo
echo "Applying retention policy..."

restic forget \
    --tag mysql \
    --keep-daily "$MAX_DAILY_BACKUPS" \
    --keep-weekly "$MAX_WEEKLY_BACKUPS" \
    --keep-monthly "$MAX_MONTHLY_BACKUPS" \
    --prune

echo
echo "Getting repo stats ..."
restic stats --mode raw-data

echo
echo "=========================================="
echo "Database backup completed successfully."
echo "Duration: $SECONDS seconds"
echo "Finished: $(date)"
echo "=========================================="
</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2026/11/using-restic-for-mysql-backups/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Bash alias trick: show multiple timezones</title>
		<link>https://play.datalude.com/blog/2026/10/bash-alias-trick-show-multiple-timezones/</link>
					<comments>https://play.datalude.com/blog/2026/10/bash-alias-trick-show-multiple-timezones/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Tue, 27 Oct 2026 03:12:45 +0000</pubDate>
				<category><![CDATA[Bash Script]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=822</guid>

					<description><![CDATA[Just a dumb trick I whipped up and was inordinately proud of. Sure I could go along to timeanddate dot com but I spend a lot of my time in my terminal and this is immediate. Small effort big payback. OK, so the code is just this, added to .bashrc The first block is the ... <a title="Bash alias trick: show multiple timezones" class="read-more" href="https://play.datalude.com/blog/2026/10/bash-alias-trick-show-multiple-timezones/" aria-label="Read more about Bash alias trick: show multiple timezones">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Just a dumb trick I whipped up and was inordinately proud of. Sure I could go along to timeanddate dot com but I spend a lot of my time in my terminal and this is immediate. Small effort big payback. </p>



<p class="wp-block-paragraph">OK, so the code is just this, added to .bashrc</p>



<pre class="wp-block-code"><code>tztime() {
  for tz_name in "$@"; do
    printf "    In %-15s its %s\n" "$tz_name" "$(TZ=$tz_name date +'%H:%M:%S %Z')"
  done
}
alias teamtime='tztime America/Chicago UTC Europe/London Asia/Manila Asia/Tokyo'
</code></pre>



<p class="wp-block-paragraph">The first block is the function that does all the work, formatting the dates nicely. </p>



<ul class="wp-block-list">
<li><code>for tz_name in "$@"; do</code> loops over all arguments supplied as space-separated array.</li>



<li><code>TZ=$tz_name <code>date +'%H:%M:%S %Z</code> </code>sets the <code>TZ</code> environment variable and then runs date with the specified format. (TZ in your shell remains unchanged)</li>



<li><code>%-15s</code> prints the time-zone name left-aligned in a field at least 15 characters wide. This was just to get them to align nicely</li>
</ul>



<p class="wp-block-paragraph">The alias is whatever you want to call it, and is basically a space separated list of timezones you want to look at. Edit away. Output:<br></p>



<pre class="wp-block-code"><code>teamtime
    In America/Chicago its 22:03:13 CDT
    In UTC             its 03:03:13 UTC
    In Europe/London   its 03:03:13 GMT
    In Asia/Manila     its 11:03:13 PST
    In Asia/Tokyo      its 12:03:13 JST
</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2026/10/bash-alias-trick-show-multiple-timezones/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Increasing Linux swapfile with minimal disruption: the swapfile shuffle</title>
		<link>https://play.datalude.com/blog/2026/04/increasing-linux-swapfile-with-minimal-disruption-the-swapfile-shuffle/</link>
					<comments>https://play.datalude.com/blog/2026/04/increasing-linux-swapfile-with-minimal-disruption-the-swapfile-shuffle/#comments</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 22 Apr 2026 07:54:06 +0000</pubDate>
				<category><![CDATA[General IT]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=805</guid>

					<description><![CDATA[Had a server which needed a bit more swap, but the current swap was at 100%, and it was marginal whether there was enough RAM to allow me to delete the current 2G swap and replace it with 4G. So I came up with the "swapfile shuffle". All good. Happy server.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Had a server which needed a bit more swap, but the current swap was at 100%, and it was marginal whether there was enough RAM to allow me to delete the current 2G swap and replace it with 4G. So I came up with the "swapfile shuffle". </p>



<pre class="wp-block-code"><code> # Lets see what we've got
swapon --show
NAME      TYPE SIZE USED PRIO
/swapfile file   2G   2G   -2

# Make a new temp swapfile and turn it on.
fallocate -l 2G /swapfile2
chmod 600 /swapfile2
mkswap /swapfile2
swapon /swapfile2

# Check progress
 htop -> 4G of active swap. Memory looks OK. 
 
# Looking good, so now we turn off the original swapfile, resize it and then turn it on
swapoff /swapfile
fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile

# Check again. 
htop -> Whoo, now have 6Gb swap

# Now can disable the temp swapfile 
swapoff /swapfile2 
rm /swapfile2
</code></pre>



<p class="wp-block-paragraph">All good. Happy server. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2026/04/increasing-linux-swapfile-with-minimal-disruption-the-swapfile-shuffle/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Removing all 5.xx kernels and associated modules, config from Ubuntu</title>
		<link>https://play.datalude.com/blog/2026/03/removing-all-5-xx-kernels-and-associated-modules-config-from-ubuntu/</link>
					<comments>https://play.datalude.com/blog/2026/03/removing-all-5-xx-kernels-and-associated-modules-config-from-ubuntu/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 06 Mar 2026 09:05:36 +0000</pubDate>
				<category><![CDATA[Bash Script]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=797</guid>

					<description><![CDATA[I was getting a bit cramped for space on the root partition of an older desktop, which has been running for 4 years or so, and discovered that although I'd been running the 6.x kernel for several years, there was a lot of baggage from 5.x kernels lying around. Here's a reminder to myself how ... <a title="Removing all 5.xx kernels and associated modules, config from Ubuntu" class="read-more" href="https://play.datalude.com/blog/2026/03/removing-all-5-xx-kernels-and-associated-modules-config-from-ubuntu/" aria-label="Read more about Removing all 5.xx kernels and associated modules, config from Ubuntu">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">I was getting a bit cramped for space on the root partition of an older desktop, which has been running for 4 years or so, and discovered that although I'd been running the 6.x kernel for several years, there was a lot of baggage from 5.x kernels lying around. Here's a reminder to myself how to clear it up. If you've done an inplace upgrade from Ubuntu 22 to 24, you're probably in the same position. <br><br>So first of all, check your running kernel. You definitely want to keep that one! Then check what kernels you've got installed</p>



<pre class="wp-block-code"><code># Current kernel
uname -r
6.8.0-101-generic
# What kernels do we have installed. 
# ii at the beginning of the line means installed, but rc entries might have some residual config files.
dpkg --list | grep 'linux-image-'</code></pre>



<p class="wp-block-paragraph">Now, if you're certain that you want to get rid of all the kernels beginning with 5.x, then go ahead and run the following. Or otherwise edit the commands so that you're disposing of the ones you want to get. </p>



<pre class="wp-block-code"><code>sudo apt remove $(dpkg --list | grep 'linux-image-5\.' | awk '{print $2}' | xargs)  
# And now we get rid of all the associated modules and headers
sudo apt remove $(dpkg --list | grep 'linux-headers-5\.' | awk '{print $2}' | xargs)
sudo apt remove $(dpkg --list | grep 'linux-modules-5\.' | awk '{print $2}' | xargs)   
sudo apt remove $(dpkg --list | grep 'linux-modules-extra-5\.' | awk '{print $2}' | xargs)
# And clean up
sudo apt autoremove --purge
sudo update-grub   </code></pre>



<p class="wp-block-paragraph">So that cleared over a Gigabyte. Ubuntu will generally (I think) keep the last 3 kernels, but sometimes it doesn't seem to clean up everything it can. </p>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2026/03/removing-all-5-xx-kernels-and-associated-modules-config-from-ubuntu/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Mail troubleshooting with curl.</title>
		<link>https://play.datalude.com/blog/2026/02/mail-troubleshooting-with-curl/</link>
					<comments>https://play.datalude.com/blog/2026/02/mail-troubleshooting-with-curl/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 26 Feb 2026 08:30:56 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=793</guid>

					<description><![CDATA[A docker container wasn't sending mail. I'd debugged the connection from the host machine and that was working, but once inside the container, there were no tools available. No mail, no mutt, no traceroute, no ping, no mtr, no netcat &#8230; so how to find out if the container could send to the mail server ... <a title="Mail troubleshooting with curl." class="read-more" href="https://play.datalude.com/blog/2026/02/mail-troubleshooting-with-curl/" aria-label="Read more about Mail troubleshooting with curl.">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">A docker container wasn't sending mail. I'd debugged the connection from the host machine and that was working, but once inside the container, there were no tools available. No mail, no mutt, no traceroute, no ping, no mtr, no netcat &#8230; so how to find out if the container could send to the mail server &#8230; </p>



<p class="wp-block-paragraph">Well it turns out curl was available and curl can help! This command was able to send a test email without any of the tools I'd normally use on a full OS. Sweet. </p>



<pre class="wp-block-code"><code>curl --url 'smtp://103.125.202.12:25' \
 --mail-from no_reply@pretend.org \
 --mail-rcpt mailtest@datalude.com \
 --upload-file - &lt;&lt;EOF
From: Mr Roboto &lt;no_reply@pretend.org>
To: Mailtest &lt;mailtest@datalude.com>
Subject: Robot Mail Test
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: quoted-printable
Content-Disposition: inline

So is it working? Maybe.
EOF</code></pre>



<p class="wp-block-paragraph">Other useful looking options, not needed this time were:<br>&#8211;ssl-reqd \<br>&#8211;user 'username:password' \<br></p>



<p class="wp-block-paragraph">I did find another even more rudimentary connectivity check, which I'll put here for kicks, which doesn't even need curl. </p>



<pre class="wp-block-code"><code>(echo >/dev/tcp/103.125.202.12/25) &amp;>/dev/null &amp;&amp; echo "open" || echo "closed"   </code></pre>



<p class="wp-block-paragraph">Its all about using what you've got. But then again if it wasn't for docker in the first place it would all have been a lot simpler &#8230;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2026/02/mail-troubleshooting-with-curl/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Bash script to replicate a directory structure</title>
		<link>https://play.datalude.com/blog/2025/12/bash-script-to-replicate-a-directory-structure/</link>
					<comments>https://play.datalude.com/blog/2025/12/bash-script-to-replicate-a-directory-structure/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 10 Dec 2025 06:17:08 +0000</pubDate>
				<category><![CDATA[Bash Script]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=789</guid>

					<description><![CDATA[I found a need for this once upon a time. It will descend through a Linux directory, get the permissions, ownership details for all the subdirs and then write a script for you to recreate it somewhere else. You use it like this. Script listing]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">I found a need for this once upon a time. It will descend through a Linux directory, get the permissions, ownership details for all the subdirs and then write a script for you to recreate it somewhere else. </p>



<p class="wp-block-paragraph">You use it like this. </p>



<pre class="wp-block-code"><code># Put the script in the parent directory of the one you want to clone and run it.
clone_directory_structure.sh targetdirectory &gt; regenerate_directory_structure.sh

# Then move the script to where you want to clone the directory and run it. 
regenerate_directory_structure.sh 
</code></pre>



<p class="wp-block-paragraph">Script listing</p>



<pre class="wp-block-code"><code>#!/bin/bash

# Check if directory is provided
if &#91; $# -ne 1 ]; then
    echo "Usage: $0 &lt;directory>"
    echo "Example: $0 /path/to/directory"
    exit 1
fi

# Remove trailing slash if present
TARGET_DIR="${1%/}"
TARGET_BASENAME="$(basename "$TARGET_DIR")"
TARGET_PARENT="$(dirname "$TARGET_DIR")"

# Check if directory exists
if &#91; ! -d "$TARGET_DIR" ]; then
    echo "Error: Directory '$TARGET_DIR' does not exist"
    exit 1
fi

echo "#!/bin/bash"
echo "# Script generated on $(date)"
echo "# To recreate the directory structure, run this script as root or with sudo"
echo "set -e  # Exit on error"
echo

# Process the target directory itself
echo "# Creating target directory: $TARGET_BASENAME"
echo "mkdir -p \"$TARGET_BASENAME\""

# Get permissions, owner, and group of the target directory
TARGET_PERMS=$(stat -c "%a" "$TARGET_DIR")
TARGET_OWNER=$(stat -c "%U" "$TARGET_DIR")
TARGET_GROUP=$(stat -c "%G" "$TARGET_DIR")

echo "chmod $TARGET_PERMS \"$TARGET_BASENAME\""
echo "chown $TARGET_OWNER:$TARGET_GROUP \"$TARGET_BASENAME\""
echo

# Find all subdirectories and process them
find "$TARGET_DIR" -type d -not -path "$TARGET_DIR" -print0 | while IFS= read -r -d $'\0' dir; do
    # Quote the directory path to handle spaces
    dir="$dir"
    # Get relative path from target directory
    rel_path="${dir#$TARGET_DIR/}"
    
    # Quote the path to handle spaces
    rel_path_quoted="$(printf '%q' "$rel_path")"
    
    # Get permissions in octal
    perms=$(stat -c "%a" "$dir")
    
    # Get owner and group
    owner=$(stat -c "%U" "$dir")
    group=$(stat -c "%G" "$dir")
    
    # Output commands with proper quoting for paths with spaces
    echo "# Creating directory: $TARGET_BASENAME/$rel_path"
    echo "mkdir -p $(printf '%q' "$TARGET_BASENAME/$rel_path")"
    echo "chmod $perms $(printf '%q' "$TARGET_BASENAME/$rel_path")"
    echo "chown $owner:$group $(printf '%q' "$TARGET_BASENAME/$rel_path")"
    echo
done

echo "echo \"Directory structure recreation complete!\""
echo "echo \"Created structure under: $TARGET_BASENAME/\""
</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2025/12/bash-script-to-replicate-a-directory-structure/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>bash htaccess file management script</title>
		<link>https://play.datalude.com/blog/2025/11/bash-htaccess-file-management-script/</link>
					<comments>https://play.datalude.com/blog/2025/11/bash-htaccess-file-management-script/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 06 Nov 2025 02:23:24 +0000</pubDate>
				<category><![CDATA[Bash Script]]></category>
		<category><![CDATA[General IT]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=780</guid>

					<description><![CDATA[OK, so its not too hard to run htpasswd manually, but if you spend a lot of time in your job doing it, it's nice to have a tool to do it more efficiently. This is a menu driven script, which will make a backup of your file, and suggest a random password, which you ... <a title="bash htaccess file management script" class="read-more" href="https://play.datalude.com/blog/2025/11/bash-htaccess-file-management-script/" aria-label="Read more about bash htaccess file management script">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">OK, so its not too hard to  run htpasswd manually, but if you spend a lot of time in your job doing it, it's nice to have a tool to do it more efficiently. This is a menu driven script, which will make a backup of your file, and suggest a random password, which you can choose to use or not. </p>



<p class="wp-block-paragraph">As always, don't trust everything you read on the internet, and test before you use in anger. </p>



<pre class="wp-block-code"><code>#!/bin/bash

# Configuration
HTACCESS_FILE_DEFAULT="/etc/nginx/htpasswd-developers

# Function to display a list of users
display_users() {
  echo "--- Existing Users ---"
  # Grep for lines that don't start with # and aren't empty
  # Then use cut to show only the username before the colon, and number the lines
  grep -vE '^(#|$)' "$HTACCESS_FILE" | cut -d':' -f1 | cat -n
  echo "----------------------"
}

# Function to perform a backup
backup_file() {
  if &#91; -f "$HTACCESS_FILE" ]; then
    cp "$HTACCESS_FILE" "$HTACCESS_FILE.bak"
    echo "Backup created at $HTACCESS_FILE.bak"
  else
    echo "No .htpasswd file to back up."
  fi
}

# Function to generate a random password
generate_password() {
    tr -cd '&#91;:alnum:]' &lt; /dev/urandom | head -c 12
}

# --- Main Script ---

# Select the .htpasswd file. Suggest the default value, but allow user to type another name
read -p "Enter .htpasswd file (default: $HTACCESS_FILE_DEFAULT): " HTACCESS_FILE
HTACCESS_FILE=${HTACCESS_FILE:-$HTACCESS_FILE_DEFAULT}

# Ensure the file exists, exit if not
if &#91; ! -f "$HTACCESS_FILE" ]; then
  echo "Password file doesn't exist"
  exit 1
fi

# Main menu loop
while true; do
  echo "Do you want to:"
  echo "a) Add a user"
  echo "r) Remove a user"
  echo "u) Update a user's password"
  echo "l) List users"
  echo "q) Quit"
  read -p "Enter your choice: " choice

  case "$choice" in
    a)
      read -p "Enter username to add: " username
      # Check if the username already exists
      if grep -q "^$username:" "$HTACCESS_FILE"; then
        echo "Error: User '$username' already exists. Use the 'u' option to update their password."
      else
        suggested_password=$(generate_password)
        read -p "Enter password for '$username' (or press Enter to use suggested: $suggested_password): " password
        password=${password:-$suggested_password}
        
        backup_file
        htpasswd -b "$HTACCESS_FILE" "$username" "$password"
        echo "User '$username' added."
      fi
      ;;
    r)
      display_users
      read -p "Enter reference number of user to remove: " ref
      # Use grep and sed to find the line number and get the username
      username_to_remove=$(grep -vE '^(#|$)' "$HTACCESS_FILE" | sed -n "${ref}p" | cut -d':' -f1)

      if &#91; -z "$username_to_remove" ]; then
        echo "Invalid reference number."
      else
        backup_file
        # Create a temp file without the user and then replace the original
        grep -v "^$username_to_remove:" "$HTACCESS_FILE" > "$HTACCESS_FILE.tmp" &amp;&amp; mv "$HTACCESS_FILE.tmp" "$HTACCESS_FILE"
        echo "User '$username_to_remove' removed."
      fi
      ;;
    u)
      display_users
      read -p "Enter reference number of user to update: " ref
      username_to_update=$(grep -vE '^(#|$)' "$HTACCESS_FILE" | sed -n "${ref}p" | cut -d':' -f1)

      if &#91; -z "$username_to_update" ]; then
        echo "Invalid reference number."
      else
        suggested_password=$(generate_password)
        read -p "Enter new password for '$username_to_update' (or press Enter to use suggested: $suggested_password): " password
        password=${password:-$suggested_password}

        backup_file
        htpasswd -b "$HTACCESS_FILE" "$username_to_update" "$password"
        echo "Password for user '$username_to_update' updated."
      fi
      ;;
    l)
      display_users
      ;;
    q)
      echo "Exiting."
      exit 0
      ;;
    *)
      echo "Invalid option. Please try again."
      ;;
  esac

  echo ""
done
</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2025/11/bash-htaccess-file-management-script/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Fixing up nginx file opening permissions</title>
		<link>https://play.datalude.com/blog/2025/10/fixing-up-nginx-file-opening-permissions/</link>
					<comments>https://play.datalude.com/blog/2025/10/fixing-up-nginx-file-opening-permissions/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 15 Oct 2025 08:16:16 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<category><![CDATA[nginx]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=776</guid>

					<description><![CDATA[Got this error message on startup of nginx. There are a lot of places you can change this value so it gets a bit confusing. It could be the user that nginx is running under, (usually www-data) or the process, or it could be set in systemd init file or in security/limits.conf &#8230; OK, so ... <a title="Fixing up nginx file opening permissions" class="read-more" href="https://play.datalude.com/blog/2025/10/fixing-up-nginx-file-opening-permissions/" aria-label="Read more about Fixing up nginx file opening permissions">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Got this error message on startup of nginx. </p>



<pre class="wp-block-code"><code>nginx: &#91;warn] 4096 worker_connections exceed open file resource limit: 1024</code></pre>



<p class="wp-block-paragraph">There are a lot of places you can change this value so it gets a bit confusing. It could be the user that nginx is running under, (usually www-data) or the process, or it could be set in systemd init file or in security/limits.conf &#8230; OK, so we'll run a script to gather the info</p>



<pre class="wp-block-code"><code>#!/bin/bash

# --- Configuration ---
NGINX_CONF="/etc/nginx/nginx.conf"
NGINX_SERVICE="nginx.service"
LIMITS_CONF="/etc/security/limits.conf"
SYSCTL_CONF="/etc/sysctl.conf"
# --- End Configuration ---

echo "#################################################################"
echo "# NGINX ULIMIT (MAX OPEN FILES) CHECKER"
echo "#################################################################"

# 1. Find the NGINX User
NGINX_USER=$(grep -E '^\s*user\s+' $NGINX_CONF | awk '{print $2}' | sed 's/;//' | head -n 1)
if &#91;&#91; -z "$NGINX_USER" ]]; then
    NGINX_USER="www-data" # Common default user if not explicitly set
fi
echo -e "\n&#91;1] NGINX RUNNING USER: ${NGINX_USER}"

# 2. Get NGINX Process Limits
echo -e "\n&#91;2] CURRENT NGINX WORKER PROCESS LIMITS (/proc/&lt;pid&gt;/limits)"
NGINX_PID=$(pgrep -u "$NGINX_USER" nginx | head -n 1)
if &#91;&#91; -n "$NGINX_PID" ]]; then
    cat "/proc/$NGINX_PID/limits" | grep "Max open files"
else
    echo "NGINX worker process is not currently running under user '$NGINX_USER'."
fi

# 3. Check NGINX Configuration Directives
echo -e "\n&#91;3] NGINX CONFIGURATION CHECK (${NGINX_CONF})"
NGINX_RBLIMIT=$(grep -E '^\s*worker_rlimit_nofile\s+' $NGINX_CONF | awk '{print $2}' | sed 's/;//' | head -n 1)
NGINX_CONNECTIONS=$(grep -E '^\s*worker_connections\s+' $NGINX_CONF | awk '{print $2}' | sed 's/;//' | head -n 1)

if &#91;&#91; -n "$NGINX_RBLIMIT" ]]; then
    echo -e "   - worker_rlimit_nofile: \t**$NGINX_RBLIMIT**"
else
    echo -e "   - worker_rlimit_nofile: \tNot set (NGINX inherits OS limit)"
fi

if &#91;&#91; -n "$NGINX_CONNECTIONS" ]]; then
    echo -e "   - worker_connections: \t**$NGINX_CONNECTIONS**"
else
    echo -e "   - worker_connections: \tNot set (Defaults to 512 or 1024)"
fi

# 4. Check systemd Service Unit Limit (Most modern Linux systems)
echo -e "\n&#91;4] SYSTEMD SERVICE UNIT LIMIT (${NGINX_SERVICE})"
SYSTEMD_LIMIT=$(systemctl show $NGINX_SERVICE --property LimitNOFILE | awk -F'=' '{print $2}')
if &#91;&#91; -n "$SYSTEMD_LIMIT" ]]; then
    echo -e "   - LimitNOFILE (systemd): \t**$SYSTEMD_LIMIT**"
else
    echo "   - LimitNOFILE (systemd): \tNot explicitly set (Inherits from system defaults/limits.conf)"
fi

# 5. Check User Limits (limits.conf)
echo -e "\n&#91;5] USER LIMITS CONFIGURATION (${LIMITS_CONF})"
USER_LIMITS=$(grep -E "^$NGINX_USER\s+(soft|hard)\s+nofile" $LIMITS_CONF)
ALL_USER_LIMITS=$(grep -E "^\*\s+(soft|hard)\s+nofile" $LIMITS_CONF)

if &#91;&#91; -n "$USER_LIMITS" ]]; then
    echo -e "   - Limits for $NGINX_USER:\n$USER_LIMITS"
elif &#91;&#91; -n "$ALL_USER_LIMITS" ]]; then
    echo -e "   - General limits (*):\n$ALL_USER_LIMITS"
else
    echo "   - No explicit nofile limits found for '$NGINX_USER' or '*'."
fi

# 6. Check System-Wide Kernel Limit
echo -e "\n&#91;6] SYSTEM-WIDE KERNEL LIMIT (fs.file-max)"
KERNEL_MAX=$(cat /proc/sys/fs/file-max)
echo -e "   - fs.file-max (Kernel): \t**$KERNEL_MAX**"

echo "#################################################################"</code></pre>



<p class="wp-block-paragraph">OK, so that gives us the output </p>



<pre class="wp-block-code"><code>#################################################################
# NGINX ULIMIT (MAX OPEN FILES) CHECKER
#################################################################

&#91;1] NGINX RUNNING USER: www-data

&#91;2] CURRENT NGINX WORKER PROCESS LIMITS (/proc/&lt;pid&gt;/limits)
Max open files            1024                 524288               files     

&#91;3] NGINX CONFIGURATION CHECK (/etc/nginx/nginx.conf)
   - worker_rlimit_nofile: 	Not set (NGINX inherits OS limit)
   - worker_connections: 	**4096**

&#91;4] SYSTEMD SERVICE UNIT LIMIT (nginx.service)
   - LimitNOFILE (systemd): 	**524288**

&#91;5] USER LIMITS CONFIGURATION (/etc/security/limits.conf)
   - Limits for www-data:
www-data         hard    nofile          65536
www-data         soft    nofile          65536

&#91;6] SYSTEM-WIDE KERNEL LIMIT (fs.file-max)
   - fs.file-max (Kernel): 	**9223372036854775807**
#################################################################</code></pre>



<p class="wp-block-paragraph">So we need to alter the low value for the nginx worker process, currently at 1024</p>



<p class="wp-block-paragraph">Insert this line near the top of /etc/nginx/nginx.conf file, before the events {} section. </p>



<pre class="wp-block-code"><code>worker_rlimit_nofile 65536; </code></pre>



<p class="wp-block-paragraph">And restart nginx. Now we see </p>



<pre class="wp-block-code"><code>&#91;2] CURRENT NGINX WORKER PROCESS LIMITS (/proc/&lt;pid>/limits)
Max open files            65536                65536                files     

&#91;3] NGINX CONFIGURATION CHECK (/etc/nginx/nginx.conf)
   - worker_rlimit_nofile: 	**65536**
   - worker_connections: 	**4096**
</code></pre>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2025/10/fixing-up-nginx-file-opening-permissions/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Copy tmux Scroll Buffer to a File</title>
		<link>https://play.datalude.com/blog/2025/10/copy-tmux-scroll-buffer-to-a-file/</link>
					<comments>https://play.datalude.com/blog/2025/10/copy-tmux-scroll-buffer-to-a-file/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Fri, 10 Oct 2025 03:31:12 +0000</pubDate>
				<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=774</guid>

					<description><![CDATA[tmux is super handy for long running commands. Especially if you have a dodgy connection which is likely to break: the command will keep running and you can re-attach to the session to save the day. But as a dyed-in-the-wool bash user, I've kinda got used to being able to scroll up and down my ... <a title="Copy tmux Scroll Buffer to a File" class="read-more" href="https://play.datalude.com/blog/2025/10/copy-tmux-scroll-buffer-to-a-file/" aria-label="Read more about Copy tmux Scroll Buffer to a File">Read more</a>]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">tmux is super handy for long running commands. Especially if you have a dodgy connection which is likely to break: the command will keep running and you can re-attach to the session to save the day.  </p>



<p class="wp-block-paragraph">But as a dyed-in-the-wool bash user, I've kinda got used to being able to scroll up and down my command history and copy items from there. But I always have to search the internet the exact commands I need in tmux. Here's an easy way to dump the whole tmux history buffer to a text file without complicated edit/scroll/copy start/copy end combinations. We'll assume your tmux prefix key is the default CTRL-B</p>



<pre class="wp-block-code"><code># default prefix key and colon. opens the command pane, at the bottom
CTRL-B  : 
# send whole history to tmux buffer
capture-pane -S -       
# get ready for another command, tmux
CTRL-B   : 
<code># self explanatory</code><code>save-buffer ~/tmux_output.txt       </code> </code></pre>



<p class="wp-block-paragraph">Now you can use your text editor to look at the command history, alerts, and outputs. I had to use this recently when I piped a long running script through tee -a but it failed to send any of the screen output to the specified text file. This was a lifesaver.</p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2025/10/copy-tmux-scroll-buffer-to-a-file/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>HEREDOC operators</title>
		<link>https://play.datalude.com/blog/2025/09/heredoc-operators/</link>
					<comments>https://play.datalude.com/blog/2025/09/heredoc-operators/#respond</comments>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 24 Sep 2025 06:41:25 +0000</pubDate>
				<category><![CDATA[Bash Script]]></category>
		<category><![CDATA[Linux]]></category>
		<guid isPermaLink="false">https://play.datalude.com/blog/?p=767</guid>

					<description><![CDATA[Basic usage Output alternatives: Can also use >> to append to output file, or &#124; tee to output to screen as it runs. Quoting preserves content If you're outputting a script you might need to preserve the variable notation instead of evaluating it. You can use either single or double quotes to do this. Zapping ... <a title="HEREDOC operators" class="read-more" href="https://play.datalude.com/blog/2025/09/heredoc-operators/" aria-label="Read more about HEREDOC operators">Read more</a>]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Basic usage</h2>



<pre class="wp-block-code"><code>VARIABLE="variable"

# command format
cat &lt;&lt; CONTENTS > /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
        These are Tabbed
        Indented
CONTENTS

# Result, cat /path/to/output.conf
Normal text here
The second line contains a variable
        These are Tabbed
        Indented</code></pre>



<p class="wp-block-paragraph"><strong>Output alternatives:</strong> Can also use >> to append to output file, or | tee to output to screen as it runs. </p>



<h2 class="wp-block-heading">Quoting preserves content</h2>



<p class="wp-block-paragraph">If you're outputting a script you might need to preserve the variable notation instead of evaluating it. You can use either single or double quotes to do this. </p>



<pre class="wp-block-code"><code>VARIABLE="variable"

# command format
cat &lt;&lt; 'CONTENTS' > /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
        These are Tabbed
        Indented
CONTENTS

# Result, cat /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
        These are Tabbed
        Indented
</code></pre>



<h2 class="wp-block-heading">Zapping Tabs</h2>



<p class="wp-block-paragraph">The &lt;&lt;- construct will remove tabs from your input, which means you can format your code nicely. Doesn't work at the same time as "CONTENTS"<br><br></p>



<pre class="wp-block-code"><code>VARIABLE="variable"

# command format
cat &lt;&lt;- CONTENTS > /path/to/output.conf
Normal text here 
The second line contains a $VARIABLE
	These are Tabbed
		Indented
CONTENTS

# Result, cat /path/to/output.conf
Normal text here 
The second line contains a variable
These are Tabbed
Indented
</code></pre>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
					<wfw:commentRss>https://play.datalude.com/blog/2025/09/heredoc-operators/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
