r_bash – Telegram
Manage buckets

Hello,

I am building a small noscript to analyse the log of my online app and find IP's with a bad pattern to exclude them through a reverse-proxy or firewall rule. I have been successfull that far to identify the "bad IP's" but I would like to manage what I would call "time buckets" (apologies if this is not correct, English is not my mother tongue, neither is bash) before I exclude them. For instance, if an IP address appears 5 times in 1 minute, I exclude it.

This is what I started to write, but I meet problems I don't understand and can't get any further.

#!/bin/bash

CONTAINER='my_app'

TEMP_FILE='/home/eric/monitoring/temp'

LOG_FILE=$(docker inspect "$CONTAINER" | grep 'LogPath' | cut -d '"' -f4)

declare -A OCCUR
declare -A HOUR

tail -F "$LOG_FILE" | while read LINE; do
IP=$(echo "$LINE" | grep -Po "([0-9]{1,3}[\.]){3}[0-9]{1,3}" | head -n 1 | grepcidr -v '10.0.0.0/8' | grepcidr -v '127.0.0.0/8' | grepcidr -v '172.16.0.0/12' | grepcidr -v '192.168.0.0/16')
if [ -n "$IP" ]
then
if [ -z $OCCUR["$IP"] ]
then
OCCUR["$IP"]=0
fi
OCCUR["$IP"]=$(OCCUR["$IP"])+1
HOUR["$IP"]=$(date)
echo "$OCCUR[$IP]" " ; " "$HOUR[$IP]" >> "$TEMP_FILE"
fi
done

I get this "log" in return

./surveillance.sh: ligne 20: OCCUR[<suspect-ip-address>] : commande introuvable
./surveillance.sh: ligne 20: OCCUR[<suspect-ip-address>] : commande introuvable
./surveillance.sh: ligne 20: OCCUR[<suspect-ip-address>] : commande introuvable
./surveillance.sh: ligne 20: OCCUR[<suspect-ip-address>] : commande introuvable
./surveillance.sh: ligne 20: OCCUR[<suspect-ip-address>] : commande introuvable
./surveillance.sh: ligne 20: OCCUR[<suspect-ip-address>] : commande introuvable

And this temp file (my check)

[<suspect-ip-address>] ; [<suspect-ip-address>]
[<suspect-ip-address>] ; [<suspect-ip-address>]
[<suspect-ip-address>] ; [<suspect-ip-address>]
[<suspect-ip-address>] ; [<suspect-ip-address>]
[<suspect-ip-address>] ; [<suspect-ip-address>]

Any clue how I should go about that ?

https://redd.it/1hnjgbh
@r_bash
Do you prefer most of your bash functions to just do a thing, and then not mess with retuning something to a caller?

It seems like the easiest thing to do is to simply just not mess with trying to set some return value to be captured by the caller. yes, I see stuff like this. However, it appears that bash leans more toward getting something done instead of checking that it was in fact done. And seems like very few, in bash, create a bunch of functions that have an interdependency on each other. I.e. seems like it’s just easier to just do logging in functions and manually check that for execution correctness, if desired, for debug etc.

Anybody else feel this way? Am I off my rocker?

https://redd.it/1hmx02r
@r_bash
Color non-printing escape sequence in Bash prompt

Hello,

Rewriting my bash prompt and I realize I completely forgotten the minutae of how to handle ANSI escape sequences for colors within variables within functions within PS1. Here's what I have to start with (it doesn't work):

RED='\e[38;5;203m'
GREEN='\e[38;5;41m'
RESET='\e[0m'

function prompt_status() {
# Set prompt color
if [ $? -ne 0 ]; then
PROMPT_COLOR=$RED
else
PROMPT_COLOR=$GREEN
fi
}

PROMPT_COMMAND=prompt_status

PS1="$PROMPT_COLOR$ $RESET"


I've been going over the Bash manual again to review expansions, etc. But I'm stuck. I've tried curly-braces, the dollar sign infront of the single-quoted escape sequence, the \[ \] trick. None work. Does anyone have a good resource for learning about why this chunk of noscript doesn't work? And what is the recommended way to go about noscripting colors for prompts? I really want to set my colors in environment variables for readability and so that I can use matching colors across Bash, Zsh, Fish and Tmux.

Thanks

NOTE: (I'm running Bash version 5.2.37 on Terminal.app with xterm-256 enabled. Colors show up fine when I use printf or echo, but not for my PS1 variable)

https://redd.it/1hodpwh
@r_bash
I'm making bash fishing game and echos dont work correctly because of backslashes

echo " "
echo " |\ o"
echo " | \/|\"
echo "~~~|~~/\"
echo " | "
echo " ⤿ "

so how can i fix it
i just want to make backslashes display in echo


(btw sorry for my terrible english)

https://redd.it/1ho7y6s
@r_bash
-t 0 for testing terminal not working as expected

In window manager (Sway) I bind the following:

bindsym $mod+5 exec -t 0 && notify-send "run from terminal"

and it reports it runs from terminal even though it's running from a keybinding executing the command.

I'm also using this check and it's not working as expected when running the noscript from status bar calling the command to the noscript.

Why might this be the case? My attempt is to determine whether to run fzf (cli) or dmenu (gui-equivalent) depending on whether it's run from the terminal. Can this be done reliably?

https://redd.it/1hp5v2d
@r_bash
Happy 2025, everyone!

bash$ for i in {1..9}; do ((t+=i*i*i)); done ; echo $t     
2025


https://redd.it/1hqar9r
@r_bash
Is this a good .bashrc file? (Using android termux)

```#!/bin/bash
# Setup
ulimit -u 100 2>/dev/null || echo "Unable to set ulimit."

[ -z "$PS1" ] && return 2>/dev/null

# Vars
PROMPT_COMMAND='now=$(date +%s)'

# Make custom programms folder
mkdir -p $HOME/bin
[[ ":$PATH:" != *":$HOME/bin:"* ]] && export PATH="$PATH:$HOME/bin"

## Aliases
# Remapping
alias clear="clear; source $HOME/.bashrc"
alias bashrc="source $HOME/.bashrc"

# Quick access
alias la="ls -A"

# Permission management
alias enable="chmod +x"
alias disable="chmod -x"

# Full commands
alias cmdlist='printf "\033[7mBuilt-in Commands:\033[0m\n%s\n\n\033[7mExternal Commands:\033[0m\n%s\n" "$(compgen -b)" "$(echo $PATH | tr ":" "\n" | xargs -I {} ls -1 {} 2>/dev/null | sort -u)"'
alias termShare="( set; export; alias ) | sed 's/$/ 2>\/dev\/null/' | tee /dev/tty | termux-clipboard-set 2>/dev/null || printf '\n\033[7mPlease copy the text above.\n'; printf '\n\033[7mNow paste the copied text into the terminal to clone this one into.\033[0m\n'"


# ANSI color codes
reset="\033[0m" #reset
bold="\033[1m" #bold
rev="\033[7m" #invert
r="\033[31m" #red
g="\033[32m" #green
y="\033[33m" #yellow
b="\033[34m" #blue
m="\033[35m" #magenta
c="\033[36m" #cyan
w="\033[37m" #white

# Inital message
printf "${reset}${rev}

,-.
\ \
\ \
/ /,----.
/ / '----'
\`-'
${reset}\n"
printf "Welcome %s\n" "$(whoami 2>/dev/null || echo "?") (${HOSTNAME:-${HOST:-"unknown"}})"

unset reset bold rev r g y b m c w

https://redd.it/1hqefgg
@r_bash
Looking for a corpus of Bash noscripts

I'm looking for a large corpus of open source Bash noscripts; preferably longer noscripts, but that doesn't really matter.

At the moment, I've found:

The `tests` directory in the [Bash repository](https://savannah.gnu.org/git/?group=bash). This is quite large, but it contains a lot of funky stuff for teasing out edge cases:

$ find tests -name "*.tests" -o -name "*.sub" -exec wc -lc --total=only {} \+
19364 467878

[This repository](https://github.com/bensuperpc/noscripts), which was mentioned on this subreddit [about three years ago](https://old.reddit.com/r/bash/comments/ox3sry/collection_of_bash_noscripts/) and contains a lot of quite short, but more "normal" noscripts:

$ find . -name "*.sh" -exec wc -lc --total=only {} \+
12074 400232

The purpose of this is to stress-test formatting engines and to get an idea of throughput.

https://redd.it/1hqey6d
@r_bash
Noob to Bash—Having Trouble Restarting RMM Service via Script, Need Help"

Although I have a workaround, it's not ideal. The workaround is to force the computer to restart once the service stops, but it doesn't always work, and it’s not a reliable solution.

I’m running the bash noscript via an RMM tool where the noscript executes as root. The issue arises when using sudo through the terminal, as the noscript works fine there.

Here’s the command that works when run manually:

sudo launchctl bootout system /Library/LaunchDaemons/com.cenra.cag.plist
sudo launchctl bootstrap system /Library/LaunchDaemons/com.cenra.cag.plist


The challenging part is that the service I'm trying to restart is actually the RMM itself (yes, the RMM is broken, haha).

What I’ve tried so far is running a cron job and saving the noscript in the logged-in user's profile under /Library, then executing it. The noscript is able to bootout the service, but it fails to bootstrap it.

I’ve even attempted to pass temporary admin credentials through the noscript itself.

I know I might be overthinking this, as this is only my second bash noscript. Any help would be greatly appreciated!



https://redd.it/1hqvtxf
@r_bash
What is X11 related to Bash CLI?

Hi and happy new year there is a new tool github for put the keybindings of trydactyl and similars of vim for linux GUI tools browser, terminal etc but requires x11... I don't know about it....
I have bash in terminal....
what is x11?

https://redd.it/1hr3olj
@r_bash
Useful and fun Bash commands

Hi All,
I have created some fun BASH commands including alias

**🚀 Supercharge Your Terminal with These Bash Snippets!**

👋 Hey Reddit! I've packed this GitHub repo with **time-saving noscripts** and **fun terminal hacks** to level up your workflow! 🌟

🔗 **Check it out**: [BashSnippets on GitHub](https://github.com/ParasKoundal/BashSnippets)

# 💻 Highlights:

# 🔥 Git Tools:

* **Beautiful Git History**: Visualize your commits like a pro.
* **Quick Git Commit & Push**: Commit changes in seconds.
* **Auto-pull on** `cd`: Stay synced without thinking.
* **Git Repo Dashboard**: Summarize repo statuses in one command.

# 🎉 Fun Extras:

* **ASCII Art Greetings**: Start your terminal sessions in style!
* **Dynamic Emojis in Prompt**: Add a dash of randomness to your terminal.
* **Deadline Tracker**: Stay on top of projects with real-time updates.

# ⭐️ Show Some Love!

If you enjoy these tools:

1. **Star this repo** ⭐️ to keep me motivated.
2. **Follow me on GitHub** for updates and more cool stuff!

🛠️ **I'm adding new noscripts regularly**, so stay tuned!

https://redd.it/1hrbn86
@r_bash
Continuous deployment on LAN/local server upon 'git push' - using webhook & ngrok

Just finished a new bash noscript pforret/landeploy


It helps me setup a local webhook, make it public with ngrok and use it in Github/BitBucket to trigger a redeployment whenever I push a new version. I need this because we have a server at the office with a custom Windows software on it (that we can't run in the cloud), and I need the project to auto-update when we push changes to GitHub. The redeploy noscript runs under WSL.


It is a bash noscript based on the bashew micro framework.

https://redd.it/1hrdyvb
@r_bash
Pipe to background process

Hi!

I am trying to write a noscript which opens a connection with psql to PostgreSQL, then issue commands and get their response, multiple times synchronously, then close the background process.

I have got stuck at the part to spawn a background process and keep its stdin and stdout somehow accessible.

I tried this:
psql -U user ... >&5 <&4 &
PID=$!

# BEGIN - I would like to issue multiple of these
echo "SELECT now()" >&4
cat <&5
# END

# close psql
kill -SIGTERM $PID


Apparently this is not working as fd 4 and fd 5 does not exist.

Should I use mkfifo? I would like to not create any files. Is there a way to open a file denoscriptor without a file, or some other way to approach the problem perhaps?

I am trying to execute this noscript on Mac, so no procfs.

https://redd.it/1hsc6fw
@r_bash
How many lines is your bashrc file? Mine is currently 4712 and counting rapidly

I (like many others of you probably) have an addiction of trying to automate every single thing I do and creating bash noscripts for it. Every single tool i make, I put in my bashrc file. Over the course of just 4 months I have gathered 4712 lines of code

At some point it even got to the point where I had to split up the bashrc file in multiple files, and create some sort of framework to create 'composite' commands where i can have one main command and multiple sub-commands like 'profile load' 'profile save' 'profile list'. see example:

alias profile="profile_main_command"

# Composite command
profile_main_command() {
    reset_ifs

    composite_define_command "profile"
    composite_define_subcommand "list"
    composite_define_subcommand "current"
    composite_define_subcommand "load"
    composite_define_subcommand "save"
    composite_define_subcommand "edit"
    composite_define_subcommand "delete"

    composite_handle_subcommand $@
}

This will even automatically make a \`profile help\` command.

All of these tools and handy bash code, i have split up in several bash files, and then I use another bash noscript to combine all of these files together in one big bash file. which is my bashrc.

What about you guys?

https://redd.it/1hshm3u
@r_bash
Bash linting, formatting, etc. tools worth using?

I'm setting up Neovim and typically people set up tools like LSP servers, linting, formatting, etc. to aid in writing code.

Currently I use only use bashls and Neovim diagnostics that rely on shellcheck (still looking for a way for diagnostics to show the relevant code warnings like "SCXXXX" as virtual text so I don't have to manually search up the actual warning and potentially disable it).

Anyone use tools like beautysh, prettier, etc.? Are they as mature as similar tools in other languages? I would like to get a sense of perspective since I don't yet have experience with other "real" programming languages. E.g. maybe such tools aren't as useful for a shell noscripting language and/or the nature of a shell noscripting language is perhaps too opinionated that such tools don't help much.

Any recommendations for tools, however trivial, is much appreciated. I've never used an "industry-standard" code editor like VS Code or a real IDE, so don't know what I might be missing with a barebones Neovim setup.

https://redd.it/1hs0x7g
@r_bash
Newbie question regarding #comment within an array of multiple values.

Hello, I have the following code below:

ModEnabled="1" # If 1 = Install/update mods
GameModList="123123123 234234234 345345345"

if $ModEnabled == "1" ;then
printf " ${yellow}REALM-SERVER${default} Updating/Downloading Mod files!\n"
for value in $GameModList; do
${HOME}/servers/steamcmd/steamcmd.sh \
+forceinstalldir ${HOME}/servers/gameserver/ \
+login "${SteamUser}" \
+workshopdownloaditem 123123 "${value}" \
validate +quit
done

printf " ${green}REALM-SERVER${default} Done downloading and updating Mod files!\n"
else
printf " ${red}Error${default} You have not enabled downloading and updating mods, skipping!\n"
fi

However,

GameModList="123123123 234234234 345345345"

Is going to be extremely big soon. My question is basically:

Is it possible do something like this:

GameModList="
123123123 #Mod Denoscription 1
234234234 #Mod Denoscription 2
345345345 #Mod Denoscription 3
"

Basically, list each modID in a new line + adding a #comment?


Best regards, <3

https://redd.it/1hswaqd
@r_bash