Why variable is not updated in the function called in a while loop?
```
readonly BATTERY_CRITICAL_THRESHOLD=15
readonly REFRESH_INTERVAL=1
readonly BAT_PATH="/sys/class/power_supply/BAT0/capacity"
BATTERY_ALERT_STATE=0
get_battery_status() {
local battery_pct ac_state icon
battery_pct=$(<"$BAT_PATH")
ac_state=$(<"$AC_PATH")
if ((battery_pct <= BATTERY_CRITICAL_THRESHOLD)) && ((BATTERY_ALERT_STATE == 0)); then
BATTERY_ALERT_STATE=1
notify-send "Battery Critical" "Battery level is at $battery_pct%"
elif ((battery_pct > BATTERY_CRITICAL_THRESHOLD)) && ((BATTERY_ALERT_STATE == 1)); then
BATTERY_ALERT_STATE=0
fi
printf '%s%%' "$battery_pct"
}
# Main loop in main shell context
while true; do
get_battery_status
sleep "$REFRESH_INTERVAL"
done
```
Above is a bash script I write.
What I expect is it will change `BATTERY_ALERT_STATE` to 1 when battery level is lower than 15, and then send a notification. After `BATTERY_ALERT_STATE` is changed to 1, it won't be changed until the battery_pct is greater than `BATTERY_CRITICAL_THRESHOLD`.
But, in practice, it's not the case, it seems that `BATTERY_ALERT_STATE` has never been changed, and therefore the notification is continueously being sent.
I don't know why, I have debugged it for days, searched online and asked ai, no result.
Can anyone told me why?
https://redd.it/1hjbl7t
@r_bash
Executing a script from another script programmatically (regardless of run location)
I'm trying to build a simple script that will stop my docker containers, drop a volume, then start my containers back up. To start my containers, I have a helper script in the root of my project, compose.sh
. The script I'm creating is in a subfolder, scripts
.
Is there a way to essentially do "if subfolder, go up a folder, then run script"? If I run the script from the root, it'd need to search the current location for the compose script. If run from elsewhere, it'd need to go up a level from the script's location to find the compose script.
I know I can hard code the script, but that's inflexible, as if the script is moved to another machine, it'd need to be modified. I don't know if my thinking of how to write this script is wrong, and would appreciate any feedback.
https://redd.it/1hhbaz2
@r_bash
tuiplette, a terminal match-three game (Bash)
https://www.reddit.com/gallery/1hhsh04
https://redd.it/1hi3fz8
@r_bash
Find files larger than X mb and promp to delete/skip each one found
Hi. I've asked Gemini, Copilot, Claude, etc. for a bash script to find files larger than X mb (this should be a parameter to the script) starting in the current path, recursively, and then read (prompt) a question to delete or skip each one found.
I've got this:#!/bin/bash
if [ $# -ne 1 ]; then
echo "Usage: $0 <size_in_MB>"
exit 1
fi
size_in_mb=$1
find . -type f -size +"${size_in_mb}M" | while IFS= read -r file; do
# Get the file size
size=$(du -h "$file" | cut -f1)
echo "File: $file"
echo "Size: $size"
while true; do
read -p "Do you want to delete this file? (y/n): " choice
case "$choice" in
[Yy]* )
rm "$file"
echo "Deleted: $file"
break
;;
[Nn]* )
echo "Skipped: $file"
break
;;
* )
echo "Please answer y or n."
;;
esac
done
done
When executing "./findlargefiles.sh 50", I'm getting an infinite loop of
"Please answer y or n."
Any ideas? I'm trying it on an Ubuntu 22.04 server
Thanks
https://redd.it/1hhtp6g
@r_bash
simple bash script/syntax help?
Hi there -
I'm looking for help with a fairly simple bash script/syntax. (If this isn't the right place, let me know!)
I am trying to write a script that will be run frequently (maybe every 10 minutes) in a short mode, but will run a different way (long mode) every 24 hours. (I can create a specific lock file in place so that it will exit if already running).
My thinking is that I can just...
* check for a timestamp file
* If doesn't exist, run **echo $(date) > tmpfile** and run the long mode(assuming this format is adequate)
* if it exists, then pull the date from tmpfile into a variable and if it's < t hours in the past, then run the short mode, otherwise, run it the long mode (and re-seed the tmpfile).
Concept is straightforward, but I just don't know the bash syntax for pulling a date (string) from a file, and doing a datediff in seconds from now, and branching accordingly.
Does anyone have any similar code snippets that could help?
https://redd.it/1hh2wfx
@r_bash
Matches - A CLI game I coded in Bash
It's based on a two player game that was played in the trenches of World War One.
I made the game as an exercise in learning three new skills with Bash.
YouTube video showing the game being played: https://www.youtube.com/watch?v=24Wrz82JowA
Git Repo to download the game: https://git.zaks.web.za/thisiszeev/matches
Download it, try it out, give me feedback, something something something, profit.
https://redd.it/1hgq6r3
@r_bash
Globbing expansion within variable
I notice this simple script behaves differently in bash and zsh
#! /bin/zsh
while read lin
do
echo DEBUG line $lin
done << EOJ
foo * bar
EOJ
In zsh I get the expected output `DEBUG line foo * bar`, but with bash the asterisk is expanded to a list of the files in the current directory. It happens with standard input as well as with HERE documents.
What bash setting could be causing this double evaluation/expansion after assignment, and how do I get similar behavoir to zsh? I do not have any glob or expansion parameter settings in my `.bashrc` so it seems to be a difference with the default bash settings in Ubuntu.
I do not want input text to be interpreted or expanded in any way unless I explicitly use `eval` or `$()`as this is a security risk.
https://redd.it/1hg8crb
@r_bash
Looking for examples of optimized bash environments for Ansible, Python, Bash development
I'm a fan of utilizing Cygwin for my development and like the feel of running in a CLI vs utilizing something like vscode. I'd like to optimize by bash environment with functions, aliases, etc. I'm looking for examples of useful bash functions or nice bashrc files to optimize development of Python, Ansible (YAML), Bash scripts, etc.
https://redd.it/1hfwnux
@r_bash
Your POV on my app.
Hi, I was wondering whether I should add GUI to my project here or not. It's an app I made which makes managing wine easier, from winehq repositories for enthusiasts like me to install the latest features.
Currently the 4.0 version is in development and adding more features to it.
What's your view on this? Should I do it in shell or Java?
https://redd.it/1hex5e9
@r_bash
made my first (actually) bash script for first time
I written little bash scripts before, they we're either just things to start wm and unfinished personal projects that was only for me, so I think I can count that one project as my first actually project that subreddit looked like where I should share it so I'm posting it in here
timecomp.sh: small script compare two different command with time command, with nice UI
preview
please tell me if you find something missing in the script or if its bad and why. I share it for getting review from other people and improve
(sorry for my bad grammar I'm not good at english)
github repo:https://github.com/LeVeryEpicUsername/timecomp.sh/tree/main
https://redd.it/1herubj
@r_bash
dLine: command-line productivity tool
If you hate multitasking while you're deep in your IDE, I feel you. I always wanted a calendar that lives right in my terminal - something that can keep track of notes, deadlines, meetings, and events, while also reminding me when something important comes up.
So, I built dLine! 🎉
dLine: command-line productivity tool
It’s a bash script that not only manages your schedule but also fetches public and school holidays (only EU countries are supported for now) and even syncs with your Google Calendar. Perfect for keeping your life in check without ever leaving your terminal (IDE).
Check it out and let me know what you think!
https://redd.it/1hdsuaa
@r_bash
bash profiler to measure cost of execuction of commands
I couldn't find or was not satisfied with existing tools for profiling the speed-ness of execution of Bash scripts, so I decided to write my own. Welcome:
https://github.com/Kamilcuk/L\_bash\_profile
It is "good enough" for me, but could be improved by tracking PIDs of children correctly and with some more documentation and less confusing output. I decided to share it anyway. The profile
subcommand generates profiling information by printing timestamped BASHCOMMAND using DEBUG trap or set -x. Then `analyze` subcommand can analyze the profiling data, subtracting the timestamps, print summary of the most expensive calls, generate a dot callgraph of functions or commands, or similar.
For example, is `sleep 0.1` faster than `sleep 0.2`? Let's make a contrived example.
$ Lbashprofile profile --before 'a() { sleep 0.1; }; b() { sleep 0.2; }' --repeat 10 -o profile.txt 'a;b'
PROFILING: 'a;b' to profile.txt
PROFING ENDED, output in profile.txt
$ Lbashprofile analyze profile.txt
Top 4 cummulatively longest commands:
percent spentus cmd calls spentPerCall topCaller1 topCaller2 topCaller3 example
--------- ---------- --------- ------- -------------- ------------ ------------ ------------ -------------
66.3129 2019599 sleep 0.2 10 201960 b 10 environment:5
33.4767 1019553 sleep 0.1 10 101955 a 10 environment:5
....some more lines...
Well, sleep 0.2
tool 201960
microseconds per call and sleep 0.1
took 101955
microseconds per call, so very suprisingly sleep 0.1
is faster.
Maybe someone will profit from this tool and even motivate me to develop it some further, so I decided to share it. Have fun.
https://redd.it/1hdncbl
@r_bash
Is this example valid?
I found an example in a Bash scripting course teaching material:
#!/bin/bash
capslocker() {
local PHRASE="Goodbye!"
return ${PHRASE^^}
}
echo $(capslocker) # will result in “GOODBYE!”
As far as I know there is no way to return non-integer values from a function and return
only sets $?
. If I'm not mistaken, this code snippet doesn't make sense because in order to "return" a string, you need to use echo
.
Am I right or am I wrong about something?
Source: https://imgur.com/AmNJeQ0 (sorry guys, I don't have direct link to the code snippets)
https://redd.it/1hc2j1h
@r_bash
Hex to ASCII conversion - noob question
Hi all, freshly joined noobie here :)
I am currently working as a jr embedded software engineer, and have been struggling with data collection at runtime of the application.
I'm using a debugger that keeps sending a variable's hex value to the host pc via usb, but since this value is interpreted as ASCII, I see invalid symbols on the terminal.
As naive as it may sound, my question is: is there a way with a script to "get in between" the debugger and the terminal on the host pc to convert these hex values in their ASCII counterpart, so they are displayable "correctly"? (like, if I send 0x0123 I'd like the terminal to show "291" instead of the symbols associated with 0x01 and 0x23).
Extra question: do you have any suggestion on material I can study on to get a solid knowledge of bash scripting in general, too?
Thank you for your time and your patience, I hope I didn't sound too stupid haha.
https://redd.it/1hchsln
@r_bash
Cron Python Venv VPS issue
Hi guys,
0 0 * * * source $VENV_ACTIVATE && python $SCRIPT_PATH >> $LOG_FILE 2>&1
$SCRIPT_PATH
, which requires to activate a Python’s Virtual Environment, at midnight UTC then redirect Std out and err into $LOG_FILE
. systemctl status cron
the cron is running like clockwork but the $LOG_FILE
isn’t being overwritten. source $VENV_ACTIVATE
is mentioned (in the status / log). If I remember correctly.
# Set timezone to UTC
log "Setting timezone to UTC..."
sudo timedatectl set-timezone UTC
# Define the cron job command
CRON_JOB="0 0 * * * source $VENV_ACTIVATE && python $SCRIPT_PATH > $LOG_FILE 2>&1"
# Add the cron job
log "Adding the cron job to execute the script at 00:00 UTC daily..."
(crontab -l 2>/dev/null; echo "$CRON_JOB") | crontab -
# Verify if the cron job was added successfully
if crontab -l | grep -q "$SCRIPT_PATH"; then
log "Cron job successfully added."
else
log "Error: Failed to add the cron job."
exit 1
fi
cron.service
is enabled by systemctl. crontab -l
Change terminal color programmatically?
Hello mates, I am using bash terminal. I can change my terminal color if an ssh session is opened. I wrote a function if "$SSH_CONNECTION" then the terminal color is changed. However, I want to do similar change for virtualenv, nothing happens. I print "$VIRTUAL_ENV" and it's null. What should I do?
https://redd.it/1hj8oof
@r_bash
Need help understanding and altering a script
Hello folks,
I am looking for some help on what this part of a script is doing but also alter it to spit out a different output.
p=system_profiler SPHardwareDataType | awk '/Serial/ {print $4}' | tr '[A-Z]' '[K-ZA-J]' | tr 0-9 4-90-3 | base64
This is a part of an Intune macOS script that creates a temp admin account and makes a password using the serial number of the device. The problem I am having is that newer macbooks don't contain numbers in their serial! This is conflicting with our password policy that requires a password have atleast 2 numbers and 1 non-alphanumeric.
I understand everything up to the tr and base64. From what I've gathered online, the tr is translating the range of characters, uppercase A to Z and numbers 0 to 9 but I can't get my head around what they're translating to (K-ZA-J and 4-90-3). After this I'm assuming base64 converts the whole thing again to something else.
Any help and suggestions on how to create some numerics out of a character serial would be greatly appreciated.
https://redd.it/1hiiopc
@r_bash
Rate my Ubuntu debloater bash script
(I give you permission to steal it)
https://redd.it/1hhw6xe
@r_bash
any way I can improve this bash script that has double stow command?
stow doesn't delete. It can only throw error or use --adopt to overwrite MY REPO's files instead of overwriting computer files with dotfiles.
I know normal ln can overwrite destination files like this:
ln -sf ~/.dotfiles/alacritty ~/.config/alacritty
# this code clones repo, runs install script, cd's into that repo, uses stow to distribute files via stow.
# I need to repeat stow twice. First so that if files exist already, those files overwrite
# this git repo files, then I reset this repo and run stow again.
# all this because git stow can't overwrite files / directories if they are already present
git clone --recurse-submodules git@github.com:monoira/.dotfiles.git ~/.dotfiles &&
bash ~/.dotfiles/install_scripts/_install.sh &&
cd ~/.dotfiles &&
stow -v --adopt alacritty cmus git nvim sqlfluff tmux zsh &&
git add . && git reset --hard &&
stow -v --adopt alacritty cmus git nvim sqlfluff tmux zsh
Two different while loops
Is there a functional difference between these two while loops:
find /path/ -type f -name "file.pdf" | while read -r file; do
echo $file
done
while read -r file; do
echo $file
done < <(find /path/ -type f -name "file.pdf")
https://redd.it/1hh3kpt
@r_bash
Reflow-safe right-aligned text in terminal via bash?
For styling my PS1, I create a a separator line using ANSI escape codes to create a string of $COLUMNS spaces which is underlined in gray. A simplified form of this would be
PROMPT_COMMAND='PS1=$(printf "\[\033[4;37m%${COLUMNS}s\033[0m\]" " ")"\n\s-\v$ "'
https://preview.redd.it/gdv4df0m3d7e1.png?width=901&format=png&auto=webp&s=1a0d6b7860356d7b2b31dba3a384f3b15fc0c42d
However, this messes up the display when the screen contents get reflowed, e.g. switching from a maximized to a half-screen window. Then I get something awkward like this:
https://preview.redd.it/5dj8l8zh4d7e1.png?width=565&format=png&auto=webp&s=87b998dff60c1bb61c172d2884a3a54f577478b2
https://preview.redd.it/ev36rx2n4d7e1.png?width=901&format=png&auto=webp&s=715dac21d32ac06ef29c5fdd600dd46c09764712
Is it possible to instead genuinely *right-align* a text on the terminal, such that it remains at the right end even if *$COLUMNS* changes? Or, alternatively, is there a way to insert a horizontal line that self-resizes like *<hr>* in HTML?
https://redd.it/1hg5ouj
@r_bash
Stackabrix, a simple terminal game
https://redd.it/1hg79en
@r_bash
Is there a way to delete all files and reset via Bash?
I have a VPS that I can access only via ssh, is there a way to factory reset purely via ssh/bash? Thanks in advance!
https://redd.it/1heider
@r_bash
Apash Library
Hello World,
I would like to share with you a library written in shell script (bash/zsh): Apash
Apash provides a readable interface for performing simple operations available in shell script like in the other languages.
It is inspired by the Apache commons libraries.
This work leads me to render the interface compatible between shells like bash and zsh (for the moment).
It's relatively easy to contribute with your own snippets.
You can fully install it by following the procedure or just run a container ready to use:
docker run --rm docker.io/hastec/apash:0.2.0-ready 'StringUtils.upperCase "Do or do not, there is no try."'
# Download version for bash
curl "https://raw.githubusercontent.com/hastec-fr/apash/refs/tags/v0.2.0/bin/apash-bash-min.sh" -o apash-bash-min.sh
# Source
. ./apash-bash-min.sh
# Repeat the string
StringUtils.repeat 3 "Ho! "
# result: Ho! Ho! Ho!
Dev Wrap '24 - Spotify Wrapped for Dev's
https://devwrap.thesafezone.xyz
https://redd.it/1heksng
@r_bash
Inputing bash through a userLAnd terminal is going to make my head explode.
https://redd.it/1hdmspg
@r_bash
Help with UserLAnd terminal? Don't mind the face lol
https://redd.it/1hcqpa5
@r_bash
Proper terminal settings
I am writing a terminal emulator in go, for some reason when pressing enter on a prompt with no command (just the $ sign) bash doesn't send a \\n... is it up to my terminal to manage that?
Edit: after some more testing:
dev@arch:~ ls<output of command>\n
dev@arch:~
Help message annotations
I had an idea to automatically create help messages for commands inside of a bash script. I wrote a quick script for personal use and was wondering what other people thought.
#!/usr/bin/env bash
HELP_MESSAGE_SPACING=35
# Generates help message given a function name
__help() {
help=$(declare -f $1 | awk '
NR>2 {
if ( $1 != ":") {
exit 0
} else if ($2 == "@help" ) {
for(i = 3; i < NF; i++){
printf "%s ", $i
}
printf "%s ", substr($NF, 1, length($NF)-1)
}
}')
printf "%-${HELP_MESSAGE_SPACING}s %s\n" "$1" "$help"
}
# User defined functions start here
# -------------------------------
function command_1 {
: u/help Example help message here
echo "Command 1"
}
function command_2 {
: @help Example help message here
echo "Command 2"
}
# User defined functions end here
#---------------------------------
if [[ $# == 0 ]]; then
cmds=$(compgen -A function | sed /^__*/d)
__printf "\033[31mError! No Command Selected!\033[0m\nRun Script Using sudo -E $0 <cmd> [args]\n\n\033[32mCommands:\033[0m\n"
for cmd in ${cmds[@]}; do
__help $cmd
done
else
CMD=$1
shift
if [[ $(type -t $CMD) == "function" ]]; then
$CMD $@
else
__printf "\033[31m$CMD is not a valid command!\033[0m\n";
fi
fi
Then running the script directly will generate a summary of each user defined function and `<script> command_1 [additional args here]` will run the bash code inside command\_1
https://redd.it/1hc8d8w
@r_bash
trap inside or outside su subshell?
If I want to prevent Ctrl-C from interrupting the command I'm going to run in the terminal with su - -c
, should I do
su - -c 'trap "" INT; somecommand'
or
trap '' INT; su - -c 'somecommand'; trap - INT
Is there a difference in their functionality?
https://redd.it/1hb965x
@r_bash