r/bash

▲ 8 r/bash

Help scripting Caps lock on off status

Hey everyone. I have been using linux mint since a year and loved it. It just works without manual tinkering. But now, captivated by the tiling managers, i jumped to Cachy hyprland. It's interesting but doesn't have many basic functionalities like alerting user about Caps lock key status through sound. I took help of ai but it somehow spikes my cpu usage and i have to reboot to make it normal again. Here is the Script :

#!/bin/bash

# Target the specific caps lock directory (adjust if you have a specific one like input3::capslock)

LED_PATH=$(ls -d /sys/class/leds/*::capslock | head -n 1)

# Fallback paths for the sounds

SOUND_ON="/usr/share/sounds/freedesktop/stereo/dialog-information.oga"

SOUND_OFF="/usr/share/sounds/freedesktop/stereo/dialog-warning.oga"

# Read initial state

last_state=$(cat "$LED_PATH/brightness")

while true; do

# Instant raw read of the file system

current_state=$(cat "$LED_PATH/brightness")

if [ "$current_state" != "$last_state" ]; then

if [ "$current_state" -eq 1 ]; then

# Using pw-play or paplay with low-latency flags

pw-play "$SOUND_ON" &

else

pw-play "$SOUND_OFF" &

fi

last_state=$current_state

fi

# 20ms polling rate (0.02s) gives instant human response time

# without hurting CPU performance

sleep 0.02

done

Can you guys please help me out.

reddit.com
u/Landkisabzee — 19 hours ago
▲ 40 r/bash

[VinMail] Bash-ing out emails: built a Bash-based terminal mail manager for multiple email accounts

I recently built VinMail, an interactive CLI mail manager written entirely in Bash that sits on top of msmtp.

It lets you manage multiple email accounts from a terminal interface, compose emails with attachments, switch accounts instantly, save drafts, reply to existing emails from .eml files, and optionally GPG-sign messages. VinMail builds complete RFC 2822/MIME messages itself in pure Bash and sends them directly through msmtp, without requiring a graphical mail client or mail daemon.

The interface supports arrow keys and j/k navigation, while email bodies are edited using your preferred $EDITOR.

GitHub repo: https://github.com/VintellX/vinmail

If this looks interesting, give it a try and let me know what you think. Feedback, bug reports, feature requests, and contributions are all welcome. Thanks for checking it out! :)

Like VinMail? A ⭐ on GitHub would mean a lot. ^_^

u/VintellX — 2 days ago
▲ 40 r/bash+1 crossposts

What is your notification system for long running comands

Hi I usually do large backups that take time and need a notification system that notify me when is done.

Ideally I would like a notification on my phone but any alternative is ok.

Should I set up an email or there is something that is less painful?

reddit.com
u/marianoatm — 3 days ago
▲ 5 r/bash

how do you call the Calendar app from terminal?

Hi, I have installed Calendar, but I can not call it from cmd line...
How doy you call it from terminal?
screenshot GUI
Thank you and Regards!

u/jazei_2021 — 3 days ago
▲ 11 r/bash+1 crossposts

I can't even do the simple - inotify. please help

I'm not good at this. I've been banging my head against a wall for two nights and this tiny, simple script is not working. My goal is to copy a download and paste it to a different folder, leaving the original

#!/bin/bash

source_d="~/data/downloads/data/downloads"

destination_d="~/data/library/ingest"

inotifywait -m -r -e close_write "$source_d" |

while read -r path; do

cp -r "$path" "$destination_d"

done

I've made it as far as having the watch initiated in from the source directory, but it doesn't move anything. Please help, and if it makes you feel good you can call me an idiot.

reddit.com
u/capnfatpants — 3 days ago
▲ 13 r/bash

Beginner here — A personal backup script, would love feedback

Not an experienced programmer. I wrote a Bash script to back up my files to an external drive, Learnt a lot doing that, and I'm posting here because I'd like more experienced people to look at it and tell me what I'm still missing.

The basic idea: it uses rsync with --link-dest to make daily snapshot backups. Each backup looks like a full copy of your files, but files that haven't changed are hard-linked instead of copied again, so it doesn't waste disk space. Something similar to "Time Machine".

Repo is here if anyone wants to look at the code or try to break it: https://github.com/UFpondiboy/linux-snapshot-backup

Any feedback — big picture or nitpicky — is genuinely welcome. I'd rather find out what's wrong now than trust it blindly.

u/No_Condition4387 — 3 days ago
▲ 894 r/bash+1 crossposts

Intellisense autocompletions inside of Bash

The completions are generated using Bash's existing completion framework (commonly scop/bash-completion or your own completion scripts). And if you don't have a completion script setup, flyline will try to synthesize one on the fly (😉) using man pages or --help output!

This is similar to https://github.com/microsoft/inshellisense but inshellisense only works for a hardcoded list of completions specifications and runs in a different process as Bash.

Flyline has a bunch of other features, so if you're interested you can check it out here: https://github.com/HalFrgrd/flyline. Thanks!

This software's code is partially AI-generated

u/gooddy — 5 days ago
▲ 16 r/bash

Volume Mixer for Rotary Knob

Hi all, I've only been using Linux and bash for less than a year now and was wondering if i could get some feedback on a code i just finished. The script is for a rotary knob on my keyboard, that doesn't get much use. I really wanted it to be used for volume control but, the control it gave me out the box only controlled the main volume. So i made a script that gave me finer control over all active applications with the center button on the rotary knob cycling the apps and turning the knob adjusting the volume. Thanks

https://github.com/Thothermese/VolumeMixer

reddit.com
u/EmuWizard — 3 days ago
▲ 10 r/bash

Script to replicate the copy/move behavior in typical file managers (prompt to overwrite?)

AFAIK in file managers in Windows/Linux, they have the same convenient behavior where if you copy one folder into another folder of the same name and there's a conflict (e.g. a folder of the same name already exists), instead of aborting, it prompts to "overwrite" (merge the contents of the folder), recursively. If any of the files result in conflict (e.g. a file of the same name already exists), it prompts the user whether they want to overwrite, letting the user know which is larger and which is newer.

The above is useful if e.g. you abort the copy/move progress half and then want to resume at a later point.


Does anyone have a similar script they can share? How would such a script be implemented? I know rsync can do something similar. With these file managers, they seem to update one file at a time, e.g. when a file is successfully moved during the process, the source file is removed. With rsync, a file gets removed after rsync finishes(?) which is not as intuitive because it does not reflect the latest state of the progress.

Implementation-wise, is it as simple as rsyncing each file one at a time, checking for potential overwrites before rsync and comparing the file size and modification time of files ith stat, then prompting the user if there are conflicts, else rsync that file? Is there a way to do this more efficiently (or ideas for a better UX)? Can rsync or similar tools handle more of this?

Any tips are much appreciated.

reddit.com
u/gkaiser8 — 6 days ago
▲ 13 r/bash

Does anyone know/use about xset dpms?

Hi, I'd like to use that cmd xset for try to get xset -s NOW...
Could I set from terminal this cmd for put blank screen now
and then when I come back I move my finger in touchpad or press any key and OS wake up again...

Thank you and Regards!

reddit.com
u/jazei_2021 — 7 days ago
▲ 45 r/bash

A little fzf function I use constantly to jump into any subfolder

Not sure if this is old news to everyone but I use this all day so figured I'd share. I got sick of typing cd really/long/nested/path/to/thing so I "made" this:

#fuzzy cd into any subdirectory
fcd() {
    local dir
    dir=$(find "${1:-.}" -type d 2>/dev/null | fzf) && cd "$dir" || return
}

Drop it in your .bashrc, open a new shell, and just run fcd. It lists every folder under where you are, you start typing, hit enter, and you're in it. You can also give it a starting point like fcd ~/projects if you don't want to scan from the current dir.

Curious if anyone has a slicker version. I'm sure there's a way to make it faster on huge trees.

reddit.com
u/Infamous-Rem — 9 days ago
▲ 8 r/bash

scp-turbo.sh (replay)

A new iteration on my old idea (half-broken) /r/bash/comments/1ajkmvh/scpturbo/ of a tar-based scp replacement primarily for making faster backups over ssh, especially when you have tens of thousands of small files which takes forever over scp/rsync. After hours of trial and error my most wanted key requirement was added: the --sudo flag which lets you tar huge folders (bigger than the amount of free space on your disk) directly to a stream that is saved on your local machine, compressed to a single file or uncompressed. The destination can be any combination of remote vs local, similar to rsync/scp.

Am I reinventing the wheel? I've searched for existing tools that could do this but didn't find any. Or maybe I didn't know what to search for?

The twist of this script: --sudo requires a passwordless sudo on the target box; I am not comfortable with having no root password on world visible boxes so added an alternative workaround when you DO have to interactively get sudo: --tmux-sudo; the idea is that you manually create a tmux session as your regular user on the remote, do sudo -i inside the session and then detach from it (ctrl+b > d); after this scp-turbo --tmux-sudo remote42:/etc backup-etc-remote42.gz should be able to pick the existing tmux session to run your backup as root with no password prompting (more detailed explanation in --help). Not sure how portable/reliable it is but got it working with a regular ubuntu remote. Is this too crazy? Or am I trying to solve a problem that does not exist?

latest final (?) version: https://gist.github.com/glowinthedark/e56fed33be889cea6ec2326dc33f535d

the key takeaway: all this can be done directly with tar+ssh, the script just wraps the invocation and builds the command line, if you run the script with --verbose --dry-run source target then the script will spit the actual raw tar+ssh command line that you can run directly, which reads pretty much like vogon poetry.

u/coldpizza — 8 days ago
▲ 39 r/bash+5 crossposts

I tried to write a model REPL using only bash, jq, and standard pipes

I’ve recently just started tinkering with using local large language models, focusing on simple, low-dependency CLI setups. I ended up going down a bit of a rabbit hole: I wanted to see if I could build a functional model interaction REPL using exclusively standard command-line building blocks.

I might be reinventing a very weird wheel here, but it turns out you can get surprisingly far using just standard text streams (stdin/stdout), pipes, and append-only logs.

I tried to abide by the Unix philosophy, breaking the REPL into the composition of a few small, single-purpose program. Because the logical flow is just text streams fed through pipes, at any step you can inject tools to inspect or modify the data—like using grep to filter out strings before they hit the model, or pv to benchmark model throughput (not really a standard tool but was pretty useful in my experiments).

A few architectural details I thought this crowd might appreciate:

  • Zero heavy dependencies: No pip, npm, package managers, virtual environments, etc. . It just requires bash, jq, and curl to talk to the local model server. These should be available in most modern CLI environments.
  • Transparent, file-based state: The agent's memory is just an append-only .jsonl file (like .bash_history). If you want to rewind the agent's memory, you just run head on the log to drop the last few lines.
  • Standard exit codes for control flow: Tool execution is handled by checking standard Unix exit codes within a basic bash while loop.

I'm sure there are scaling limits to doing this all in shell, and I'm still figuring out the most elegant way to handle some of the edge cases, particularly around tool calling - but those appear to mostly be limitations of the underlying models. Nevertheless it's been a really fun experiment in stripping out bloat.

I put the code up here if anyone wants to poke around: https://github.com/cloudkj/llayer

Would love to hear if anyone else has tried orchestrating things this way, or if you spot any glaring anti-patterns in how I've structured the pipes!

u/cloud_kj — 11 days ago
▲ 6 r/bash+1 crossposts

Would love Some Advice on an Install Script

I am trying to install artix with Root on one Drive and Home on another Drive

it will be formatted as ext4 of course and use awesome window manager and fastcompmgr

I am wanting to know if this is going to break my install or anything, if something is redundant, etc..

paste.myst.rs
u/1negroup — 8 days ago
▲ 18 r/bash+1 crossposts

Calling All BASH Warriors...

We all love the terminal for its speed, its power, and that raw, unfiltered command-line efficiency. It is where real work gets done.

But even the most hardened command-line veteran needs to blow off some steam.

Back in the day, we had simple ASCII games and hidden Easter eggs tucked away in the system files. Modern Linux keeps that tradition alive, and the repositories are packed with brilliant, useless, and thoroughly entertaining tools designed to turn your terminal into a playground.

Here is the BASH Warriors entertainment list...

--- BASH WARRIOR ENTERTAINMENT LIST ---

Command: Description: Download:

sl (Steam Locomotive): If you type ls wrong, a train chugs across your screen. (sudo apt install sl)

cmatrix: Turns your terminal into the falling code from The Matrix. (sudo apt install cmatrix)

fortune: Prints a random, often funny, quote or message. (sudo apt install fortune-mod)

cowsay: An ASCII art cow that speaks whatever text you give it. (sudo apt install cowsay)

aafire: Renders a realistic fire animation using ASCII characters. (sudo apt install libaa-bin)

xeyes: A pair of eyes that follows your mouse cursor around the screen (requires X11). (sudo apt install x11-apps)

bastet: A bastardized version of Tetris where the game intentionally gives you the worst possible piece. (sudo apt install bastet)

robotfindskitten: A Zen simulation where you navigate a robot to find a kitten among hundreds of random objects. (sudo apt install robotfindskitten)

moon-buggy: Drive a moon buggy over craters in this side-scrolling game. (sudo apt install moon-buggy)

fortune bofh-excuses: Generates corporate excuses for why you are late for work. (sudo apt install fortune-mod fortunes-bofh)

figlet: Creates large, stylized ASCII art banners from your text. Example: figlet "Hello World" (sudo apt install figlet)

telnet towel.blinkenlights.nl You can still watch Star Wars Episode IV entirely in ASCII art via Telnet. (sudo apt install telnet)

apt moo: The package manager has a secret. Run apt moo to see a cow. (No download required)

fortune | cowsay | lolcat: Get a rainbow-colored cow giving you random life advice. (sudo apt install fortune-mod cowsay lolcat)

Asciiquarium is an aquarium/sea animation in ASCII art. (https://github.com/cmatsuoka/asciiquarium)

--- Combo Funpack Download ---

sudo apt update && sudo apt install -y sl cmatrix fortune-mod cowsay libaa-bin x11-apps bastet robotfindskitten moon-buggy fortunes-bofh figlet telnet lolcat

==========================================================

Paste the following at the end of your .bashrc file that is located in your home directory. Customize to your heart's content...

# --- BASH WARRIOR Aliases (APT Package Management) ---

alias refresh='sudo apt update && sudo apt upgrade && sudo apt autoremove'

alias apt2='sudo apt update && sudo apt install'

alias update='sudo apt update'

alias upgrade='sudo apt upgrade'

alias fullup='sudo apt full-upgrade'

alias install='sudo apt install'

alias remove='sudo apt remove'

alias purge='sudo apt purge'

alias cleanup='sudo apt autoremove'

alias searchpkg='apt search'

alias info='apt show'

alias listup='apt list --upgradable'

# --- Enhanced System Calls ---

alias top='htop'

alias port='ss -tulpn'

alias myip='curl -s ifconfig.me'

alias dns='cat /etc/resolv.conf'

alias reboot='sudo reboot'

alias shutdown='sudo shutdown now'

For my DOS Warrior Alias List please goto: https://www.reddit.com/r/pop_os/comments/1u7e7ex/calling_all_dos_warriors/

reddit.com
u/Signal_Care6558 — 11 days ago
▲ 13 r/bash

Shell scripting from scratch — what would you do differently?

If you could restart your shell scripting journey with your current knowledge, what would you do differently in the first 30 days — and what common mistakes would you tell your past self to avoid?

reddit.com
u/SuccessfulMonth8401 — 12 days ago
▲ 10 r/bash

How redraw the current line of bash?

I make some bindings to help me navigate using the terminal, but I couldn't get to redraw the current lime. I would like to have ps1 info update to display the directory changes.

https://gist.github.com/srcid/25f376b60e6ec2f5b5d20b4eca88b176

I tried:

__update_prompt() {
  echo -ne "\r\e[K"
  kill -INT $$
}

But it breaks line and output with error sing

__update_prompt() {
  echo -ne "\r\e[K${PS1@P}"
  READLINE_LINE="$READLINE_LINE"
}

That kinda work, but the old ps1 sticks in the line, I couldn't get rid of it.

u/GuitaristKitten — 9 days ago
▲ 8 r/bash+1 crossposts

Bash 3.2 alternative to read -i for prefilled user input on macOS

Hi everyone,

I have a script that works fine on Linux with Bash 4.x+, where I use read -e -i to prefill existing values and allow the user to edit them:

case "$vals" in

b|B) echo -ne " ${CYAN}Bsl${RESET}: " read -e -i "$bsl" -r bsl ;;

t|T) echo -ne " ${CYAN}Term${RESET}: " read -e -i "$term" -r term ;;

s|S) echo -ne " ${CYAN}Site${RESET}: " read -e -i "$site" -r site ;;

c|C) echo -ne " ${CYAN}Capt${RESET}: " read -e -i "$capt" -r capt ;;

esac

However, on macOS (which ships with Bash 3.2), I get:

read: -i invalid option read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...]

From what I understand, the -i option was introduced in Bash 4+.

Is there any portable workaround or alternative way to present a default/prefilled value to the user in Bash 3.2 while still allowing them to edit it interactively?

I'd appreciate any suggestions or examples that work on both Linux and macOS.

Thanks!

reddit.com
u/GaramChandraGandhi — 11 days ago
▲ 10 r/bash

Bash Noughts & Crosses (Tic Tac Toe)

So as one or two regular readers may have noticed, I occasionally write terminal games. Everyone needs a hobby, right?

This is one I'd intended to write for a long time, albeit not necessarily in Bash, because it uses a technique called 'Minimax' that I had to study on an AI course decades ago, but never coded.

Until now. I've reused the same mouse control function from previous games. Hope some may find it of interest.

If I'm honest, it was probably a lot more interesting as a coding exercise than as a game, because by default it's impossible for the computer opponent to lose. I've introduced a "compromised" mode to overcome this and let the human win occasionally.

https://github.com/StarShovel/bash-noughts

u/LoneGroover1960 — 10 days ago
▲ 85 r/bash

A joke using Grep

We were discussing ways to use Grep at work today and I came up with this...

grep -R ^"My Car Keys"$ /home/

If only life was that easy... But I'm still going to put it on a t-shirt.

reddit.com
u/thisiszeev — 14 days ago