Post your handy utility scripts!

There is no package named emojione-picker on the AUR. There is emojione-picker-git which hasn’t been updated since 2017.

edit it to -git

see it’s working for me.

Thanks for pointing me on the -git. On the spot …

I was playing a little with bash outputs and I needed to rewrite some entries in the already printed output. There are some escape sequences that allows to navigate cursor in the terminal.

So the goal was to first output something like this

  start  |   stop   |  duration  | s | filename
17:51:39 |          |            |   | foo

After the script do the work it fills the blanks and changes it to this.

  start  |   stop   |  duration  | s | filename
17:51:39 | 17:52:39 |    60.00 s | 0 | foo

Here is part of the script that can handle the rewrite. Some terminals wrap the printed text to multiple lines so there is a way to count how many lines has to be deleted.
Only limitation is that the printed string has to start at the beginning of the line or it will accidentaly delete something it should not.

# this function will delete last echo output
clear_last() { # arg1==last printed string
    local text="${#1}"
    local line_length=$(tput cols)
    local up=$(( $text / $line_length + 1 ))    # last printed string should have \n at the end therefore +1

    echo -ne "\e[${up}A\r\e[J"
}

# print header
echo -e "\e[1m\e[4m  start  |   stop   |  duration  | s | filename\e[0m"

#while-do loop start
    # conversion time measurement
    TIMESTAMP_START=$(date +%H:%M:%S)
    TIME_START=$(date +%s%N)

    # first print
    output="${TIMESTAMP_START} |          |            |   | ${filename}"
    printf "${output}\n"

    ###
    ### here is a long running part of the script
    ###

    # process a return value of the long running part of the script
    if [ $? -ne 0 ]; then
        status=1
    else
        status=0
    fi
    # conversion time measurement
	TIMESTAMP_STOP=$(date +%H:%M:%S)
	TIME_STOP=$(date +%s%N)

    # rewrite original output with "end" times
    clear_last "${output}"
    printf "${TIMESTAMP_START} | ${TIMESTAMP_STOP} | %8.2f s | ${status} | ${filename}\n" \
                "$(echo "(${TIME_STOP}-${TIME_START})/1000000000" | bc -l | sed -e "s/,/\./g")"

#end of while loop
1 Like

Imagine using YouTube to watch YouTube videos in the current year!

I use this script to watch videos:

#!/bin/sh
# ytp - a simple script that downloads and plays a video!
# No buffering, no telemetry, no ads, and you get to keep the video locally

# Modify these variables as needed:
# Directory for downloaded videos:
DIR="$HOME/Videos/temp"
# Video player:
PLAYER="xdg-open"
#PLAYER="/usr/bin/smplayer"

# Downloader and options:
YTDL="/usr/bin/yt-dlp"
YTDLOPTS="--no-playlist"
YTDIROPTS="-P \"$DIR\""

set -e

# Get URL from clipboard if run without argument:
if [ -z "$1" ]; then
  URL="$(xclip -o -sel c)"
else
  URL="$1"
fi

# Get video filename
printf "[URL]: %s\n" "$URL"
FILENAME=$("$YTDL" "--get-filename" "$YTDIROPTS" "$URL")
printf "[FILE]: %s\n" "$FILENAME"

# Download video
printf "[CMD]: \"%s\" \"%s\" \"%s\" \"%s\"\n" "$YTDL" "$YTDLOPTS" "$YTDIROPTS" "$URL"
"$YTDL" "$YTDLOPTS" "$YTDIROPTS" "$URL"

# Play video
printf "[CMD]: \"%s\" \"%s\" >/dev/null 2>&1\n" "$PLAYER" "$FILENAME"
"$PLAYER" "$FILENAME" >/dev/null 2>&1

There are two ways to use it, either with a video URL, like this:

ytp https://www.youtube.com/watch\?v\=vyR2NWYn6hE

in which case, if you use Zsh, check out my post on bracketed paste magic.

Alternatively, if you have the URL already in the clipboard, it’s sufficient to just write:

ytp

and the script will use the URL from your clipboard. There is no error checking, however, so be careful what you have in your clipboard.

Of course, this is only usable if you have a very fast connection, or a very slow one, because it doesn’t stream the video, but downloads it in its entirety before playing it. For me, this is preferable in 99% of times, unless the video is really large, in which case it takes ages to download it. If you want to stream the video, any media player worth its salt will open a video URL.

Also, remember to clean your downloaded videos directory from time to time, unless you have plenty of storage space.

2 Likes

And you don’t delete the video file after watching? :rofl:

2 Likes

No, I often want to keep it. I delete the entire directory once in a while, after I copy what I want to preserve locally.

Simple script to install packages on a new system. Useful when you, like me, often forget package names.

#!/usr/bin/env bash
#-------------------------------------------------------------------------
# ARCH PACKAGE INSTALLATION
#-------------------------------------------------------------------------

echo
echo "INSTALLING SOFTWARE"
echo

PKGS=(

    'packagename1'
    'packagename2'
    'packagename3'

)

for PKG in "${PKGS[@]}"; do
    echo "INSTALLING: ${PKG}"
    paru -S "$PKG" --noconfirm --needed
done

echo
echo "DONE INSTALLING SOFTWARE"
echo

Replace paru with yay if that’s your preference.

Another small, but useful script which I use frequently is this little bit which launches ncmpcpp with one click (and labels it ‘music’) rather than having to open a terminal and then start it.

 st -c music -e ncmpcpp

If you’re using Alacritty or Kitty the command is

terminalname --class music -e ncmpcpp

Last but not least, I’d like to recommend this collection from Manas140, which has a calculator, extraction tool, a colourpicker and a handful of other useful utility scripts which I use almost daily.

1 Like

Why do you install the packages one by one?
Why not run in as paru -S "${PKGS}"?

1 Like

Mostly because I’m not a programmer, and therefore not particularly good at writing scripts. Prior to writing this I used to keep a list of programs and copy paste it, e.g. yay -S pkg1 pkg2 pkg3 pkg4, but far too often one pkg would fail to build causing the entire process to stop, forcing me to rewrite it and cut whatever didn’t build and do it again. Therefore, when writing this I wanted to do them one by one. Having said that, I have not had a pkg fail to build with this yet so I’m not entirely sure it even solves the problem I was having. For now, it does what I wanted it to, and doesn’t take long to do so.

If you want to improve upon it, you are of course free to do so.

Batteries don’t last for ever - and we all know there is a backside to run your laptop always on.

But when you plug the charger you forget it - then you charge to 100% and that is not ideal - with this script you get notifications when it is time to unplug.

From another place I got a link to a script - which I then refactored to fit my temper and the result was below script.

#! /bin/bash
#
# Script to notify when battery is outside levels - time to plug charger.
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.#
#
# Source: https://linoxide.com/remind-unplug-charging-laptop-arch-linux
#
# https://root.nix.dk
#
# 2021-11-27
# 2021-11-28 revised - checks not updating
#                    - fix variable check on all levels
#

set -eu

# dependency check
if ! [[ "$(which notify-send)" =~ (notify-send) ]]; then
	echo "Please install libnotify to use this script.\n"
	echo "   sudo pacman -S libnotify"
	exit 1
fi
if ! [[ "$(which acpi)" =~ (acpi) ]]; then
	echo "Please install acpi to use this script.\n"
	echo "   sudo pacman -S acpi"
	exit 1
fi

# check interval (seconds)
INTERVAL=60

# example battery levels
# these leves are not based on scientific evidence
# you are required to adjust as appropriate for your device
MIN_BAT=10     # low water mark
MAX_BAT=60     # high water mark

get_plugged_state(){
	echo $(cat /sys/bus/acpi/drivers/battery/*/power_supply/BAT?/status)
}

get_bat_percent(){
    echo $(acpi|grep -Po "[0-9]+(?=%)")
}

# primary loop
while true ; do

	if [ $(get_bat_percent) -le ${MIN_BAT} ]; then # Battery under low limit
 		if [[ $(get_plugged_state) = "Discharging" ]]; then # plugged
 		    notify-send "Battery below ${MIN_BAT}. Time to plug adapter"
 		fi
    fi
	if [ $(get_bat_percent) -ge ${MAX_BAT} ]; then # Battery over high limit
 		if [[ $(get_plugged_state) = "Charging" ]]; then # plugged
 			notify-send "Battery above ${MAX_BAT}. Time to unplug adapter"
 		fi
	fi
	sleep ${INTERVAL} # Repeat every $INTERVAL seconds
done

4 Likes

Now, if only I could make it run on my phone. The laptop I have is pretty well dead when not plugged, because I didn’t have this script! (at least partially - it’s really a old Toshiba that My sister ran Win 7 on, before I dual booted Arch on it! - because it’s non-UEFI machine and I wanted to try the Arch way without UEFI))

I would think you could make it work on a pinephone :slight_smile:

Quite probable - but I have a Samsung A32. I just would like for it work for longer than the previous ones I have had…which have lived a life of occasional total discharge, and too frequent charge to 100% (thus shortening their battery life). I could get by quite happily with my S3 - or my A5(2017) - if they would still charge up and hold it satisfactorily! Not much smart needed in my phone - once or twice a year needing to navigate with it, 4 times a year looking something up on the net, and frequent use of Cool Reader is about it beyond taking or making a call!

It can’t just be because I’m old, can it? :grin:

I have seen AccuBattery recommendations but I haven’t really used it that much to give an “objective” :wink: review. Might be worth some research.

If research consists of reading about it… :grin: It actually looks well worth trying it out - and thanks! Pretty much what I wanted by the description… although I wish it could actually stop the charging at the specified percentage, rather than just warn about it. Got to try it to see how it goes though…

1 Like

This would be great. I just installed AccuBattery on my Samsung S8, we’ll see how it goes. I normally leave it plugged in overnight, so I’m worried about the alarms then. I’m not sure waking up in the middle of the night every night to unplug my phone for better battery life is a good trade off. Time will tell.

Edit: There is a do not disturb setting in the app, so you can set it to not alarm in a specific time range. I slept well last night :slight_smile:

1 Like

If your phone supports it, certain custom ROMs come with the feature of stopping the charging at a specified percentage. I have CrDroid on my Oneplus 8t and it works flawlessly.

1 Like

EndeavourOS, in common with other Arch-based distros, nearly always has updates awaiting - which means a notifier isn’t as useful as it might be for some. For others, they don’t like the ‘attention-getting’ that a notifier specializes in. Sometimes you want to know more about the pending updates, though, and you usually want to know NOW!.

I had these scripts (actually implemented at the moment as bash functions) for a while, but they have been upgraded a bit lately (with some expert help).

Basically, on demand (that means when you call their name from a terminal :grin:) you will get either a full count on what’s waiting (repos and AUR) with upcnt - or you get a formatted list of all awaiting updates, both repo and AUR. You also get a bonus with upls - it will tell you if theses updates are likely to require a reboot! This can be useful in deciding whether to update NOW, or at the end of your session…

Here they are:

upcnt
# Function to count available updates

upcnt() {
# create vars
NEWPKG=0
NEWAUR=0

# count AUR and pacman updates
NEWAUR=`yay -Qua | wc -l`
NEWPKG=`checkupdates | wc -l`

# output RESULT
if [[ ${NEWPKG} == 0 && ${NEWAUR} == 0 ]]; then
	RESULT="System up-to-date"
else
	RESULT=$NEWPKG" Repo pkgs + "$NEWAUR" AUR pkgs need updating"
fi
echo $RESULT
}
upls
# Function to display listing of available updates
# will also let you know if a reboot is likely to be needed

upls() {
    local updatesAUR=$(yay -Qua)
    local updates=$(checkupdates)

    # output RESULT
    if [ -n "$updates" ] || [ -n "$updatesAUR" ]; then
		echo "Repo packages"
		echo "-------------"
		{
		     echo "$updates"
		} | column -t -N Name,Current,"->",New
        echo " "
        if [ -n "$updatesAUR" ]; then
            echo " "
            echo "AUR Packages"
            echo "------------"
            {
                echo "$updatesAUR"
            } | column -t -N Name,Current,"->",New
        fi

 	#check for core system packages
	RUN_KERNEL=$(cat /proc/version | sed 's|.*(\([^@]*\)@archlinux).*|\1|')
	CHKLINE="amd-ucode\|intel-ucode\|btrfs-progs\|cryptsetup\|nvidia*\|mesa\|systemd*\|*wayland*\|xf86-video-*\|xorg-server*\|xorg-fonts*"
	CHKLINE+="\|""${RUN_KERNEL}"

	echo " "
	echo $updates | grep -q ${CHKLINE} && echo "Reboot will be recommended due to the upgrade of core system package(s)." || echo "No reboot recommended after this update."
    else
        echo "No pending updates..."
    fi
}

As with any bash function, just paste it into your ~/.bashrc file - or into any such file that .bashrc calls (perhaps .bashrc-personal or .bash-functions?). Or, you could very easily turn them into scripts if you prefer. Enjoy!

4 Likes