Share your useful aliases and functions

Some of my zsh aliases and functions.
A few require fping and wl-copy (Wayland clipboard); paths need to be adjusted.

alias al='{alias; cat ~/.zsh/.aliasy|grep "() "}|sort|fzf'                  # Browse all aliases and functions interactively with fzf – adjust functions path as needed

alias fp='fping -c 7 -g 192.168.1.0/24 &>/tmp/ping; cat /tmp/ping|grep min'  # Quick network scan 

#pacman
alias up='sudo pacman -Syu'                                                # Full system upgrade (Arch Linux) or install package
alias pi="pacman -Sii"                                                     # Show detailed package info + dependencies/reverse deps
alias pfile="pacman -F"                                                    # Search which package provides a file
alias pf="pacman -Ss "                                                     # Search packages in repos (remote)
alias pd="pactree -r "                                                     # Show reverse dependencies of a package

#recently installed or updated packages list / with description
alias rup="expac --timefmt='%Y-%m-%d %T' '%l\t%n %v' | sort"                # List recently updated packages with date/version
alias rip='grep " installed" /var/log/pacman.log | grep -v "\[ALPM-SCRIPTLET\]" |grep -Ff <(pacman -Qq| sed "s/^/ /"|sed "s/$/ /") |sed -E "s/T([0-9]{2}:[0-9]{2}:[0-9]{2})\+[0-9]{4}/ \1/"| sed "s/\[ALPM\] installed //"'  # List recently installed packages from pacman.log
ri() { rip | tac | fzf --height=100% --preview 'pacman -Sii $(echo {} | awk "{print \$3}")' --preview-window=down | wl-copy; }  # Interactive fzf search of recently installed packages + copy name
ru() { rup | tac | fzf --height=100% --preview 'pacman -Sii $(echo {} | awk "{print \$3}")' --preview-window=down | wl-copy; }  # Interactive fzf search of recently updated packages + copy name

#search
f() { fd -H -E .cache -E .platformio -E .esphome -E .local/share/Steam $@; }  # Fast find (fd)  ignoring large cache directories, e.g. f filename (search in the home directory) or f filename path (search in a given location)
ff() { f $@ | fzf --height=100% --preview "bat --color=always --style=numbers --line-range=:100 {}" |wl-copy; }  # Find file → fzf with bat preview → copy path
fa() { fd -H $@; }                                                         # Find everything (including hidden, no excludes)
ffd() { f -t d $@ 2>/dev/null |fzf --height=100% |wl-copy; }             # Find directories only → fzf → copy path

#
alias -g NE="2> /dev/null"                                                 # Redirect stderr to /dev/null
alias -g NUL="> /dev/null 2>&1"                                             # Redirect both stdout and stderr to /dev/null

Edit: add set -k to .zshrc to accept # comments

alias sleep 'systemctl suspend'
alias die 'shutdown now'

I put these up because suspend or shutdown often fails if I use KDE Plasma’s Sleep or Shutdown button.

This is not very graceful though.

And the following is over-engineered but you can rip off the relevant commands;

plasma-poweroff() {
        OPTIND=1         # Reset in case getopts has been used previously in the shell.

        show_help() {
                cat <<EOF

l = logout
r = reboot
s = shutdown

EOF
        }

        while getopts "h?lrs" opt; do
                case "$opt" in
                        h|\?)
                        show_help
                        ;;
                        l)
                        qdbus6 org.kde.Shutdown /Shutdown logout
                        ;;
                        r)
                        qdbus6 org.kde.Shutdown /Shutdown logoutAndReboot
                        ;;
                        s)
                        qdbus6 org.kde.Shutdown /Shutdown logoutAndShutdown
                        ;;
                esac
        done
        shift $((OPTIND-1))
        [ "${1:-}" = "--" ] && shift
}
# some personal conveniences 
alias cls=clear
alias cowsay="nocorrect cowsay -f small"
alias ff='clear && fastfetch'
alias grep='grep --color=auto'
alias orphans='pacman -Qdt'

alias mountcloud='sshfs xxx@redacted:/home/shared/www/redacted/mycloud ~/mycloud/'
alias umountcloud='fusermount3 -u ~/mycloud/'

# taken from CachyOS's fish config (I think)
alias hw='hwinfo --short'                                   # Hardware Info
alias big="expac -H M '%m\t%n' | sort -h | nl"              # Sort installed packages according to size in MB
alias gitpkg='pacman -Q | grep -i "\-git" | wc -l'          # List amount of -git packages
alias update='sudo pacman -Syu'

# Replace ls with eza
alias ls='eza -al --color=always --group-directories-first --icons' # preferred listing
alias la='eza -a --color=always --group-directories-first --icons'  # all files and dirs
alias ll='eza -l --color=always --group-directories-first --icons'  # long format
alias lla='eza -al --color=always --group-directories-first --icons'  # all files and dirs long format
alias lt='eza -aT --color=always --group-directories-first --icons' # tree listing
alias l.="eza -a | grep -e '^\.'"

A rather interesting topic, as I haven’t given aliases much thought before.

So far, I’ve been using the first letter or the first two letters, and then completing the command with the arrow key.

“Many roads lead to Rome.”

I only use one alias…

alias up='yay -Pw && yay -Syyu && flatpak update && flatpak uninstall --unused'

That looks like a complete solution.

I don’t require an AUR wrapper myself, so a simple u is sufficient for me.

I am an old timer and always used yay until the last couple of years.
Hard to teach an old dog new tricks. So I made …..
alias yay=“paru”

I hear ya. I’m definitely old school. Anytime I do a fresh install of CachyOS, the first thing I do is install and set up yay (along with my alias) and Flathub. Nothing against paru, I just prefer yay. The second thing I do is uninstall Octopi. I have no use for GUI installers.

I actually have come to prefer paru now. It is yay based with significant improvements.
Yes some do not like pkg managers. I do like them.

I use pamac to find dependancies and easily view what is installed or missing. Use paru to install or uninstall anything though. The GUI is purely to speed up visual referencing.

Love your flatpak udate alias and have taken that. Thank you. Wish there was a way to do Discover and grab my updated icons, color schemes ect ….

Ok I spent a few minutes prettying some of the ones I have, which includes some that were more for fun than anything else .. anyways here is a selection with them slightly organized with some extra comments and such.

# Sensible shfmt replacement for beautysh
beautysh() { shfmt -i 4 -ci "$@" ; }


# Remote screenfetch
fetchscr() { curl -fsSL https://raw.githubusercontent.com/KittyKatt/screenFetch/master/screenfetch-dev | bash ; }


# No nonsense webcam
cammpv() {
    echo -e "\nStarting Webcam!\nType 's' to save image to current path.\n"
    mpv --profile=low-latency --untimed --demuxer-lavf-format=video4linux2 --demuxer-lavf-o-set=input_format=mjpeg av://v4l2:/dev/video0
}
mpvcam() { cammpv ; }


# Simple bc replacement
ccalc() { awk "BEGIN{print $*}"; }


# Hacky launcher
cscs-open() {
    awk 'BEGIN {command=""} /^Exec=/ {sub("^Exec=", ""); gsub(" ?%[cDdFfikmNnUuv]", ""); command=$0; exit} END {if (command!="") {exit system(command)} else {if (FILENAME == "-") {printf "ERROR: Failed to identify Exec line\n" > "/dev/stderr"} else {printf "ERROR: Failed to identify Exec line in \047%s\047\n", FILENAME > "/dev/stderr"} close("/dev/stderr"); exit 1}}' $@
}


# Slightly more memorable kioclient launcher
kio-open() {
    kioclient exec $@
}


# Seems this is what plasma uses for xkill-like function on wayland
kkill() {
    qdbus6 org.kde.KWin /KWin killWindow
}


# List size of path and top #, else root and top 20
lssz() {
    if [ "${#1}" -eq 0 ]; then local dir="/"; else local dir="$1"; fi
    if [ "${#2}" -eq 0 ]; then local outct="20"; else local outct="$2"; fi
    du -h "$dir" 2>/dev/null | sort -hr | head -"$outct"
}


# Replace or "mv" links
mvln() {
    DIR=$1
    OLD_PATTERN=$2
    NEW_PATTERN=$3

    while read -r line; do
        echo $line
        CUR_LINK_PATH="$(readlink "$line")"
        NEW_LINK_PATH="$CUR_LINK_PATH"
        NEW_LINK_PATH="${NEW_LINK_PATH/"$OLD_PATTERN"/"$NEW_PATTERN"}"
        rm "$line"
        ln -s "$NEW_LINK_PATH" "$line"
    done <<<$(find "$DIR" -type l)
}


# Print the octal permissions
octal() { stat -c '%a %n' "$@" ; }


# Simple stopwatch, <Enter> stops
stopwatch() {
    local BEGIN=$(date +%s)
    echo Starting Stopwatch...

    while true; do
        local NOW=$(date +%s)
        local DIFF=$(($NOW - $BEGIN))
        local MINS=$(($DIFF / 60))
        local SECS=$(($DIFF % 60))
        local HOURS=$(($DIFF / 3600))
        local DAYS=$(($DIFF / 86400))

        printf "\r%3d Days, %02d:%02d:%02d" $DAYS $HOURS $MINS $SECS
        read -rsN1 -t1 key
        if [ "$key" == $'\x0a' ]; then
            # echo -e "\n [Enter] Pressed"
            break
        fi
    done
    echo
}


# yt mp3 download
ymp3() {
    yt-dlp --concurrent-fragments 8 --no-warnings --extract-audio --audio-format mp3 "$@"
}


# My publc IP
myipp() {
    _myipp=$(curl -s --max-time 5 https://api.ipify.org); echo $_myipp
}


# My local IP
myipl() {
    ip -4 addr show wlan0 scope global | awk '/inet/{print $2}' | head -n1
}


# Simple local server using python 
pyserv() {
    _pyserv=$(ip route | tail -n1 | awk '{print $9}')
    echo "Starting share server at "$_pyserv":4444"
    python -m http.server 4444
}


# Upload to temp.sh
tempload() {
    local url='https://temp.sh/upload'
    if (($#)); then
        local file
        for file; do
            curl -F "file=@""$file""" "$url"
        done
    else
        curl -F 'file=@-' "$url"
    fi
}


# Upload to 0x0.st
0paste() {
    local url='https://0x0.st'
    if (($#)); then
        local file
        for file; do
            curl -F "file=@""$file""" "$url"
        done
    else
        curl -F 'file=@-' "$url"
    fi
}


# VPN connect
vpnup() {
    wg-quick up "$@"
}


# VPN list
vpnlist() {
    sudo -v; echo;
    for file in $(sudo ls /etc/wireguard); do echo -ne "\033[1m${file%".conf"}\033[0m\t" && sudo awk '/LOCATION/ {print $3,$4}' /etc/wireguard/$file; done | sort -k3,3 -k2,2 | column -t | sed 's/$/\n/'
}


# VPN ending
vpndown() {
    _curvpn=$(sudo wg show | awk 'NR==1 { print $2}')
    wg-quick down "$_curvpn"
}


# VPN information, or not connected 
vpnstat() {
    if sudo wg show | sed -n '1p;11,12p'; then
        :
    else
        echo "No VPN Up."
    fi
}


# What interface is used
whichroute() {
    ip -o route get 1.1.1.1 | awk '{print $3}'
}


# What terminal emulator is used
whichterm() {
    basename "$(cat "/proc/$PPID/comm")"
}


# A Fuzzy package manager
fuzman() {
    cmd=$(paru -Slq | fzf --prompt 'paru> ' \
        --header 'Install packages. CTRL+(Pacman/Aur/Installed)' \
        --bind 'ctrl-p:change-prompt(pacman> )+reload(pacman -Slq)' \
        --bind 'ctrl-a:change-prompt(paru> )+reload(paru -Slq)' \
        --bind 'ctrl-i:change-prompt(inst> )+reload(paru -Qq)' \
        --multi --height=80% --preview 'sleep 2; paru -Si {1}' \
        --preview-window bottom) #| xargs -ro yay -S
    cmd=${cmd//$'\n'/ }          # newline -> space
    if ! [ -z "$cmd" ]; then
        print -z paru -S $cmd
    fi
}


# Simpler fuzzy yay
yas() { yay -Slq | fzf -m --preview 'yay -Si {1}' | xargs -ro yay -S; }


# Simpler fuzzy paru
pas() { paru -Slq | fzf -m --preview 'paru -Si {1}' | xargs -ro paru -S; }


# All the package sizes
pacszs() {
    LC_ALL=C.UTF-8 pacman -Qi | awk '/^Name/{name=$3} /^Installed Size/{print $4$5, name}' | LC_ALL=C.UTF-8 sort -h
}


# Use official mirror for AUR
aurmirror() {
    git clone -b "$@" --single-branch https://github.com/archlinux/aur.git "$@"
    less ./"$@"/PKGBUILD
    while true; do
        read -rp $'\n'" Do you wish to build and install $@ (y/N)? " yn
        case $yn in
            [Yy]*)
                echo
                cd ./"$@" && makepkg -sric
                cd ..
                break
                ;;
            [Nn]* | *)
                echo
                break
                ;;
        esac
    done
}


# hblock only defaults to 4 parallels
alias hblock='hblock -p 24'


# Hack to allow sudo in aliases
alias sudo='sudo '


# Like the ubuntu thing without any package
alias update-grub='grub-mkconfig -o /boot/grub/grub.cfg'


alias updchk='checkupdates'


alias chkupd='checkupdates'


alias install-grub='grub-install --target=x86_64-efi --efi-directory=/efi --bootloader-id=GRUB'


alias updigs='sudo mkinitcpio -P && sudo update-grub'


alias updpau='sudo pacman -Syu && paru -Sua && sudo pacman -Fy'


alias updref='hblock && maclean -a'


alias updall='updpau && pacdiff -s && updigs && updref'

Wow. That is a lot. ymp3 made my day :grinning_face_with_smiling_eyes:

@cscs Wow! Inspiring!

some more :wink:

# Remote  hosts
export s1=user@99.97.0.1
export s2=user@99.97.0.2

# Midnight Commander shortcuts over SSH
alias mc1="mc sh://$s1:/home/user"          # Open MC connected to s1
alias mc2="mc sh://$s2:/home/user"          # Open MC connected to s2 
alias mc12="mc sh://$s1:/home/pi sh://$s2:/home/pi"  # Open MC with both s1 and s2 panels

# SCP wrappers for quick copy to remote hosts
cp1() { scp $1 $s1:$2; }                   # Copy file to s1 (usage: cp1 localfile remotepath)
cp2() { scp $1 $s2:$2; }                   # Copy file to s2 (usage: cp2 localfile remotepath)

alias nano='nano --rcfile=~/.zsh/.nanorc'  # Use custom nano config

# Full ESPHome environment update + cleanup old builds
alias uph='cd && [ -d ".platformio/" ] && sudo rm .platformio/ -r; [ -d "s/esp/.esphome" ] && sudo rm s/esp/.esphome -r; \
printf ESPHOME::; source ~/.esp/bin/activate && pip3 install -U esphome|grep -v "Requirement already satisfied:"; deactivate; echo DONE'

alias gl='nmcli connection up "GL" && sudo ip link set wlo1 mtu 1280'  # Connect to mobile hotspot + lower MTU (fixes some tethering issues)


# Show IPs from current scan with hostnames from text file 
alias fpd='fping -c2 -g 192.168.1.0/24 &>/tmp/ping; grep min /tmp/ping | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}" | sed -E "s/.*(\.[0-9]+)$/\1/" | while read ip; do grep -m1 "^$ip" ~/path_to_net/net.txt || echo "$ip"; done'

alias grubup='sudo grub-mkconfig -o /boot/grub/grub.cfg'  # Regenerate GRUB config

# Journalctl shortcuts
alias j='sudo journalctl -xr'   # Recent logs, newest first, with explanations
alias jr='sudo journalctl -x'   # Follow logs with explanations
alias jf='sudo journalctl -xf'  # Follow logs live
alias s='sudo systemctl'        # Short systemctl
alias sr='sudo systemctl restart'  # Restart service
alias ss='sudo systemctl status'   # Service status

alias n='micro --filetype=zsh'     # Open micro editor with zsh syntax

# Force CPU scaling governor to minimum/maximum frequency (power saving / performance)
alias cmin='for C in /sys/devices/system/cpu/cpu[0-15]*; do sudo tee "$C/cpufreq/scaling_max_freq" <<< "$(cat "$C/cpufreq/cpuinfo_min_freq")" > /dev/null; done'
alias cmax='for C in /sys/devices/system/cpu/cpu[0-15]*; do sudo tee "$C/cpufreq/scaling_max_freq" <<< "$(cat "$C/cpufreq/cpuinfo_max_freq")" > /dev/null; done'

# Enable/disable specific number of CPU cores (starting from core 1)
cpu() { n=$1; i=1; for cpu in /sys/devices/system/cpu/cpu([1-9]*)/online; do [[ $i -lt $n ]] && echo 1 | sudo tee $cpu > /dev/null || echo 0 | sudo tee $cpu > /dev/null; ((i++)); done; }

# NVIDIA GPU lock clock shortcuts 
alias nv='sudo nvidia-smi -lgc 210,3105|head -n 1'   # Normal/high performance
alias nv8='sudo nvidia-smi -lgc 210,2700|head -n 1'  # 
alias nv6='sudo nvidia-smi -lgc 210,1800|head -n 1'
alias nv3='sudo nvidia-smi -lgc 210,1000|head -n 1'
alias nv1='sudo nvidia-smi -lgc 210,210|head -n 1'   # Extreme power saving

alias p='upower -d |grep -e energy-rate -e "time to empty"|sort|uniq'  # Quick power in W, time to empty

alias caf='systemd-inhibit --what=idle:sleep'  # Prevent suspend/sleep (caffeine mode)

# ESPHome shortcuts (activate venv first)
alias eh='source ~/.esp/bin/activate; esphome'           # Enter ESPHome command
alias ehr='source ~/.esp/bin/activate; esphome run'      # Run/upload
alias ehcl='source ~/.esp/bin/activate; esphome clean'   # Clean build
alias ehc='source ~/.esp/bin/activate; esphome compile'  # Compile only
alias ehl='source ~/.esp/bin/activate; esphome logs'     # Show logs
alias ehu='source ~/.esp/bin/activate; esphome upload'   # Upload only
alias ehd='source ~/.esp/bin/activate && esphome dashboard ~/s/esp/ &; xdg-open http://0.0.0.0:6052'  # Start dashboard + open browser

# Better ls replacements with eza
alias eza='eza --color=always --group-directories-first --icons'
alias ls='eza -l'          # Long list
alias la='eza -a'          # Show hidden
alias ll='eza -alg'        # Long + hidden + user/group
alias lt='eza -aT'         # Tree view
alias l.='command eza -a| grep -e "^\."'  # Show only dotfiles
alias l='eza'              # Short list

# Archive shortcuts
alias tarnow='tar -acf '   # Create .tar.zst archive (zstd compression)
alias untar='tar -zxvf '   # Extract tar.gz

alias wget='wget -c --no-hsts'  # Resume support + disable HSTS file


# System update shortcuts (CachyOS/Arch)
alias upd='arch-update'           # Fancy update script
alias up='sudo pacman -Syu'       # Standard pacman upgrade
alias mirror="sudo cachyos-rate-mirrors"  # Update mirrorlist with fastest mirrors

alias err="journalctl -p 3 -xb"   # Show only errors from current boot

# Quick web search in Brave via DuckDuckGo
ws() { brave "https://duckduckgo.com/?q=$*"; }

# Open file in KWrite detached
kw() { kwrite "$@" &>/dev/null & disown; }

# Silent ripgrep (hide errors)
rg() { command rg "$@" 2>/dev/null; }

Do scripts count? I just made this script to use with hypridle. I’m kinda new to scripting so let me know if there are better ways to go about what I’m doing here. It uses ddcutil to save the current brightness value of a monitor and dim it. It can also restore the saved brightness value if used again (different arguments).

#!/usr/bin/env bash
# save monitor brightness and dim monitor with "dim" argument
# restor brightness with "restore" argument

# ------- User Config ---------
MONITOR="${2:-1}"                               # monitor identifier
CACHE_DIR="${XDG_CACHE_HOME}/ddc_brightness"    # cache directory
DIM_LEVEL=0                                     # level to dim to (0-100)
# -----------------------------

# Verify ddcutil is installed
if ! command -v ddcutil >/dev/null 2>&1; then
    echo "ddcutil not found" >&2
    exit 1
fi

# Make sure the cache directory exists
if [ ! -d "${CACHE_DIR}" ]; then
    mkdir -p "${CACHE_DIR}"
    chmod 700 "${CACHE_DIR}"
fi

# -----------------------------

case "$1" in
    dim) # Save current monitor value then dim
        CUR=$(ddcutil --display 1 getvcp 10 |
            awk '/current[[:space:]]+value/ {
                if (match($0, /current[[:space:]]+value[[:space:]]*=[[:space:]]*([0-9]+)/, m)) {
                    print m[1]
                }
            }'
        )
        echo "$CUR" > "${CACHE_DIR}/lastvalue"  # save the value
        chmod 600 "${CACHE_DIR}/lastvalue"
        ddcutil --display "$MONITOR" setvcp 10 "$DIM_LEVEL"  # Dim the monitor
    ;;
    restore)    # Restore the previously saved value to the monitor
        if [[ -f "${CACHE_DIR}/lastvalue" ]]; then
            PREV=$(cat "${CACHE_DIR}/lastvalue")
            ddcutil --display "$MONITOR" setvcp 10 "$PREV"
        else
            echo "No cached brightness found" >&2
        fi
    ;;
    *)
        echo "Usage: ${0##*/} {dim|restore} [monitor #]" >&2
        echo 'Use "ddcutil detect" to find which monitor number you would like to use. Defaults to "1" if nothing is passed.'
        exit 1
    ;;
esac

Very Nice!