Update Reminders in Arch Linux Terminal

Disclaimer: Proceed with caution, I’m fairly new to Arch & Linux, so please do due diligence and research around any commands you enter on your system.

I was trying to conceive of a method of updating regularly and safely in Arch Linux.

You shouldn’t automatically apply updates, Arch is designed for human intervention. With automatically applying updates there’s the chance that you’ll log in one day to a broken system. I haven’t settled on my backup strategy yet so that adds extra risk.

There are still some things you can do to speed up and prepare/notify yourself around updates, I will call this my Update Prep System. Apologies for the bad formatting, still getting a hang of blogging and styling WordPress. Additional apologies for the rough scripting, if there is interest I’ll extract this source into a public git repo.

Update Prep System

update-prep-notification

Pre-requisites

  • Arch install (although may work on other distros)
  • cronie
#!/usr/bin/env bash

sudo pacman -Syy cronie
sudo systemctl enable --now cronie.service

Steps

The system consists of these steps:

  1. Install the cron job
  2. Regular download of new packages (pacman) without install
  3. Upgrade user .bashrc
  4. Each time terminal opens, if new packages are ready, echo before the prompt.

Script for downloading updated packages

Save the following script somewhere as `download-packages` for the cron job to access it.

#!/usr/bin/env bash
#
# Usages
#     Please run to check: root@root# crontab -l
#
# Usage
#     [-h|--help]    - show help

logdir="/var/log"
logpath="$logdir/download-packages.log"
if [ ! -f $logpath ]; then
    mkdir -p "${logdir}"
    touch "${logpath}"
fi

function printlog () {
    local DATE=`date '+%Y-%m-%d %H:%M:%S'`
    echo "${DATE}: $1" | tee -a $logpath
}

# root check
user="$(whoami)"
if [ "$user" != "root" ]; then
    printlog "This script must be run as root user."
    exit 1;
fi

if [ -z "${1+xxx}" ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    echo "Usage"
    echo "    NOTE: This script must be run as root."
    echo "    --download                 downloads new packages"
fi

if [ "$1" == "--download" ]; then
    printlog "Downloading new packages..."

    # TODO: print to log file...
    pacman -Syuw --noconfirm
    printlog "New package check complete."
    exit 0;
fi

exit 1; # should be impossible to reach here.

cron job

Run this script `add-root-cronjob_download-packages.sh –install-cron` to instruct your system to regularly download new packages:

#!/usr/bin/env bash
#
# Usage
#     [-h|--help]    - show help
#
# Dependencies
#     - cronie (Arch)

cron="1 * * * *" # each hour
#cron="* * * * *" # test every minute
logdir="/tmp"
logpath="$logdir/.download-packages.log"
if [ ! -f $logpath ]; then
    mkdir -p "${logdir}"
    touch "${logpath}"
fi

function printlog () {
    local DATE=`date '+%Y-%m-%d %H:%M:%S'`
    echo "${DATE}: $1" | tee -a $logpath
}


# root check, script must be run as user first.
user="$(whoami)"
if [ "$user" != "root" ]; then
    printlog "This script must be run as root user."
    exit 1;
fi
printlog "root user detected."


# show help if no args are passed, or if help flag gets passed
if [ -z "${1+xxx}" ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    echo "Usage"
    echo "--install-cron             creates cronjob to run this script hourly"
fi


# run as user.
if [ "$1" == "--install-cron" ]; then
    printlog "Attempting to install cron job"
    #####################
    # check if cronie has been installed
    pacman -Qi cronie >/dev/null 2>&1
    if [ $? -eq 0 ]
    then
        printlog "Cronie already installed, continuing."
    else
        printlog "installing cronie."
        sudo pacman -Syy cronie
        sudo systemctl enable --now cronie.service
    fi
    
    # rewrite crontab into temp file
    cwd=$(pwd)
    tempdir="/tmp/croninstall"
    mkdir -p $tempdir
    cd $tempdir
    job="crontab.tmp"
    # copy current crontab to temporary file $job
    crontab -l > $job
    dlscript="/path/to/download-packages"
    printlog "creating temporary crontab for editing: '${tempdir}/$job'"
    cronjob="${cron} /usr/bin/env bash ${dlscript} --download"
    echo "${cronjob}" >> $job
    printlog "installing cron job from '${tempdir}/$job' to ${user}'s crontab:"
    printlog "${cronjob}"
    crontab $job
    printlog "cleaning up temporary cron job install files"
    rm -rf $tempdir
    cd "${cwd}"
    printlog "contents of $user crontab: (to edit, run \$ crontab -e)"
    crontab -l | tee -a $logpath

    printlog "install mode of this script finished. Exit."
    exit 0;
fi

Upgrade .bashrc

Use the following script `add-bashrc-check.sh` to upgrade your .bashrc to check if updates are ready to install.


#!/usr/bin/env bash

user="$(whoami)"
group="$(groups $user)"
if [ "$user" == "root" ] || [ "$group" == "root" ]; then
    echo "This install script must be run for/as a non-root user."
    exit 1;
fi

cat  ~/.bashrc

# check if there are package updates and notify user.
# installed with archlinux/install/mine/download-packages-install/add-bashrc-check.sh
bash is-offline-updates-ready
if [ \$? -eq 0 ]; then
    echo "Updates required. Run 'upgrade-packages' to install."
fi
EOT
exit 0;

Open Terminal: Are Updates Ready?

Place this script `is-offline-updates-ready.sh` on your user `$PATH`. This checks for pending updates each time a terminal is open and stays silent if there aren’t any.

#!/usr/bin/env bash

# How to use this script
#     bash is-offline-updates-ready
#     if [ $? -eq 0 ]
#     then
#         echo "Updates required."
#     fi


if [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    echo "Usage:"
    echo "    NOTE: This script must be run as root."
    echo "    returns 0 if packages are ready to install"
    echo "    returns 1 if no new packages are downloaded"
fi


# grep for lines containing an arrow (i.e. contain the format 1.0.0.0 -> 2.0.0.0)
toUpdate=$(pacman -Qu | grep "\->" | wc -l)
if [ $toUpdate -gt 0 ]; then
    echo "There are $toUpdate packages to update."
    exit 0;
fi

exit 1;

upgrade-packages

A small script that upgrades all pacman and aur packages. You could use your own implementation as mine is a bit primitive right now.

#!/usr/bin/env bash

# https://wiki.archlinux.org/index.php/Pacman#Upgrading_packages
# https://wiki.archlinux.org/index.php/System_maintenance#Upgrading_the_system


# Upgrade AUR (yay) via running git install script again.
# ------------------------------------------------------------------------------
#       https://github.com/Jguer/yay/issues/1087#issuecomment-545585765
# TODO: only remove and reinstall if newer yay package exists.
sudo pacman -R yay
# TODO: put the following in a yay install script for D.R.Y.
cwd=$(pwd)
cd /tmp
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg -si
cd ..
rm -rf yay
cd "$cwd"
# ------------------------------------------------------------------------------

echo "upgrading packages => pacman -Syu"
sudo pacman -Syu

echo "upgrading packages => yay -Syu --devel --timeupdate"
yay -Syu --devel --timeupdate

finally {}

Let me know if you’d like me to extract this to a public git repo, at the moment it’s highly coupled to my personal scripts repo and filesystem structure.

Effective Life Changes: Self-Contracts

This blog post was inspired by a Ted talk I just watched from Mark Adams. He mentions a system called Lock-in. A brief scouring of the internet didn’t get anywhere for me, but I did manage to extract some value from his talk.

Let’s call this system Self-Contracts. It’s a work in progress, and I’ll keep this post as it’s home for now.

Structure

You will need the following. Create a cloud text document or your favourite record system and start writing the following:

Constraint

You’re trying to make an improvement in your life, so most likely you’re trying to give yourself an Enabling Constraint.

Penalty

You’ve got to make ‘doing the thing’ the lesser evil – the penalty for not doing it needs to be a lot worse.

Risk

What you have to risk if you fail.

Reward

What you stand to gain should you succeed.

Stakeholders

These are people involved that have a vested interest in you succeeding. They may cast shame upon you (depending on how you structure your contract) if you breach your contract.

Exit Criteria

What would be required to make this self-contract obsolete and never reoccur?

Time

A set period of time for your self-contract to be in effect

Conditions

The self-contract is indefinite or unbounded by time. There may still be conditions to exit a self-contract not based on time.

Example

Self-Contract: Alcohol Constraint

Constraint: No drinking alcohol when above 95KGs in body weight.
Penalty: Social Shame
Risk: Pride, seen to have no control.
Reward: Health, Productivity, Control.
Stakeholders: Flatmates
Exit Criteria: Discovering a life-threatening disease, where drinking alcohol is the least of my worries.

Conclusion

This is a work in progress. Any suggestions to refine, constructive criticism is welcomed. Feel free to leave a comment.

The Toolbox Fallacy

I recently watched a video describing something called The Toolbox Fallacy. It’s about a cognitive fallacy that fights personal achievement, and knowing a bit about it reveals how we waste opportunities.

Watch the youtube video by Passion of the Nerd.

For this post I’ll transcribe, paraphrase, and write a bit about my interpretation. I set out to write this post intending to have a convincing message, but as it turns out, I’m figuring it out as I go along. Including how to write a blog post. I’m not an expert, take my conjecture with a grain of salt.

The premise

I can’t do (x-goal) until I have (y-thing)

The fallacy

  • You’ve likely substituted thinking for buying
  • You haven’t disproven alternative paths towards your goal
  • You shift your attention from the goal towards the tool
  • You’ve settled early on a tool (solution) for the job, rather than a process. You’re likely to adapt your resulting process to fit the tool, due to the sunk cost fallacy.

I think it’s important to have a trigger to remind you that you’re ‘entering the fallacy’.

If you catch yourself saying:

“If I just do/buy/get this first, it will let me….”

it might pay dividends to reassess your motivations.

From experience, and also paraphrased from the video, usually, once you have the tool you’re coveting, things still don’t change. A few examples from my own experience:

  • Purchased a second PC to use as a “server”.
    • I thought it would motivate me to study Linux, and I would use it for a host of purposes. I didn’t have much of a goal.
    • I could have technically used my existing desktop PC, perhaps with a bit more storage.
  • I buy electronics like crazy from eBay and Aliexpress.
    • Each time I think I’ll learn from playing around with the modules and equipment I buy.
    • Electronics seem to accumulate about 10 times faster than I use them.
  • I have accumulated over 600 games on Steam and recently canceled my monthly subscription to humblebundle. I was a big sucker for sales.
    • I thought if I kept buying games, I wouldn’t be bored and I’d be relevant in the gaming community (my ego identifies as a gamer).
    • I could have watched other streamers/lets plays, done research, made my mind up about the game quality, then committed to a full-price game and actually enjoyed it. Possibly even stream it.

Image result for steam sale spongebob conch

Pictured: The monkey with tiny cymbal inside my head.

Motivations

The driving force behind indulging in the toolbox fallacy is the fear of failure. It’s a form of procrastination. Fearing something motivates you to avoid it. You tell yourself that your chances of success will be greater with this tool. It’s not rational or fully conscious, but emotional. You wait to acquire a tool before acting because the tool fits with your preconceived self-identity.

Ego

You have an image or “identity of self” known as your ego. Your image of yourself, having achieved (x-goal), pairs nicely with commanding a tool (y-thing). Therefore, through a lack of rational thinking, having a tool is vital to achieving success.

In your mind’s eye, you “ought to have” useful tools once you’ve achieved your goal. It satisfies your self-image. What’s harder to visualise, however, is how you will truthfully arrive at success. There are many variables and paths.

Fear of Failure

When you buy “a key piece of the puzzle” in order to do the thing, you’re telling yourself you won’t be able to achieve success, in some shape or form, without the tools. You fear that without (y-thing) you’re doomed with (x-goal).

You’re not a failure if you’re not tackling the glorious, lofty goals with proportionally impressive tooling. Buying, or planning to buy a tool without the prerequisite critical thinking is a distraction. Break up your goals, run experiments, prototype. These are mental tools you can first acquire that allow you to see small incremental progress. You make more progress in small mindful increments than wasting time mindlessly improvising your way towards a goal – gathering tools before justifying them.

We greatly underestimate the effort involved to achieve our vision. We don’t know what we don’t know yet. We shouldn’t fear and try to avoid failure – it can be beneficial to seek it fast and often. It’s a powerful feedback loop.

Opportunity Cost

You’ve already chosen your weapon, so you’re marching off to slay the beast. This assumes a few things:

  • You’ve chosen the right goal
  • You’ve chosen the right tool
  • You’re going to succeed

Opportunity cost is the loss you incur by removing alternative choices and not enjoying the benefit associated with the best alternative choice. By settling on a tool first, you’ve already sunk your investment.

If you’re like me and work a job with high demands on your time, then you might opt to buy the “Ferrari” of that category of the tool. You trade off money for thinking. You don’t provide yourself the option of spending time, researching the right solution to your goals. You don’t appreciate an expensive tool to the fullest extent because you don’t have the time. You might even damage that expensive tool through incorrect use, because you’re tempted to shortcut learning. You experiment rather than spend time to study.

Remedies

Recording

Journal your way towards a goal from the outset. Your memory is terrible at best. Create a single starting point to identify the location of future records. Recording your thought process will set it in stone. Writing helps you clarify thoughts. You may think you’re clear until you try to define it in explicit detail. That’s exactly what happened while writing this blog post!

Reasoning

From software development:

Visualisation

Visualisation is powerful. Make yourself a project mindmap to record your decision-making process. I recently purchased mindmeister although they have a free version.

To validate your need for a tool, you ought to be able to have a conversation with someone (who is objective and constructively critical) while feeling conviction as you justify your need for the tool.

Prototype

Before buying, consider a prototype that would prove the tool’s usefulness. Lower your expectations greatly. Study and read up around the tool, is there a way you can get what you really want, deep down, without or perhaps with a cheaper or alternative version of the tool?

Recursive Questioning

Ask yourself at least five whys. Drill deep and see if the thing you want to buy connects back up to your values.

Goal Genocide

Celebrate killing your goals and ideas.

Conclusion

I think gratitude plays a large role in this fallacy. With less want for more, we might be predisposed to working with what we have, and perhaps valuing the process that takes us towards our goals, which will inevitably change.

No doubt this blog post will need some refinement. I welcome constructive feedback. I came in guns blazing and burned a lot of time refining it, with a loose definition of success. But you know what they say, real artists ship! I will endeavor to address the rationale being why I’m blogging in a future post.

Create a free website or blog at WordPress.com.

Up ↑