r_bash – Telegram
Can you change the escape key in vi mode?

I want to use ctrl+c like I use in my editor to enter normal mode

https://redd.it/1h33g39
@r_bash
Escape $ to write literal placeholders

Hi,

Newbie here, apologies in advance if my question is not appropriate.

I have a bash noscript that installs some software, and I would like to generate a networkd-dispatcher noscript.

The networkd-dispatcher noscript should contain placeholders such as "$IFACE" and "$UNIT_NAME", but the installation noscript interprets them as undeclared variables, and the networkd-dispatcher noscripts ends up with empty spaces.

How can I escape these "$"?

This is what I have at the moment in the installation noscript:

createnetworkdnoscript() {
cat << EOF > $HOME/BirdNET-Pi/templates/50-birdweather-publication
#!/bin/bash
UNITNAME="birdweatherpublication@$IFACE.service"
# Check if the service is active and then start it
if systemctl is-active --quiet "$UNITNAME"; then
echo "
$UNITNAME is already running."
else
echo "Starting $UNITNAME..."
systemctl start "
$UNITNAME"
fi
EOF
chmod +x $HOME/BirdNET-Pi/templates/50-birdweather-publication
chown root:root $HOME/BirdNET-Pi/templates/50-birdweather-publication
ln -sf $HOME/BirdNET-Pi/templates/50-birdweather-publication /etc/networkd-dispatcher/routable.d
systemctl enable systemd-networkd
}

createnetworkdnoscript

https://redd.it/1h47zez
@r_bash
Advent of Code 2024 - Day 1 Problem 1 Solution in Bash

Hi, I have been learning Bash the last two days as my first noscripting language. I saw the advent of code started this year, and I thought why not try to solve it with Bash (since it's the only language I know so far." I managed to solve most of it by myself, had only to look for the sort command.

---

# Bash solution for day 1 problem 1

## Summary of the problem

- 2 Teams are searching for the locations where the Chief Historian might be.
- Each location has a 'location ID'.
- 2 Groups trying to make a complete list of 'location ID'.
- The two lists are not similar.
- Pair the smallest 'location ID' from the left with the smallest 'location ID' from the right
- Measure the distance (difference) between each 'location ID' pair.
- Measure the total aggregate distance between all 'location ID' pairs.

# inputs

A text file with the 2 lists is presented in the following format

18944   47230
94847 63037
93893 35622


## Steps to solution

1. Separate the numbers in the text file into two lists.
2. Order the numbers in each list from the smallest to the biggest.
3. Measure the distance between each 2 respective numbers.
4. Measure the total of distances.

## Solution

Save the numbers in a text file called input.txt"

#!/bin/bash

# Generate an array from the input
list=(`cat input.txt`)

# Save the even elements into list.left.txt and the odd elements into list.right.txt
for el in "${!list[@]}"
do
rem=$((${el} % 2))
if [[ rem -eq 0 ]]
then
echo "${list[$el]}" >> list.left.txt
else
echo "${list[$el]}" >> list.right.txt
fi
done

# Sorting the numbers
sort list.left.txt > list.left.sorted.txt
sort list.right.txt > list.right.sorted.txt

# create arrays from the two files
left=(`cat list.left.sorted.txt`)
right=(`cat list.right.sorted.txt`)

# calculate the difference and save it to a text file.
for ele in "${!left[@]}"
do
diff=$(("${left[$ele]}"-"${right[$ele]}"))
if [ $diff -ge 0 ]
then
echo "$diff" >> diffs.txt
else
diff=$(($diff * -1))
echo "$diff" >> diffs.txt
fi
done

# Import the differences as an array
di=(`cat diffs.txt`)

total=0

for elem in ${di[@]}
do
total=$(($total + $elem))
done
echo "$total"


https://redd.it/1h4t92n
@r_bash
Why this loop doesn't break the first time?

while read -r line
do
echo "$line"
done <file.txt


Here, the condition read -r line has nothing to read the first time the loop runs, why it doesn't break the first time?

https://redd.it/1h526bx
@r_bash
Move files from all subfolders to root folder but new filename should contain the folders

Hello,


i have a lot of folders containing files and more sobfolders with files. I want to have all that files in the root folder and the filename should contain the folder name. For example the file /testdir1/testdir2/testfile,txt should be in /testdir1_-_testdir2_-_testfile.txt

The thing is, some years ago i had done this by accident (i think i tried just to remove bad characters from filename but by accident also replaces the / but i can't get it together again :-( )



https://redd.it/1h5mrsi
@r_bash
Any way to hook into 'command not found' and run a noscript / function?

Curious if there's any way to hook into the error condition 'command not found' and run a noscript/function? Basically, I'd like to do something similar to "thefuck" but have it run automatically.

$ doesnotexist
-bash: doesnotexist: command not found

# how to (automatically) call some custom function/noscript/etc?
# preferably with access to bash history so I can run a
# fuzzy find with target command vs my defined aliases

So far my searches keep coming up with irrelevant stuff so I'm not sure if I'm just using bad search terms or if this is something that is just not possible under bash.

https://redd.it/1h65lkg
@r_bash
I made a bash noscript to exclude dropbox sync directories via command line

I code a lot in my dropbox folder to keep them synced across my devices (before git commits are viable) and unfortunately dropbox does not include an automatic way to exclude syncs. Took a while but with some guidance from claude 3.5 I hacked this together.

https://github.com/kavehtehrani/dropbox-exclude

https://redd.it/1h716kg
@r_bash
How to exclude a directory from find and rsync except for a few very specific files?

I'm struggling with nested include/exclude for find and rsync.

I want to find or rsync my dotfiles, except for the .mozilla folder (among some others). But I want the login data of firefox preserved. So far, I have

find -path '*/.*' -not -path '*/.cache/*' -not -path '*/.mozilla/*' -path '*/.mozilla/firefox/*.default-release/{autofill-profiles,signedInUser,prefs}.js*' > dotfiles

which gives back a blank file. How can I do this properly to exclude the majority of stuff from one directory, but still include these specific files?

I haven't yet tackled this for rsync (and maybe tar), but solutions for these are also welcome.

https://redd.it/1h75w8x
@r_bash
Need help passing argument with alias

Hi,

I want to make an alias with the word cheat. Ex. cheat topic

I tried making an alias but can't get it right. I presume because there is whitespace between the command and the argument.

alias cheat="curl cht.sh/$1"

How can I make this alias work so when I type cheat zip, and make curl cht.sh.zip the result?

Thanks.

https://redd.it/1h7p3vn
@r_bash
replacing placeholders in a file with variables from a noscript

Yeah, this noscript probably doesn't make sense so here I go...

I have a txt file with a bunch of html code that will make up a person's signature. In the txt file I have {{firstname}} {{lastname}} and {{email}}. In my bash noscript I have variables $firstname $lastname and $email. I want to write the txt file to a html file but replace the placeholders in the txt file with what the variables are.

https://redd.it/1h7li6n
@r_bash
Unexpected evaluatoin of "date +%M" in ~/.bashrc

I use the following command in an alias in my bashrc

$(date +%Y)/$(date +%M)/KW$(date +%V)-$(( $(date +%V) +2))

Why on earth does it evaluate to something like 2024/23/KW49-51 and an ever changing month? I cannot even figure out, what is the problem. Sometimes when sourcing the bashrc I get a new month, sometimes not. What is happening here?

https://redd.it/1h81d98
@r_bash
Exports block prev exports

I'm using zshell and my config exports are like that. But when i want to use lazygit or openvpn etc. it says '...not included path.' I add it with export or via config file but then I can't even use ls. Say's I have to add it to path It's in the path on .zshrc. Couldn't find solution pls help. Everything works fine in root terminal but it's not suitable i guess.

https://preview.redd.it/8qtx9l58495e1.png?width=817&format=png&auto=webp&s=3a0a8e4e448a86ccb451d407ffa769b21adbff99

https://preview.redd.it/cxqmojw0495e1.png?width=1346&format=png&auto=webp&s=5142078c29552f2707520a69cc505162c51d1983

https://redd.it/1h8576v
@r_bash
Which is better for capturing function output

Which is the better way to capture output from a function? Passing a variable name to a function and creating a reference with declare -n, or command substitution? What do you all prefer?

What I'm doing is calling a function which then queries an API which returns a json string. Which i then later parse. I have to do this with 4 different API endpoints to gather all the information i need. I like to keep related things stored in a dictionary. I'm sure I'm being pedantic but i can't decide between the two.

mydictjson="$(somefunc)"
vs.
some
func mydict

Is there that much of a performance hit with the subshell that spawns with command substitution?

https://redd.it/1h8cuhy
@r_bash
Append multiline at the begin

I have multiple lines from a grep command,. I put this lines in a variable. Ho can i append this lines at the begin of a file? I tried with sed but It don't work, i don't know because a multi lines.
Someone can help me please

https://redd.it/1h8fogz
@r_bash
Parse urls, print those not found

I have a list of urls in the forms:

https://abc.com/d341/en/ab/cd/ef/gh/cat-ifje-full
https://abc.com/defw/en/cat-don
https://abc.com/ens/cat-ifje
https://abc.com/dm29/dofne-don-partial
https://abc.com/ens/mew-feo
https://abc.com/ens/mew-feo-partial
https://def.com/fgew/dofne-don-full

The only thing that matters are abc.com urls (I don't care about URLs from other domains) and its last "field" of the url with the suffix -full and -partial being optional. When there are duplicates, prefer first the -full version, then the -partial version. In the above example, 1st and 3rd urls are duplicates and the 3rd url should be excluded from the list. 5th and 6th urls are the same and the 6th url should be excluded from the list.

Now the unique list of items are:

cat-ifje
cat-don
mew-feo
dofne-don


From this list, I apply a command likefind to search my filesystem to each item to see if I have a file containing this name of this item as a substring.

Now, how do I get back the original url if there are no results from find for the item? The output I'm looking for is:

https://abc.com/d341/en/ab/cd/ef/gh/cat-ifje-full
https://abc.com/defw/en/cat-don
https://abc.com/dm29/dofne-don-full
https://abc.com/ens/mew-feo-partial
https://abc.com/dm29/dofne-don-partial

I think working from my existing solution to "search the item not found" from the array of URLs would be in-efficient. I guess an associative array from the start can work?

I'm processing several hundreds of items, applying find to each. I've gotten up to the point where I have the list of items not found from the filesystem, so I only need to get back their original URLs.

Any solutions much appreciated. Can even be a single awk command.

https://redd.it/1h8jdoq
@r_bash
Environment variables in subshell

I have been trying to understand how env command works and have a question.

Is there any difference between

var=value somecommand
and
env var=value somecommand?

These both set the variable var for subshells and will not retain its value after somecommand finishes.

Can someone help me understand when and why env is useful. Thank you!

https://redd.it/1h9ha6s
@r_bash
Is there a way to know history of update?

Edited: noscript should say Uptime and not update

Hi, I'd like to get something like a uptime history...

for add time to use in last 2 days for check battery use...

I think batt is dead at 2 hours.

thanks and regards!

https://redd.it/1h9jhwe
@r_bash
Remove function issue Wireguard Server config

Hello all,

Not sure if this is the proper place for this but I am having an issue with a bash noscript I am trying to write on my Raspberry Pi. The purpose of the noscript is to be a fully automated Wireguard Server Manager. Upon defining the Home LAN subnet, WG Server IP, Wireguard port, and DNS IP. Your then shown a menu of 8 options. 1.) Add Client 2.) Remove Client 3.) List Clients 4.) Edit Configuration 5.) Display Server wg0.conf 6.) Clean up wg0 file 7.) Display QR code for client 8.) Clean up Orphaned Client Config.

I am having an issue with my option 2.) Remove Client. When I select option 2 to remove a selected client. It removes the client config file which is want I it to do. I also when selected option 2 I want it to remove the associated peer in the wg0.conf file but in the wg0.conf file it removes all of my peers. I for the life of me am struggling to figure out how to resolve this and its driving me nuts. So I am asking for help if it can be provided. I will paste my noscript below for reference.

#!/bin/bash # Unified logging function: Use log for all messages. # Log levels: # INFO - Informational messages # DEBUG - Debugging messages (enabled when DEBUG_MODE=true) # ERROR - Error messages (logged to stderr) set -e log() { local level="$1" local message="$2" local timestamp timestamp=$(date +"%Y-%m-%d %H:%M:%S") # Print directly to stdout/stderr case "$level" in INFO) echo -e "[${timestamp}] [INFO] $message" ;; DEBUG) if [[ "${DEBUG_MODE}" == true ]]; then echo -e "[${timestamp}] [DEBUG] $message" fi ;; ERROR) echo -e "[${timestamp}] [ERROR] $message" >&2 ;; *) echo -e "[${timestamp}] [UNKNOWN] $message" >&2 ;; esac } # Restrict file permissions for sensitive files umask 077 # Centralized Configuration and Defaults declare -A DEFAULTS=( ["dns"]="10.6.0.7" # Default DNS server (Pi-hole) ["port"]=51642 # Default WireGuard server port ["endpoint"]="testmachinevm.ddns.net" # Default endpoint address ["conf_dir"]="/etc/wireguard" # WireGuard configuration directory ["log_file"]="/var/log/wireguard_install.log" # WireGuard log file ) # Derived Paths DEFAULTS["device_config_dir"]="${DEFAULTS["conf_dir"]}/deviceconfigs" DEFAULTS["wg_conf_file"]="${DEFAULTS["conf_dir"]}/wg0.conf" # Enable Debug Mode (default is off; set DEBUG_MODE=true to enable detailed logs) DEBUG_MODE=${DEBUG_MODE:-false} # Function to log sensitive messages securely secure_log() { local MESSAGE="$1" logger -p authpriv.info "WireGuard Management: ${MESSAGE}" } # Function to conditionally log debug messages debug_log() { if [[ "${DEBUG_MODE}" == true ]]; then echo "DEBUG: $1" else secure_log "$1" fi } # Function to check for required dependencies check_dependencies() { local DEPENDENCIES=("micro" "qrencode" "fbi" "wg" "systemctl" "ss") local MISSING_DEPS=() local DEP_STATUS=() log INFO "Checking dependencies..." # Check dependencies in parallel for TOOL in "${DEPENDENCIES[@]}"; do { if ! command -v "$TOOL" &>/dev/null; then DEP_STATUS+=("$TOOL") fi } & done # Wait for all background checks to complete wait # Handle missing dependencies if [[ ${#DEP_STATUS[@]} -ne 0 ]]; then log ERROR "Missing dependencies: ${DEP_STATUS[*]}" log ERROR "Install missing dependencies and retry." exit 1 fi log INFO "All dependencies are installed." } # Call dependency check at the start of the noscript check_dependencies # Centralized configuration WG_CONF_DIR="${DEFAULTS["conf_dir"]}" WG_CONF_FILE="${DEFAULTS["wg_conf_file"]}" DEVICE_CONFIG_DIR="${DEFAULTS["device_config_dir"]}" DEFAULT_DNS="${DEFAULTS["dns"]}" DEFAULT_ENDPOINT="testmachinevm.ddns.net" DEFAULT_PORT=51642 # Default WireGuard port LOG_FILE="${DEFAULTS["log_file"]}" echo "DEBUG: LOG_FILE is set to '${LOG_FILE}'" #Validate Input validate() { local value="$1" local type="$2" local error_message="$3" case "$type" in ip) if ! [[ "$value" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}(/([0-9]|[1-2][0-9]|3[0-2]))?$ ]]; then echo "Error: ${error_message:-Invalid IP address format. Use CIDR notation (e.g., 10.100.0.1/24).}" return 1 fi ;; dns) if ! [[ "$value" =~