Post your handy utility scripts!

Have something you use every day that you think might be useful to others? Post it here.

Here’s one of mine:

#!/bin/bash

# The output is similar to what you'd see by simply running pacman -Ss "search term"
# but each package name is prepended with a number. If you wish to install any of the
# packages after making a search, you simply enter in the number of the package, otherwise
# q to quit. Once you select which package to install, pacman -S is run and will ask for your
# password and confirm if you really wish to install the package.

search_term="$1"

if [[ -z "$search_term" ]]; then 
	echo "please enter a search term"
	exit
fi

pacman -Ss "$search_term" | awk 'NR % 2 { printf "%s) %s\n", i += 1, $0 } !(NR % 2) { print $0; }'

read -p "which package do you wish to install (q to cancel): " usrans

if [[ "$usrans" == "q" ]]; then exit; fi
		
sudo pacman -S $(pacman -Ssq "$search_term" | sed -n "$usrans"p)

I often perform a search then an install, this simplifies that process :grinning:

example output:

someone@somewhere~]$ ./pacwrapper.sh icons
1) extra/adwaita-icon-theme 3.36.1-1 [installed]
    GNOME standard icons
2) extra/akonadiconsole 20.08.0-1 (kde-applications kdepim)
    Akonadi management and debugging console
3) extra/breeze-icons 5.73.0-1 (kf5)
    Breeze icon themes
4) extra/gnome-icon-theme-symbolic 3.12.0-6 [installed]
    GNOME icon theme, symbolic icons
5) extra/icon-naming-utils 0.8.90-5
which package do you wish to install (q to cancel): 
10 Likes

Shorter:

[[ "$usrans" == "q" ]] && exit

Also,

yay ? :stuck_out_tongue_winking_eye:

5 Likes

I like verbosity so it’s a bit clearer what’s going on; especially when someone isn’t familiar with the syntax, but thanks for the tip :slight_smile:

I’m old and stuck in my ways :joy:

EDIT: for those curious, yay search_term will basically do what my script does. Pretty nifty.

6 Likes

I have a little script that offloads RCUo tasks defined by boot parameter rcu_nocbs=cpulist to specific CPUs, in order to reduce latency on the other CPUs.
But no one is interested in this nerdy useless stuff :innocent:

1 Like

Here is a utility script I made (which I find quite useful in my daily workflow):

7 Likes

Here’s an extremely complicated way of generating random passwords (no clue whether they are cryptographically secure, but…you can also use pwgen):

#!/bin/bash

[[ -z $1 ]] && echo "Missing argument: length of password (max. 16)" && exit 1

for ((i=1 ; i<=3 ; i++)) ; do
    _offset=$(( $i + $RANDOM % 3 ))
    _hash=$(openssl rand -hex 8)
	dd if=/dev/urandom count=32 bs=1 status=none | argon2 $_hash -i -e -k 65536 -t 5 | awk -F , '{print $3}' | awk -F $ '{print $2}' | cut -c$_offset-$(( $_offset + $1 - 1 ))
done

exit 0

Example output:

$ random.sh 10
jZkOTkxMTI
Q2ZDIyZjE0
NDIxZGI2M2
2 Likes

To have more search terms to find precisely (but doesn’t install):

#!/bin/bash
cmd=(pacman -S)        # replace pacman with yay to include AUR results
for arg in "$@" ; do
  cmd+=(-s "$arg")
done
"${cmd[@]}"

A call could be for example:

./scriptname python editor
2 Likes

Not exactly handy, and some people here already know about it, but here’s my benchmarker script: https://github.com/torvic9/bash-scripts/tree/master/mini-benchmarker

(Note: it’s not meant to provide accurate and detailed figures, but useful enough to have a quick performance overview. Run it in multi-user runlevel. Don’t use it for serious benchmarking, there are many other tools for that.)

5 Likes
fh() {
    print -z $( ([ -n "$ZSH_NAME" ] && fc -l 1 || history) | fzf -e +s --tac | sed 's/ *[0-9]* *//' | sed 's/ *[*]* *//')
}

Search history and execute, alias for zsh, so probably doesn’t count :smiley:

3 Likes

Nice! :smiley:

Does bash alias count as well?

# currect directory size checking
alias da='du -h -d1 | sort -k2'    # sort by alphabet
alias ds='du -h -d1 | sort -h'     # sort by size

Or a conversion subtitles/text files from “common” format into UTF-8 (to fix diacritic for my movie player). It mostly works. :wink:

#!/bin/bash

orig_format="Windows-1250"

dir="."
tmp="utf8"

find $dir -type f | sort -V | while read file; do

if [[ "$file" == *'.srt' ]] || [[ "$file" == *'.txt' ]] || [[ "$file" == *'.sub' ]]; then

echo "${file}"

#Convert windows ansii file into temporary UTF-8 text file
iconv -f "${orig_format}" "${file}" -t UTF-8 > "${file}.${tmp}"

#Remove original file
rm "${file}"

#Rename temp file to original file to take its place
mv "${file}.${tmp}" "${file}"

fi
done

Some time ago I made this wrapper for checking if my password was leaked and is now on haveibeenpwned.com.

#!/bin/bash

# this script compares sha1sum of entered password with a database on haveibeenpwned.com website
# if there is a match it is a good chance that this password is already in some dictionary decryptor

echo -n "Password to check:"
read -s password
echo -e "\n"

hash=$(echo -n "$password" | sha1sum | awk '{print $1}' | tr '[:lower:]' '[:upper:]')
prefix=$(echo -n "$hash" | cut -c -5)

echo -e "sha1sum:\n$hash\n"

retval=$(curl "https://api.pwnedpasswords.com/range/$prefix" 2> /dev/null)

for line in $(echo "$retval"); do

    line_hash=$(echo -n "$prefix$line" | cut -d ":" -f 1)
    if [ "$line_hash" == "$hash" ]; then
        occur=$(echo -n $line | cut -d : -f 2 | tr -dc '[[:print:]]')
        echo -e "\"$password\" is in the list $occur times"
        exit 0      
    fi

done
echo "\"$password\" not listed"
4 Likes

I have a simpler one

#!/bin/bash
echo “Type string length :”
read LN
< /dev/urandom tr -dc A-Za-z0-9 | head -c$LN | xsel -ib

Note: You can add special characters with it which I hide for security reasons :wink: :rofl:

Also one to show QR code of clipboard content ( only because I don’t use clipman )

#!/bin/bash
xsel -ob | qrencode -o /tmp/QR0001.png && viewnior /tmp/QR0001.png && rm /tmp/QR0001.png

Edit : qiv is faster than viewnior

1 Like

I use KeepassXC for that

USB partition script

#!/usr/bin/env bash
# format USB device to exfat

# ensure a device is given
if [[ -z "$1" ]]; then
    echo "No device specified ..."
    echo "Usage: format-usb.sh /dev/sdy"
    exit
fi

# get the last part of device path
device="$(echo $1 | cut -d'/' -f2)"

# create list of available devices
devices="$(lsblk -o NAME | egrep '^sd')"

# check if device is valid - abort if not
if ! [[ $devices =~ (^|[[:space:]])$device($|[[:space:]]) ]]; then
    echo "$1 not found"
    echo "Aborting"
    exit 1
fi

# check if device is removable - abort if not
[[ $(echo $(lsblk -no RM "$1" | head -n 1)) = '0' ]] && \
    echo "Non removable device detected!" && \
    echo "Aborting" && \
    exit 1

# Ask for confirmation
read -r -p "Confirm reformat of '$1' [y/N] " resp
if [[ "$resp" =~ ^([yY][eE][sS]|[yY])$ ]]; then

    # Repeat confirmation question
    read -r -p "Irrevocably format  '$1' [y/N] " resp2
    if [[ "$resp2" =~ ^([yY][eE][sS]|[yY])$ ]]; then

        # will do
        echo "Formatting $1 ..."

        # use gdisk to create new partition table
        # and a single Microsoft basic data partition type
        printf 'o\ny\nn\n\n\n\n0700\nw\ny\n' | \
            sudo gdisk "$1" && \
            sudo mkexfatfs "$1"1

        # done
        echo "Done"
        exit
    fi
    echo "Formatting aborted"
else
    echo "Formatting aborted"
fi
curl -s https://get.geojs.io/v1/ip

curl -s https://get.geojs.io/v1/ip/country.json

curl -s https://get.geojs.io/v1/ip/geo.json
#!/bin/bash
# get public IP
IP=$(curl -s https://get.geojs.io/v1/ip)
echo ${IP}
# various methods of displaying the IP
#notify-send --urgency=normal --expire-time=5000 "Public IP " "\nYour public IP address is $IP\n"
#yad --title="Public IP" --text="Your public IP is '"$IP"'" --button=OK --center --width=300 --height=100
#zenity --info --text "Your public IP is '"$IP"'" --no-wrap

Show your country code and your public IP:

curl -s https://ipinfo.io/country
curl -s https://ipinfo.io/ip

Edir: also:

curl -s https://ipinfo.io/ip https://ipinfo.io/country
5 Likes

Useful :smiling_face_with_three_hearts:

2 Likes
#!/bin/bash
localip () {
dev=`iw dev | grep Interface |  awk '{print $2}'`
        ip=`ip addr show $dev | grep 'inet ' |  awk '{print $2}' | cut -f1 -d'/'`
        echo $dev: $ip
 }

localip
printf 'Wireless: ' && localip && echo -n 'ipv6: ' && curl v6.ifconfig.co && echo -n 'ipv4: ' && curl -4 v4.ifconfig.co
ip=`ip addr show $dev | grep 'inet ' |  awk '{print $2}' | cut -f1 -d'/'`
geoiplookup $(curl -4 v4.ifconfig.co 2> /dev/null) 

if [[ `pgrep -c ^wg-crypt-azirev` == "1" ]]; then
   echo "Wireguard Running......."
fi

My version of the ip script:

wlan0: 192.168.0.5
Wireless: wlan0: 192.168.0.5
ipv6: 2a02:c7f:b62f:5100:ad0e:ca7:b52f:f75f
ipv4: 151.227.242.69
GeoIP Country Edition: GB, United Kingdom
4 Likes

Not really a utility script per se, but I set my .bash_aliases to contain the following line ;

alias yay='sudo timeshift --create && yay'

For me, it makes sense in that I never forget to timeshift before an update… :slight_smile:

Every once in a while I go through www.linuxfromscratch.org. Doing this tutorial really helped me develop some good fundamental Linux knowledge. In order to help speed up some of the common monotonous tasks I wrote the below. Instead of sourcing it like the help text suggests, a function in your .bashrc is probably easier. You could also expand this script a bit more but this has served me well.

#!/bin/bash

# run this by sourcing it, i.e. "source lfs -t" or ". lfs -t"
# you can make it easier on yourself by making an alias
# for example, alias lfs="source /path/to/lfs.sh"

# colors to use within the script

BLACK='\033[0;30m'     
DGRAY='\033[1;30m'
RED='\033[0;31m'     
LRED='\033[1;31m'
GREEN='\033[0;32m'     
LGREEN='\033[1;32m'
ORANGE='\033[0;33m'     
YELLOW='\033[1;33m'
BLUE='\033[0;34m'     
LBLUE='\033[1;34m'
PURPLE='\033[0;35m'     
LPURPLE='\033[1;35m'
CYAN='\033[0;36m'     
LCYAN='\033[1;36m'
LGRAY='\033[0;37m'     
WHITE='\033[1;37m'
NC='\033[0m'

case "$1" in
    -t)
        ./configure --prefix=/tools
        make -j$(nproc)
        make install
        printf "${LBLUE}configured and compiled for the ${YELLOW}/tools${NC}${LBLUE} directory for package: ${LGREEN}$lfs_package_dir${NC}\n"
        ;;
    -u)
        ./configure --prefix=/usr
        make -j$(nproc)
        make install
        printf "${LBLUE}configured and compiled for the ${YELLOW}/usr${NC}${LBLUE} directory for package: ${LGREEN}$lfs_package_dir${NC}\n"
        ;;
    -r)
        printf "moving to $lfs_source_dir and removing $lfs_package_dir directory and files...\n"
        cd $lfs_source_dir
        rm -rf $lfs_package_dir
        unset lfs_source_dir 
        printf "${LBLUE}all files have been removed and temp variables unset for package: ${LGREEN}$lfs_package_dir${NC}\n"
        unset lfs_package_dir
        ;;
    -i)
        export lfs_source_dir=$(pwd)
        printf "${LBLUE}extracting files for package: ${LGREEN}$2{NC}\n"
        file_list=$(tar -axvf $2)
        created_dir=$(printf $file_list | cut -f1 -d"/")
        export lfs_package_dir="$created_dir"
        cd $lfs_package_dir
        printf "${LBLUE}extraction complete. now in directory for package: ${LGREEN}$(pwd)${NC}\n" 
        ;;
    
    *)
        printf "LFS Helper Script\n"
  
        printf "\nOptions:\n"
        printf "  -i   extracts the source file and then moves into the extracted directory\n"
        printf "  -t   runs configure with the prefix set to /tools then runs make and make\n"
        printf "       install"
        printf "  -u   same as -t, but with the prefix /usr instead of /tools\n"
        printf "  -r   exits out of the directory and removes it and all its files as well as a\n"
        printf "       build directory, if one was created\n"

        ;;
esac
3 Likes

There is also a pacman hook:

8 Likes