r_bash | Unsorted

Telegram-канал r_bash - r_bash

46

Credits: @r_channels & @reddit2telegram

Subscribe to a channel

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

Читать полностью…

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

Читать полностью…

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

Читать полностью…

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

Читать полностью…

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

Читать полностью…

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

Читать полностью…

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

Читать полностью…

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

Читать полностью…

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.

$ L
bashprofile 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
$ L
bashprofile analyze profile.txt
Top 4 cummulatively longest commands:
percent spent
us 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

Читать полностью…

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

Читать полностью…

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

Читать полностью…

r_bash

Cron Python Venv VPS issue

Hi guys,

0 0 * * * source $VENV_ACTIVATE && python $SCRIPT_PATH >> $LOG_FILE 2>&1


I am trying to run $SCRIPT_PATH, which requires to activate a Python’s Virtual Environment, at midnight UTC then redirect Std out and err into $LOG_FILE.

When I check systemctl status cron the cron is running like clockwork but the $LOG_FILE isn’t being overwritten.

“The cron is running like clockwork” but only the first part source $VENV_ACTIVATE is mentioned (in the status / log). If I remember correctly.

Everything works as planned when I manually run the cron’s command.

Running it on a VPS… The paths are absolute.

That’s the whole setup:


# 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


Got no error or whatever but I can’t really see if the program is running. It’s just that the log file isn’t being overwritten therefore I wonder if it’s running at all.

The python file is outputing prints and logs.

cron.service is enabled by systemctl.

The job is within crontab -l

I mean looks like it’s running.

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

Читать полностью…

r_bash

"${WG_CONF_FILE}" | less ;; 6) backup_config cleanup_wg0 ;; 7) show_qr_code ;; 8) backup_config cleanup_client_configs ;; 9) echo "Exiting WireGuard management." break ;; *) echo "Invalid option. Please try again." ;; esac done

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

Читать полностью…

r_bash

not found. Aborting." return fi # Retrieve the client's AllowedIPs and PublicKey dynamically local CLIENT_ALLOWED_IP CLIENT_ALLOWED_IP=$(grep -Po '(?<=Address = )[^\s]+' "${CLIENT_CONF_FILE}") local CLIENT_PUBLIC_KEY CLIENT_PUBLIC_KEY=$(grep -Po '(?<=PublicKey = )[^\s]+' "${CLIENT_CONF_FILE}") echo "DEBUG: Removing client '${CLIENT_NAME}' with IP: ${CLIENT_ALLOWED_IP} and PublicKey: ${CLIENT_PUBLIC_KEY}" # Escape any special characters in the PublicKey for sed local ESCAPED_PUBLIC_KEY ESCAPED_PUBLIC_KEY=$(printf '%s\n' "${CLIENT_PUBLIC_KEY}" | sed -e 's/[\/&]/\\&/g') # Remove the specific peer block from wg0.conf using the PublicKey if grep -q "PublicKey = ${CLIENT_PUBLIC_KEY}" "${WG_CONF_FILE}"; then sed -i "/\[Peer\]/,/^$/ { /PublicKey = ${ESCAPED_PUBLIC_KEY}/,/^$/ d }" "${WG_CONF_FILE}" echo "Peer with PublicKey ${CLIENT_PUBLIC_KEY} removed from wg0.conf." else echo "Warning: Peer with PublicKey ${CLIENT_PUBLIC_KEY} not found in wg0.conf." fi # Remove the client's configuration file rm -f "${CLIENT_CONF_FILE}" "${CLIENT_CONF_FILE}.png" echo "Client configuration files for '${CLIENT_NAME}' removed." # Restart WireGuard to apply changes echo "Restarting WireGuard service..." restart_wireguard echo "Client '${CLIENT_NAME}' removed successfully." } # Clean up wg0.conf by removing orphaned peers cleanup_wg0() { echo "------------------------------------" echo " Clean Up WireGuard Config " echo "------------------------------------" # Backup the current WireGuard configuration backup_config # Extract all public keys from wg0.conf local WG_PUBLIC_KEYS=($(grep -A 1 "\[Peer\]" "${WG_CONF_FILE}" | grep "PublicKey" | awk '{print $3}')) # Identify all existing public keys from client configuration files local EXISTING_CLIENT_KEYS=() for CLIENT_CONF in "${DEVICE_CONFIG_DIR}"/*.conf; do if [[ -f "${CLIENT_CONF}" ]]; then CLIENT_PUBLIC_KEY=$(grep "PublicKey" "${CLIENT_CONF}" | awk '{print $3}') EXISTING_CLIENT_KEYS+=("${CLIENT_PUBLIC_KEY}") fi done # Remove only orphaned peers from wg0.conf local CLEANED=false for WG_KEY in "${WG_PUBLIC_KEYS[@]}"; do if [[ ! " ${EXISTING_CLIENT_KEYS[*]} " =~ ${WG_KEY} ]]; then # Escape special characters in PublicKey for sed ESCAPED_KEY=$(echo "${WG_KEY}" | sed -e 's/[\/&]/\\&/g') echo "Removing orphaned peer with PublicKey: ${WG_KEY}" sed -i "/\[Peer\]/,/^$/ { /PublicKey = ${ESCAPED_KEY}/,/^$/ d }" "${WG_CONF_FILE}" CLEANED=true fi done # Remove leftover empty [Peer] blocks sed -i '/^\[Peer\]$/,/^$/d' "${WG_CONF_FILE}" if [[ "${CLEANED}" == true ]]; then echo "wg0.conf cleaned up successfully." else echo "No orphaned peers found in wg0.conf." fi # Restart WireGuard service restart_wireguard } # Clean up Client Configuration files cleanup_client_configs() { echo "------------------------------------" echo " Clean Up Orphaned Client Configs " echo "------------------------------------" # Backup the current configuration local BACKUP_FILE="/etc/wireguard/backup_$(date +%Y%m%d_%H%M%S).conf" cp "${WG_CONF_FILE}" "${BACKUP_FILE}" echo "Backup saved in ${BACKUP_FILE}." # Collect all PublicKeys from wg0.conf local WG_PUBLIC_KEYS=($(grep -Po '(?<=PublicKey = )[^\s]+' "${WG_CONF_FILE}")) echo "DEBUG: PublicKeys in wg0.conf: ${WG_PUBLIC_KEYS[*]}" # Collect all PublicKeys from client config files local CLIENT_PUBLIC_KEYS=() for CLIENT_FILE in "${DEVICE_CONFIG_DIR}"/*.conf; do if [[ -f "${CLIENT_FILE}" ]]; then CLIENT_PUBLIC_KEYS+=($(grep -Po '(?<=PublicKey = )[^\s]+' "${CLIENT_FILE}")) fi done echo "DEBUG: PublicKeys in client configs: ${CLIENT_PUBLIC_KEYS[*]}" # Identify orphaned peers in wg0.conf echo "Checking for orphaned peers in wg0.conf..." for WG_KEY in "${WG_PUBLIC_KEYS[@]}"; do if [[ ! " ${CLIENT_PUBLIC_KEYS[*]} " =~ " ${WG_KEY} " ]]; then echo "Orphaned peer detected with PublicKey: ${WG_KEY}" sed -i -e "/\[Peer\]/,/^$/ { /PublicKey = ${WG_KEY}/d; }" "${WG_CONF_FILE}" || { echo "Failed to remove peer with PublicKey: ${WG_KEY} from wg0.conf." } echo "Removed orphaned peer with PublicKey: ${WG_KEY} from wg0.conf." fi done # Identify orphaned client configuration files echo "Checking for orphaned

Читать полностью…

r_bash

Directory: ${DEFAULTS["device_config_dir"]}" echo "Log File: ${LOG_FILE}" echo "------------------------------------" } validate_wg0_consistency() { echo "Validating WireGuard configuration consistency..." # Extract public keys from wg0.conf local WG_PUBLIC_KEYS=($(grep -A 1 "\[Peer\]" "${WG_CONF_FILE}" | grep "PublicKey" | awk '{print $3}')) # Extract public keys from client configuration files local CLIENT_PUBLIC_KEYS=() for CLIENT_CONF in "${DEVICE_CONFIG_DIR}"/*.conf; do if [[ -f "${CLIENT_CONF}" ]]; then CLIENT_PUBLIC_KEYS+=("$(grep "PublicKey" "${CLIENT_CONF}" | awk '{print $3}')") fi done # Check for mismatches local MISMATCH=false for CLIENT_KEY in "${CLIENT_PUBLIC_KEYS[@]}"; do if [[ ! " ${WG_PUBLIC_KEYS[*]} " =~ ${CLIENT_KEY} ]]; then echo "Warning: PublicKey ${CLIENT_KEY} from client config is missing in wg0.conf." MISMATCH=true fi done for WG_KEY in "${WG_PUBLIC_KEYS[@]}"; do if [[ ! " ${CLIENT_PUBLIC_KEYS[*]} " =~ ${WG_KEY} ]]; then echo "Warning: PublicKey ${WG_KEY} from wg0.conf is missing in client configs." MISMATCH=true fi done if [[ "${MISMATCH}" == true ]]; then echo "Inconsistencies detected. Do you want to clean up orphaned peers? (y/n)" read -r CLEANUP_CHOICE if [[ "${CLEANUP_CHOICE}" == "y" ]]; then cleanup_wg0 fi else echo "WireGuard configuration is consistent." fi } # Backup existing configuration backup_config() { BACKUP_DIR="${WG_CONF_DIR}/backup_$(date +%Y%m%d_%H%M%S)" mkdir -p "${BACKUP_DIR}" cp "${WG_CONF_FILE}" "${BACKUP_DIR}/" 2>/dev/null || true echo "Backup saved in ${BACKUP_DIR}." } # Restart WireGuard with logging restart_wireguard() { log INFO "Restarting WireGuard service..." systemctl restart wg-quick@wg0 if ! systemctl is-active --quiet wg-quick@wg0; then echo "Error: WireGuard failed to restart. Check logs for details." exit 1 fi echo "WireGuard restarted successfully." } # Generate unique client IP generate_unique_client_ip() { while true; do # Generate a random valid IP in the subnet CLIENT_IP="${SUBNET_PREFIX%.*}.$(shuf -i 2-254 -n 1)/32" # Debugging: Output generated CLIENT_IP echo "DEBUG: Trying CLIENT_IP=${CLIENT_IP}" >&2 # Ensure the IP is not already in the configuration if [[ -n "${CLIENT_IP}" && -n "${WG_CONF_FILE}" ]] && ! grep -q "${CLIENT_IP%/*}" "${WG_CONF_FILE}"; then echo "${CLIENT_IP}" return fi done } # Display QR Code display_qr_code() { local CLIENT_CONF_FILE=$1 local QR_CODE_FILE="${CLIENT_CONF_FILE}.png" if command -v fbi &>/dev/null; then echo "Displaying QR code for configuration..." fbi -a "${QR_CODE_FILE}" 2>/dev/null elif command -v img2txt &>/dev/null; then echo "Displaying QR code as ASCII art..." img2txt "${QR_CODE_FILE}" --width=40 else echo "No compatible QR code viewer found. You can view the QR code file at: ${QR_CODE_FILE}" fi } # Validate Client Name validate_client_name() { local CLIENT_NAME=$1 # Ensure the client name only contains valid characters if ! validate "$CLIENT_NAME" "client-name" "Client name can only contain letters, numbers, dashes, and underscores."; then exit 1 fi # Check if the client name already exists in the configuration if grep -qi "$CLIENT_NAME" "${WG_CONF_FILE}"; then echo "Error: Client name '$CLIENT_NAME' already exists. Choose a unique name." exit 1 fi } validate_peers() { local WG_PUBLIC_KEYS=($(grep -A 1 "\[Peer\]" "${WG_CONF_FILE}" | grep "PublicKey" | awk '{print $3}')) local CLIENT_KEYS=() for CLIENT_CONF in "${DEVICE_CONFIG_DIR}"/*.conf; do if [[ -f "${CLIENT_CONF}" ]]; then CLIENT_KEYS+=("$(grep "PublicKey" "${CLIENT_CONF}" | awk '{print $3}')") fi done echo "Validating peer entries in wg0.conf..." for WG_KEY in "${WG_PUBLIC_KEYS[@]}"; do if [[ ! " ${CLIENT_KEYS[*]} " =~ ${WG_KEY} ]]; then echo "Orphaned peer detected: ${WG_KEY}" fi done } # Add a client # Add a client add_client() { local CLIENT_NAME=$1 local TUNNEL_MODE=$2 validate_client_name "${CLIENT_NAME}" validate_tunnel_mode "${TUNNEL_MODE}" log DEBUG "Tunnel mode validated as ${TUNNEL_MODE}" # Function to ensure the PublicKey is unique ensure_unique_public_key() { local GENERATED_KEY=$1 # Check wg0.conf for the PublicKey if grep -q "PublicKey =

Читать полностью…

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


but I want to use stow. Current config works decently well but I was wondering if I can replace 2 stow lines with 1?

# 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


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

Читать полностью…

r_bash

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

Читать полностью…

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&amp;format=png&amp;auto=webp&amp;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&amp;format=png&amp;auto=webp&amp;s=87b998dff60c1bb61c172d2884a3a54f577478b2

https://preview.redd.it/ev36rx2n4d7e1.png?width=901&amp;format=png&amp;auto=webp&amp;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

Читать полностью…

r_bash

Stackabrix, a simple terminal game
https://redd.it/1hg79en
@r_bash

Читать полностью…

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

Читать полностью…

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."'


Alternatively, you can use a minified version (just source and forget):
# 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!


Apash currently includes around 100 methods covering a range of common operations.
I wish that Apash could one day help at least another person around the world.
And if you like it, consider giving it a star, it could help me too.

Depending on your feedbacks, I will continue (or not) to render it compatible with ksh family.

Thank you for all the help you provide there and Happy end of the year !!

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

Читать полностью…

r_bash

Dev Wrap '24 - Spotify Wrapped for Dev's
https://devwrap.thesafezone.xyz

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

Читать полностью…

r_bash

Inputing bash through a userLAnd terminal is going to make my head explode.
https://redd.it/1hdmspg
@r_bash

Читать полностью…

r_bash

Help with UserLAnd terminal? Don't mind the face lol
https://redd.it/1hcqpa5
@r_bash

Читать полностью…

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:~

even after typing a command, bash doesn't send a \\n
Edit 2: after even more testing, this happens on every value for $TERM except dumb. If $TERM=dumb bash sends \\n

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

Читать полностью…

r_bash

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

Читать полностью…

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 'some
command'; trap - INT

Is there a difference in their functionality?

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

Читать полностью…

r_bash

client configurations..." for CLIENT_FILE in "${DEVICE_CONFIG_DIR}"/*.conf; do local CLIENT_KEY=$(grep -Po '(?<=PublicKey = )[^\s]+' "${CLIENT_FILE}") if [[ ! " ${WG_PUBLIC_KEYS[*]} " =~ " ${CLIENT_KEY} " ]]; then echo "Orphaned client configuration detected: ${CLIENT_FILE}" rm -f "${CLIENT_FILE}" "${CLIENT_FILE}.png" echo "Removed orphaned client configuration: ${CLIENT_FILE}" fi done echo "Orphaned client configurations cleanup completed." } # Show QR Code for a client show_qr_code() { echo "------------------------------------" echo " Display QR Code for Client " echo "------------------------------------" # Get the list of available clients local CLIENTS=($(ls -1 "${DEVICE_CONFIG_DIR}" 2>/dev/null | sed 's/.conf$//')) if [[ ${#CLIENTS[@]} -eq 0 ]]; then echo "No clients available." return fi # Display the list of clients echo "Available Clients:" for i in "${!CLIENTS[@]}"; do echo "$((i + 1)). ${CLIENTS[$i]}" done # Prompt user to select a client read -p "Enter the number of the client to display QR code for: " CLIENT_INDEX if [[ ! "$CLIENT_INDEX" =~ ^[0-9]+$ ]] || (( CLIENT_INDEX < 1 || CLIENT_INDEX > ${#CLIENTS[@]} )); then echo "Invalid selection. Aborting." return fi # Identify the client configuration file local CLIENT_NAME="${CLIENTS[$((CLIENT_INDEX - 1))]}" local CLIENT_CONF_FILE="${DEVICE_CONFIG_DIR}/${CLIENT_NAME}.conf" if [[ ! -f "${CLIENT_CONF_FILE}" ]]; then echo "Error: Configuration file for '${CLIENT_NAME}' not found." return fi # Generate and display the QR code if command -v qrencode &>/dev/null; then qrencode -t ANSIUTF8 < "${CLIENT_CONF_FILE}" else echo "Error: 'qrencode' is not installed. Install it to display QR codes." fi } # Function to edit configurations edit_configuration() { echo "------------------------------------" echo " Edit Configuration " echo "------------------------------------" echo "1. Edit Server Configuration (wg0.conf)" echo "2. Edit a Client Configuration" read -p "Choose an option: " EDIT_OPTION case $EDIT_OPTION in 1) echo "Opening server configuration in micro..." micro "${WG_CONF_FILE}" ;; 2) echo "Available Clients:" local CLIENTS=($(ls -1 "${DEVICE_CONFIG_DIR}" 2>/dev/null | sed 's/.conf$//')) if [[ ${#CLIENTS[@]} -eq 0 ]]; then echo "No clients available to edit." return fi for i in "${!CLIENTS[@]}"; do echo "$((i + 1)). ${CLIENTS[$i]}" done read -p "Enter the number of the client to edit: " CLIENT_INDEX if [[ ! "$CLIENT_INDEX" =~ ^[0-9]+$ ]] || (( CLIENT_INDEX < 1 || CLIENT_INDEX > ${#CLIENTS[@]} )); then echo "Invalid selection. Aborting." return fi local CLIENT_NAME="${CLIENTS[$((CLIENT_INDEX - 1))]}" local CLIENT_CONF_FILE="${DEVICE_CONFIG_DIR}/${CLIENT_NAME}.conf" if [[ -f "${CLIENT_CONF_FILE}" ]]; then echo "Opening client configuration for '${CLIENT_NAME}' in micro..." micro "${CLIENT_CONF_FILE}" else echo "Error: Configuration file for '${CLIENT_NAME}' not found." fi ;; *) echo "Invalid option. Returning to main menu." ;; esac } # List clients list_clients() { echo "------------------------------------" echo " Configured Clients " echo "------------------------------------" local CLIENTS=($(ls -1 "${DEVICE_CONFIG_DIR}" 2>/dev/null | sed 's/.conf$//')) if [[ ${#CLIENTS[@]} -eq 0 ]]; then echo "No clients configured." return fi for i in "${!CLIENTS[@]}"; do echo "$((i + 1)). ${CLIENTS[$i]}" done } # Main menu while true; do echo "------------------------------------" echo " WireGuard Management " echo "------------------------------------" echo "1. Add Client" echo "2. Remove Client" echo "3. List Clients" echo "4. Edit Configuration" echo "5. Display Server Configuration" echo "6. Clean Up wg0.conf" echo "7. Show QR Code for Client" echo "8. Clean Up Orphaned Client Configs" echo "9. Exit" echo "------------------------------------" read -p "Choose an option: " OPTION case $OPTION in 1) read -p "Enter client name: " CLIENT_NAME read -p "Tunnel mode (full/split): " TUNNEL_MODE backup_config add_client "${CLIENT_NAME}" "${TUNNEL_MODE}" ;; 2) backup_config remove_client ;; 3) list_clients ;; 4) edit_configuration ;; 5) echo "Displaying server configuration..." cat

Читать полностью…

r_bash

${GENERATED_KEY}" "${WG_CONF_FILE}"; then return 1 fi # Check existing client configs for the PublicKey for CLIENT_FILE in "${DEVICE_CONFIG_DIR}"/*.conf; do if [[ -f "${CLIENT_FILE}" ]] && grep -q "PublicKey = ${GENERATED_KEY}" "${CLIENT_FILE}"; then return 1 fi done return 0 } # Securely generate unique keys local CLIENT_PRIVATE_KEY local CLIENT_PUBLIC_KEY while true; do # Securely create temporary files local CLIENT_PRIVATE_KEY_FILE local CLIENT_PUBLIC_KEY_FILE CLIENT_PRIVATE_KEY_FILE=$(mktemp -p /tmp client_privatekey_XXXXXX) CLIENT_PUBLIC_KEY_FILE=$(mktemp -p /tmp client_publickey_XXXXXX) # Generate the keys wg genkey > "${CLIENT_PRIVATE_KEY_FILE}" wg pubkey < "${CLIENT_PRIVATE_KEY_FILE}" > "${CLIENT_PUBLIC_KEY_FILE}" # Read keys into variables CLIENT_PRIVATE_KEY=$(<"${CLIENT_PRIVATE_KEY_FILE}") CLIENT_PUBLIC_KEY=$(<"${CLIENT_PUBLIC_KEY_FILE}") # Clean up temporary files securely shred -u "${CLIENT_PRIVATE_KEY_FILE}" "${CLIENT_PUBLIC_KEY_FILE}" # Ensure the PublicKey is unique if ensure_unique_public_key "${CLIENT_PUBLIC_KEY}"; then break else log ERROR "Duplicate PublicKey detected. Regenerating keys..." fi done log INFO "Generated secure keys for client '${CLIENT_NAME}'" log DEBUG "PublicKey: ${CLIENT_PUBLIC_KEY}" # Get the server's public key SERVER_PUBLIC_KEY=$(wg show wg0 public-key) if [[ -z "${SERVER_PUBLIC_KEY}" ]]; then log ERROR "Unable to retrieve the server's public key." exit 1 fi log DEBUG "Server public key retrieved." # Generate a unique IP for the client log INFO "Adding client '${CLIENT_NAME}' with tunnel mode '${TUNNEL_MODE}'" CLIENT_IP=$(generate_unique_client_ip) if [[ -z "${CLIENT_IP}" ]]; then log ERROR "Failed to generate a unique IP for the client." exit 1 fi log DEBUG "Generated Client IP: ${CLIENT_IP}" # Define AllowedIPs based on tunnel mode if [[ "${TUNNEL_MODE}" == "full" ]]; then CLIENT_ALLOWED_IPS="0.0.0.0/0,::/0" else CLIENT_ALLOWED_IPS="${FULL_SUBNET},${HOME_LAN_SUBNET}" fi log DEBUG "Allowed IPs set to ${CLIENT_ALLOWED_IPS}" # Create the client configuration CLIENT_CONF_FILE="${DEVICE_CONFIG_DIR}/${CLIENT_NAME}.conf" cat <<EOF >"${CLIENT_CONF_FILE}" [Interface] PrivateKey = ${CLIENT_PRIVATE_KEY} Address = ${CLIENT_IP} DNS = ${DEFAULT_DNS} [Peer] PublicKey = ${SERVER_PUBLIC_KEY} Endpoint = ${DEFAULT_ENDPOINT}:${SERVER_PORT} AllowedIPs = ${CLIENT_ALLOWED_IPS} EOF log INFO "Client configuration saved: ${CLIENT_CONF_FILE}" # Add the client to wg0.conf { echo "[Peer]" echo "PublicKey = ${CLIENT_PUBLIC_KEY}" echo "AllowedIPs = ${CLIENT_IP}" } >>"${WG_CONF_FILE}" log INFO "Client ${CLIENT_NAME} added to WireGuard configuration." # Restart WireGuard restart_wireguard } # Secure Log File setup_log_rotation() { cat <<EOF > /etc/logrotate.d/wireguard ${LOG_FILE} { daily rotate 7 compress missingok notifempty create 600 root root } EOF echo "Log rotation configured." } # Restrict log file permissions chmod 600 "${LOG_FILE}" # List clients list_clients() { echo "Configured Clients:" grep -A 2 "\[Peer\]" "${WG_CONF_FILE}" | awk ' /PublicKey/ {public_key=$3} /AllowedIPs/ {allowed_ips=$3; print "Client Public Key: " public_key "\nAllowed IPs: " allowed_ips "\n"} ' } # Remove a client remove_client() { echo "------------------------------------" echo " Remove WireGuard Client " echo "------------------------------------" # List available clients local CLIENTS=($(ls -1 "${DEVICE_CONFIG_DIR}" 2>/dev/null | sed 's/.conf$//')) if [[ ${#CLIENTS[@]} -eq 0 ]]; then echo "No clients available to remove." return fi echo "Available Clients:" for i in "${!CLIENTS[@]}"; do echo "$((i + 1)). ${CLIENTS[$i]}" done # Prompt for client selection read -p "Enter the number of the client to remove: " CLIENT_INDEX if [[ ! "$CLIENT_INDEX" =~ ^[0-9]+$ ]] || (( CLIENT_INDEX < 1 || CLIENT_INDEX > ${#CLIENTS[@]} )); then echo "Invalid selection. Aborting." return fi local CLIENT_NAME="${CLIENTS[$((CLIENT_INDEX - 1))]}" local CLIENT_CONF_FILE="${DEVICE_CONFIG_DIR}/${CLIENT_NAME}.conf" # Ensure the client configuration file exists if [[ ! -f "${CLIENT_CONF_FILE}" ]]; then echo "Error: Configuration file for '${CLIENT_NAME}'

Читать полностью…

r_bash

^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then echo "Error: ${error_message:-Invalid DNS format. Use a valid IP (e.g., 10.6.0.7).}" return 1 fi ;; port) if ! [[ "$value" =~ ^[0-9]+$ ]] || (( value < 1 || value > 65535 )); then echo "Error: ${error_message:-Invalid port. Use a number between 1 and 65535.}" return 1 fi ;; client-name) if ! [[ "$value" =~ ^[a-zA-Z0-9_-]+$ ]]; then echo "Error: ${error_message:-Client name can only include letters, numbers, dashes, and underscores.}" return 1 fi ;; *) echo "Error: Unknown validation type '$type'." return 1 ;; esac return 0 } # Prompt for user inputs and validate read -p "Enter your home LAN subnet (default: 10.6.0.0/24): " INPUT_HOME_LAN_SUBNET HOME_LAN_SUBNET="${INPUT_HOME_LAN_SUBNET:-10.6.0.0/24}" read -p "Enter WireGuard Server IP (e.g., 10.100.0.1/24): " INPUT_SERVER_IP SERVER_IP="${INPUT_SERVER_IP:-10.100.0.1/24}" read -p "Enter WireGuard port (default: 51642): " INPUT_SERVER_PORT SERVER_PORT="${INPUT_SERVER_PORT:-51642}" read -p "Enter Pi-hole DNS IP (default: 10.6.0.7): " INPUT_DNS DEFAULT_DNS="${INPUT_DNS:-10.6.0.7}" # Derived values SUBNET="${SERVER_IP##*/}" # Extract the CIDR part (e.g., 24) SUBNET_PREFIX="${SERVER_IP%/*}" # Extract the IP prefix (e.g., 10.100.0.1) FULL_SUBNET="${SUBNET_PREFIX%.*}.0/${SUBNET}" # Build full subnet (e.g., 10.100.0.0/24) #Validate Tunnel Mode validate_tunnel_mode() { local MODE=$1 if [[ "${MODE}" != "full" && "${MODE}" != "split" ]]; then echo "Error: Invalid tunnel mode. Choose 'full' or 'split'." exit 1 fi } # Validate Inputs if ! validate "$SERVER_IP" "ip" "Invalid IP address format. Use CIDR notation (e.g., 10.100.0.1/24)."; then exit 1 fi if ! validate "$HOME_LAN_SUBNET" "ip" "Invalid subnet format. Use CIDR notation (e.g., 10.6.0.0/24)."; then exit 1 fi if ! validate "$SERVER_PORT" "port" "Invalid port number. Use a value between 1 and 65535."; then exit 1 fi if ! validate "$DEFAULT_DNS" "dns" "Invalid DNS IP address format. Use standard IP format (e.g., 10.6.0.7)."; then exit 1 fi # Enable logging exec > >(tee -a "${LOG_FILE}") 2>&1 # Error trap and cleanup trap 'echo "An error occurred. Cleaning up..."; rm -f "${WG_CONF_DIR}/server_privatekey"; exit 1' ERR # Debugging output echo "DEBUG: SERVER_IP=${SERVER_IP}, SUBNET=${SUBNET}, SUBNET_PREFIX=${SUBNET_PREFIX}, FULL_SUBNET=${FULL_SUBNET}" # Validate IP address format validate_ip() { if ! [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]+$ ]]; then echo "Error: Invalid IP address format. Use CIDR notation (e.g., 10.100.0.1/24)." exit 1 fi } validate_ip "${SERVER_IP}" # Check for route conflicts check_route_conflict() { if ip route | grep -q "${FULL_SUBNET}"; then echo "Warning: ${FULL_SUBNET} conflicts with an existing route." read -p "Do you want to continue anyway? (y/n): " CONTINUE if [[ "${CONTINUE}" != "y" ]]; then echo "Aborting due to route conflict." exit 1 fi fi } check_route_conflict # Validate Pi-hole DNS IP format (simple IP address validation) validate_dns_ip() { if ! [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then echo "Invalid IP address format for DNS. Use a standard IP format (e.g., 10.6.0.7)." exit 1 fi } validate_dns_ip "${DEFAULT_DNS}" # Validate port availability validate_port() { if ss -tuln | grep -q ":${SERVER_PORT}"; then if wg show wg0 | grep -q "listening port: ${SERVER_PORT}"; then echo "WireGuard is already using port ${SERVER_PORT}. Restarting service." systemctl restart wg-quick@wg0 else echo "Port ${SERVER_PORT} is in use by another process. Resolve the conflict before proceeding." exit 1 fi fi } # Log rotation setup setup_log_rotation() { cat <<EOF > /etc/logrotate.d/wireguard ${LOG_FILE} { daily rotate 7 compress missingok notifempty } EOF echo "Log rotation configured." } setup_log_rotation # Display server configuration display_server_config() { echo "------------------------------------" echo "WireGuard Server Configuration:" echo "------------------------------------" echo "Server IP: ${SERVER_IP}" echo "Server Port: ${SERVER_PORT}" echo "Pi-hole DNS: ${DEFAULT_DNS}" echo "Configuration File: ${DEFAULTS["wg_conf_file"]}" echo "Device Configurations

Читать полностью…
Subscribe to a channel