why is sleep not working properly?
echoing RANDOM works just fine
and so does sleep
why does it say sleep missing operand?
https://redd.it/1hri7i5
@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 scripts** 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 scripts regularly**, so stay tuned!
https://redd.it/1hrbn86
@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
Looking for a corpus of Bash scripts
I'm looking for a large corpus of open source Bash scripts; preferably longer scripts, 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/scripts), which was mentioned on this subreddit [about three years ago](https://old.reddit.com/r/bash/comments/ox3sry/collection_of_bash_scripts/) and contains a lot of quite short, but more "normal" scripts:
$ 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
Happy 2025, everyone!
bash$ for i in {1..9}; do ((t+=i*i*i)); done ; echo $t
2025
new to bash ,made a doom scrolling breaker over 4 days
https://preview.redd.it/fr7utt9flt9e1.png?width=949&format=png&auto=webp&s=ce7f0319961978574f41db669313e8da81a48e8e
https://preview.redd.it/sk6f4dwklt9e1.png?width=982&format=png&auto=webp&s=cc6952c112245898edf1104fe27ea867e2f9c76a
https://redd.it/1hp0i9r
@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
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
Time bucket
Hello,
I am building a small script 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/1hnjukf
@r_bash
how to exit script gracefully
**how to handle these exception in the bash script :**
* when pressing `ctrl + c` to exit the script it just exit the current running process in the script and move to next process. instead of exiting the entire script. how to handle it ??
* How should a script handle the situation when its terminal is closed while it is still running ??
* what is the best common code / function which should be present in every script to handle exception and graceful exiting of the scripting ??
if you wish you can also dump your exception handling code here
**feel free for any inside**
i would really appreciate your answer ; **thanks :-)**
https://redd.it/1hn07dy
@r_bash
Convert JSON array to bash array
Hi guys,
I am a linux noob and am trying to write a script to extract info from a mkv file using mkvmerge but am not able to convert the target json script to a bash array. I have tried a number of solutions from stack overflow but with no success.
here are some of my attempts
dir="/mnt/Anime/Series/KonoSuba/Season 2/[Nep_Blanc] KonoSuba II 10 .mkv"
*********************************************************************************
ARRAY_SIZE=$(mkvmerge -J "$dir" | jq '.tracks | length')
count=0
arr=()
while [ $count -lt $ARRAY_SIZE ];
do
arr+=($(mkvmerge -J "$dir" | jq '.tracks'[$count]))
((count++))
done
*********************************************************************************
readarray -t test_array < <(mkvmerge -J "$dir" | jq '.tracks')
for element in "${test_array[@]}";
do
echo "$element"
done
*********************************************************************************
array=($(mkvmerge -J "$dir" | jq '.tracks' | sed -e 's/^\[/(/' -e 's/\]$/)/'))
but the echo prints out lines instead of the specific objects.
Though now it is helpling me with my python, originally the project was to help me learn bash scripting. I would really like to have a bash implementation so any help overcoming this roadblock would be appreciated.
https://redd.it/1hm27y2
@r_bash
I give up bash.
There is a structured way to learn every stupid programming language but not bash. There are textbooks with exercises, leetcode like problem solving series. but not for bash. Maybe, it is because one is expected to copy paste stuffs while doing bash.
I've taken many many bash scripting courses, but fk those courses. Courses teach you nothing. What you want is a structured problem solving approach.
I want to build something. I can;t do it without chatgpt. Learning to build with chatgpt is like learning to fly before learning to walk.
I ask in forums, but they are similar lke chatgpt in the sense that they provide you solution. And believe me, nobody who has got solutions to their programming problems from forums has ever learnt programming by asking. Ask a few more and people think you're a spammer.
I am learning java and bash scripting/shell scripting since a year. I can can see visible progress in java where I have outgrown myself before year. But bash, oh fck. I can't tell the syntax of array looping without chatgpt/google. I've to look up google for even the minor of the things.
This is because I have got nothing to practice. I don't want to be a prompt master that copies stuffs from chatgpt or google. Copying isn't bad, but when you haven't even build a muscle memory to declare an array there is when things go south.
Should I even tell what I am trying to build in bash?
Let me go ahead.
I've a csv file with 2 columns separated by a comma.
U-DLCI,6
C/R,1
EA,1
L-DLCI,4
FECN,1
BECN,1
DE,
EA,1
Like this, now I want to go through them one by one.
U-DLCI is 6, so I allocate 6 unit of distance for it. And print U-DLCI inside it center justified.
C/R is 1, so I slloate 1 unit of distance for it and print C/R inside it.
EA is 1 so I do ....
Now, the sum of past three numbers was 8.
So, I jump to a new line.
Then L-DLCI is 4 so I print it in a 4 units of distance at the center.
and so on....
Had I learnt file handling in java, this is a no-brainer in java. But bash, ffck whtat is this? How can a language be so deceptive?
https://redd.it/1hla31k
@r_bash
Array lengths - this works but the traditional method doesn't
Any ideas? The first one works, The second one doesn't in a script, doing a test from the command prompt all is good. Its a simple list of numbers all <100 , array length < 10
len="$(echo "${nlist[@]}" | wc -w)" # Good
len="${#nlist@}" # Bad
https://redd.it/1hkn7gw
@r_bash
friends I am looking for this but if you know bash manager types similar to this, can you share it?
https://redd.it/1hk3jpb
@r_bash
Continuous deployment on LAN/local server upon 'git push' - using webhook & ngrok
Just finished a new bash script 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 script runs under WSL.
It is a bash script based on the bashew
micro framework.
https://redd.it/1hrdyvb
@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 script via an RMM tool where the script executes as root. The issue arises when using sudo through the terminal, as the script 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 script in the logged-in user's profile under /Library, then executing it. The script is able to bootout the service, but it fails to bootstrap it.
I’ve even attempted to pass temporary admin credentials through the script itself.
I know I might be overthinking this, as this is only my second bash script. Any help would be greatly appreciated!
https://redd.it/1hqvtxf
@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
-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 script from status bar calling the command to the script.
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
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"
\[
\]
trick. None work. Does anyone have a good resource for learning about why this chunk of script doesn't work? And what is the recommended way to go about scripting 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.printf
or echo
, but not for my PS1
variable)Manage buckets
Hello,
I am building a small script 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
Tuifoop, a terminal game in Bash
https://redd.it/1hn2md5
@r_bash
Tools to edit modified/createdAt infos about a file based on its name?
I have a bunch of files, and more or less their name can be categorized into these categories:
.trashed-1737661897-video20241213152336.mp4
.trashed-1737661969-IMG20241217205925.jpg
1675865719503..jpg
20190207063809.jpg
20200830202505
.jpg
FBIMG1574447155845.jpg
IMG-20190622-WA0006.jpg
IMG20200724114950442.jpg
VID20240623230607.mp4
ReactNative-snapshot-image8923079110072067694.png
Screenshot20241212082715Chrome.jpg
originalbadf21d1-5c56-43a1-b19a-82f5d43de9beIMG20220707155608.jpg
video20240720102400.mp4
The problem is that their "created at" or "modified at" date are set to today. Do you know any tools that might help me change their dates based on their name?
https://redd.it/1hm2z2r
@r_bash
Guys, which platform would you recommend me to learn bash scripting?
https://redd.it/1hlwlow
@r_bash
pure-bash-bible alternative?
Since pure-bash-bible Got archived, is there any viable alternative for it? I know bash but I don't remember every little thing like reversing an array.
I want to have bash cheatsheet.
https://redd.it/1hjvy3m
@r_bash
Multiple coprocs?
I have a use case where I have to execute several processes. For the most part, the processes will communicate with each other via CAN, or rather a virualized vcan0
.
But I also need to retain each process's stdin/out/err in the top-level management session, so I can see things each process is printing, and send commands to them outside of their normal command and control channel on vcan0
.
Just reading up on the coproc
command and thought it sounded perfect, but then I read what is essentially the last line in the entire bash man page:
There may be only one active coprocess at a time.
Huh? How's come? What's the best practice for juggling multiple simultaneously running programs with all I/O streams available in a way that's not going to drive me insane, if I can't use multiple coprocs?
https://redd.it/1hkven3
@r_bash
Grep question about dashes
Im pulling my hair out with this and could use some help. Im trying to match some strings with grep that contain a hyphen, but there are similar strings that dont contain a hyphen. Here is an example.
echo "test-case another-value foo" | grep -Eom 1 "test-case"
test-case
echo "test-case another-value foo" | grep -Eom 1 "test"
test
I dont want grep to return test, I only want it to return test-case. I also need to be able to grep for foo if needed.
https://redd.it/1hk9edb
@r_bash
XDG & ~/.bashrc
I created a file to be sourced by bashrc to organize directories and files after running xdg-ninja.
I'm just not sure it's fool proof. I was hoping that a more experienced user could comment.
This is a shortened version with only one example. (cargo)
\#! /usr/bin/env dash
\# shellcheck shell=dash
\# shellcheck enable=all
\#------------------------------------------------------------------------------|
\# xdg-ninja
\#------------------------------------------------------------------------------|
alias 'xdg-ninja'='xdg-ninja --skip-ok --skip-unsupported' ;
\#------------------------------------------------------------------------------|
\# XDG Base Directory specification:
\#------------------------------------------------------------------------------|
export XDG_CACHE_HOME="${HOME}/.cache" ;
export XDG_CONFIG_HOME="${HOME}/.config" ;
export XDG_DATA_HOME="${HOME}/.local/share" ;
export XDG_STATE_HOME="${HOME}/.local/state" ;
\#------------------------------------------------------------------------------|
\# xdgmv
\#------------------------------------------------------------------------------|
xdgmv () {
test "${#}" -ne '2' && return ; test -e "${1}" || return ;
if test -d "${2%/*}" ;
then
mv --backup='numbered' --force "${1}" "${2}" ;
else
mkdir -p "${2%/*}" &&
mv --backup='numbered' --force "${1}" "${2}" ;
fi ;
} ;
\#------------------------------------------------------------------------------|
\# [cargo\]: "${HOME}/.cargo"
\#------------------------------------------------------------------------------|
xdgmv "${HOME}/.cargo" "${XDG_DATA_HOME}/cargo" &&
export CARGO_HOME="${XDG_DATA_HOME}/cargo" ;
\#------------------------------------------------------------------------------|
\# unset function(s)
\#------------------------------------------------------------------------------|
unset xdgmv ;
\#------------------------------------------------------------------------------|
https://redd.it/1hjybbv
@r_bash