r_bash – Telegram
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 =
${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}'
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
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
"${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
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
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 noscript 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
Help message annotations

I had an idea to automatically create help messages for commands inside of a bash noscript. I wrote a quick noscript 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 noscript directly will generate a summary of each user defined function and `<noscript> command_1 [additional args here]` will run the bash code inside command\_1

https://redd.it/1hc8d8w
@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 noscript 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 noscripting 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
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
Is this example valid?

I found an example in a Bash noscripting 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
Help with UserLAnd terminal? Don't mind the face lol
https://redd.it/1hcqpa5
@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 noscripts, 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
Inputing bash through a userLAnd terminal is going to make my head explode.
https://redd.it/1hdmspg
@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 noscript 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
made my first (actually) bash noscript for first time

I written little bash noscripts 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 noscript compare two different command with time command, with nice UI

preview

please tell me if you find something missing in the noscript 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
Apash Library

Hello World,

I would like to share with you a library written in shell noscript (bash/zsh): Apash
Apash provides a readable interface for performing simple operations available in shell noscript 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
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
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
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 noscripts, etc.

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