r_bash – Telegram
Seeking Feedback on My Bash Script for Migrating APT Keys

Hello everyone!

I recently created a Bash noscript designed to help migrate APT keys from the deprecated apt-key to the new best practices in Ubuntu. The noscript includes user confirmation before each step, ensuring that users have control over the process. I developed this noscript using DuckDuckGo's AI tool, which helped me refine my approach.

# What This Script Does:

It exports existing APT keys to the `/etc/apt/trusted.gpg.d/` directory.
It verifies that the keys have been successfully exported.
It removes the old keys from `apt-key`.
It updates the APT package lists.

# Why I Want This:

As Ubuntu continues to evolve, it's important to keep our systems secure and up to date. Migrating to the new key management practices is essential for maintaining the integrity of package installations and updates.

# Questions for the Community:

1. Is this noscript safe to use? I want to ensure that it won't cause any issues with my system or package management.
2. Will this noscript work as is? I would appreciate any feedback on its functionality or any improvements that could be made.

Here’s the noscript for your review:Hello everyone!
I recently created a Bash noscript designed to help migrate APT keys from the deprecated apt-key to the new best practices in Ubuntu. The noscript includes user confirmation before each step, ensuring that users have control over the process. I developed this noscript using DuckDuckGo's AI tool, which helped me refine my approach.
What This Script Does:
It exports existing APT keys to the /etc/apt/trusted.gpg.d/ directory.
It verifies that the keys have been successfully exported.
It removes the old keys from apt-key.
It updates the APT package lists.
Why I Want This:
As Ubuntu continues to evolve, it's important to keep our systems secure and up to date. Migrating to the new key management practices is essential for maintaining the integrity of package installations and updates.
Questions for the Community:
Is this noscript safe to use? I want to ensure that it won't cause any issues with my system or package management.
Will this noscript work as is? I would appreciate any feedback on its functionality or any improvements that could be made.
Here’s the noscript for your review:

# !/bin/bash

# Directory to store the exported keys

KEY_DIR="/etc/apt/trusted.gpg.d"

# Function to handle errors

handle_error() { echo "Error: $1" exit 1 }

# Function to prompt for user confirmation

confirm() { read -p "$1 (y/n): " -n 1 -r echo # Move to a new line if [[ ! $REPLY =\~ ^([Yy\]$) \]\]; then echo "Operation aborted." exit 0 fi }

# Check if the directory exists

if [ ! -d "$KEY_DIR" \]; then handle_error "Directory $KEY_DIR does not exist. Exiting." fi

# List all keys in apt-key

KEYS=$(apt-key list | grep -E 'pub ' | awk '{print $2}' | cut -d'/' -f2)

# Check if there are no keys to export

if [ -z "$KEYS" \]; then echo "No keys found to export. Exiting." exit 0 fi

# Export each key

for KEY in $KEYS; do echo "Exporting key: $KEY" confirm "Proceed with exporting key: $KEY?" if ! sudo apt-key export "$KEY" | gpg --dearmor | sudo tee "$KEY_DIR/$KEY.gpg" > /dev/null; then handle_error "Failed to export key: $KEY" fi echo "Key $KEY exported successfully." done

# Verify the keys have been exported

echo "Verifying exported keys..." confirm "Proceed with verification of exported keys?" for KEY in $KEYS; do if [ -f "$KEY_DIR/$KEY.gpg" \]; then echo "Key $KEY successfully exported." else echo "Key $KEY failed to export." fi done

# Remove old keys from apt-key

echo "Removing old keys from apt-key..." confirm "Proceed with removing old keys from apt-key?" for KEY in $KEYS; do echo "Removing key: $KEY" if ! sudo apt-key del "$KEY"; then echo "Warning: Failed to remove key: $KEY" fi done

# Update APT

echo "Updating APT..." confirm "Proceed with
updating APT?" if ! sudo apt update; then handle_error "Failed to update APT." fi

echo "Key migration completed successfully."

I appreciate any insights or suggestions you may have. Thank you for your help!

https://redd.it/1jaz34c
@r_bash
Using grep / sed in a bash noscript...

Hello, I've spent a lot more time than I'd like to admit trying to figure out how to write this noscript. I've looked through the official Bash docs and many online StackOverflow posts.

This noscript is supposed to take a directory as input, i.e. /lib/64, and recursively change files in a directory to the new path, i.e. /lib64.

The command is supposed to be invoked by doing ./replace.sh /lib/64 /lib64

#!/bin/bash

# filename: replace.sh

INDIR=$(sed -r 's/\//\\\//g' <<< "$1")
OUT
DIR=$(sed -r 's/\//\\\//g' <<< "$2")

echo "$1 -> $2"
echo $1
echo "${INDIR} -> ${OUTDIR}"

grep -rl -e "$1" | xargs sed -i 's/${INDIR}/${OUTDIR}/g'

# test for white space ahead, white space behind
grep -rl -e "$1" | xargs sed -i 's/\s${INDIR}\s/\s${OUTDIR}\s/g'

# test for beginning of line ahead, white space behind
grep -rl -e "$1" | xargs sed -i 's/^${INDIR}\s/^${OUTDIR}\s/g'

# test for white space ahead, end of line behind
grep -rl -e "$1" | xargs sed -i 's/\s${INDIR}$/\s${OUTDIR}$/g'

# test for beginning of line ahead, end of line behind
grep -rl -e "$1" | xargs sed -i 's/^${INDIR}$/^${OUTDIR}$/g'

IN_DIR and OUT_DIR are taking the two directory arguments, then using sed to insert a backslash before each slash. grep -rl -e "$1" | xargs sed -i 's/${IN_DIR}/${OUT_DIR}/g' is supposed to be recursively going through a directory tree from where the command is invoked, and replacing the original path (arg1) with the new path (arg2).

No matter what I've tried, this will not function correctly. The original file that I'm using to test the functionality remains unchanged, despite being able to do the grep ... | xargs sed ... manually with success.

What am I doing wrong?

Many thanks

https://redd.it/1javegq
@r_bash
find, but exclude file from results if another file exists?

I found a project that locally uses whisper to generate subnoscripts from media. Bulk translations are done by passing a text file to the command line that contains absolute file paths. I can generate this file easily enough with

find /mnt/media/ -iname .mkv -o -iname .m4v -o -iname .mp4 -o -iname .avi -o -iname .mov -o -name .mpg > media.txt

The goal would be to exclude media that already has an .srt file with the same filename. So show.mkv that also has show.srt would not show up.

I think this goes beyond find and needs to be piped else where but I am not quite sure where to go from here.

https://redd.it/1jc6ht5
@r_bash
Install NVM with bash

Anyone have a handy noscript that will install nvm + LTS nodejs with a bash noscript?

I use the following commands on an interactive shell fine, but for the life of me I can't get it to install with a bash noscript on Ubuntu 22.04.

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash && source ~/.bashrc && nvm install --lts


https://redd.it/1jc4ge2
@r_bash
How to make a noscript to populate an array in another noscript?

I'm too new to know what I even need to look up in the docs, here. Hopefully this makes sense.

I have this noscript:

#!/bin/bash

arr0="0"
arr1="1"
arr2="2"

rand=$$RANDOM % ${#arr[@}]

xdotool type ${arr$rand}

Which, when executed, types one of the characters 0, 1, or 2 at random. Instead of hard coding those values to be selected at random, I would like to make another noscript that prompts the user for the values in the arrays.

Ie. Execute new noscript. It asks for a list of items. I enter "r", "g", "q". Now the example noscript above will type one of the characters r, g, or q at random.

I'm trying to figure out how to set the arrays arbitrarily without editing the noscript manually every time I want to change the selection of possible random characters.

https://redd.it/1jc3m5l
@r_bash
My while read loop isn't looping

I have a folder structure like so:
/path/to/directory/foldernameAUTO001
/path/to/directory/foldername
002

I am trying to search through /path/to/directory to find instances where the directory "foldernameAUTO" has any other directories of the same name (potentially without AUTO) with a higher number after the underscore.

For example, if I have a folder called "testfolderAUTO001" I want to find "testfolder002" or "testfolderAUTO002". Hope all that makes sense.

Here is my loop:

#!/bin/bash

Folder=/path/to/directory/

while IFS='/' read -r blank path to directory foldername
seq; do
echo "Found AUTO of $foldernameseq"
foldername=$(echo "$foldername
seq" | cut -d -f1) && echo "foldername is $foldername"
seq=$(echo "$foldername
seq" | cut -d -f2) && echo "sequence is $seq"
printf -v int '%d/n' "$seq"
(( newseq=seq+1 )) && echo "New sequence is 00$newseq"
echo "Finding successors for $foldername"
find $Folder -name "$foldername"
00"$newseq"
noauto=$(echo "${foldername:0:-4}") && echo "NoAuto is $noauto"
find $Folder -name "noauto"00"newseq"
echo ""
done < <(find $Folder -name "*AUTO*")

And this is what I'm getting as output. It just lists the same directory over and over:

Found AUTO of foldernameAUTO
001
foldername is foldernameAUTO
sequence is 001
New sequence is 002
Finding successors for foldernameAUTO
NoAUTO is foldername

Found AUTO of foldernameAUTO001
foldername is foldernameAUTO
sequence is 001
New sequence is 002
Finding successors for foldernameAUTO
NoAUTO is foldername

Found AUTO of foldernameAUTO
001
foldername is foldernameAUTO
sequence is 001
New sequence is 002
Finding successors for foldernameAUTO
NoAUTO is foldername

https://redd.it/1jdel1z
@r_bash
DD strange behavior

Im sending 38bytes string from one device via uart to pc. Stty is configured as needed 9600 8n1. I want to catch incoming data via dd and i know its exactly 38bytes.

dd if=/dev/ttyusb0 bs=1 count=38

But after receiving 38bytes it still sits and waits till more data will come. As a workaround i used timeout 1 which makes dd work as expected but i dont like that solution. I switched to using cat eventually but still want to understand the reasons for dd to behave like that shouldnt it terminate with a status code right after 38bytes?

https://redd.it/1jgxyit
@r_bash
"return" doesn't return the exit code of the last command in a function

#!/bin/bash

bar() {
echo bar
return
}

foo() {
echo foo
bar
echo "Return code from bar(): $?"
exit
}
trap foo SIGINT

while :; do
sleep 1;
done

I have this example noscript. When I start it and press CTRL-C (SIGINT):

# Expected output:
^Cfoo
bar
Return code from bar(): 0

# Actual output:
^Cfoo
bar
Return code from bar(): 130

I understand, that 130 (128 + 2) is SIGINT. But why is the return statement in the bar function ignoring the successful echo?

https://redd.it/1jgvheu
@r_bash
send commands via stdin

Hi every one, I am working with gdb, and I want to send commands to it via stdin,

look at this commands:

`echo -e "i r\n" > /proc/\`ps aux | grep "gdb ./args2" | awk 'NR == 1 {print $2}'\`/fd/0`

and I tried this

`echo -e "i r\r\n" > /proc/\`ps aux | grep "gdb ./args2" | awk 'NR == 1 {print $2}'\`/fd/0`





I expected to send `i r` to gdb, and when I check gdb, I found the string I send "i r", but it did not execute, and I was need to press enter, how to do it without press enter.

note: I do not want to use any tools "like expect", I want to do it through echo and stdin only.





https://redd.it/1jhergb
@r_bash
Continue the noscript after an if ?

Hi there, I'm struggling :)

trying to make a small bash noscript, here it is :



#!/bin/bash

set -x #;)

read user

if [[ -n $user ]]; then

exec adduser $user

else

exit 1

fi

mkdir $HOME/$user && chown $user

mkdir -p $HOME/$user/{Commun,Work,stuff}


I am wondering why commands after the if statement won't execute ?



https://redd.it/1ji02u4
@r_bash
Why is this echo command printing the error to terminal?

I was expecting the following command to print nothing. But for some reason it prints the error message from ls. Why? (I am on Fedora 41, GNOME terminal, on bash 5.2.32)

echo $(ls /sdfsdgd) &>/dev/null

If someone knows, please explain? I just can't get this off my head.

https://redd.it/1ji5o1o
@r_bash
How to run every noscript in directory one-at-a-time, pause after each, and wait for user input to advance to the next noscript?

find . -type f -executable -executable {} \; runs every noscript in the directory, automatically running each as soon as the previous one is finished. I would like to see the output of each noscript individually and manually advance to the next.

https://redd.it/1jiimyg
@r_bash
Sourcing for bash -c fails, but bash -i -c works

I think I am going insane already....



I need to run a lot of commands in parallel, but I want to ensure there is a timeout. So I tried this and any mutation I can think off:



timeout 2 bash -c ". ${BASH_SOURCE}; function_inside_this_file "$count"" > temp_findstuff_$count &


I am 100% unable to get this to work. I tried cat to ensure that bashsource is defined properly. Yes, the file prints to stdout perfectly fine. So the path definitely is correct. Sourcing with && echo Success || echo Failed prints Success, so the sourcing itself is working. I tried with export. I tried eval. Eval does not work, as it is not a program, but just a function of the noscript and it cannot find it. Here commmes the issue:



timeout 2 bash -c ". ${BASH_SOURCE}; function_inside_this_file "$count""

Does not output anything.

timeout 2 bash -i -c ". ${BASH_SOURCE}; function_inside_this_file "$count""

This outputs the result as expected to console. But now combining the timeout with an & at the end to make it parallel and the loop being followed with a wait statement, the noscript never finishes executing, also not after 5 minutes. Adding an exit after the command also does nothing. I am now at 500 processes. What is going on?


There MUST be a way, to run a function from a noscript file (with a relative path like from $BASH_SOURCE) with a given timeout in parallel. I cannot get it to work. I tried like 100 different mutations of this command and none work. The first book of moses is short to the list of variations I tried.


You want to know, what pisses me off further?


This works:

timeout 2 bash -i -c ". ${BASH_SOURCE}; function_inside_this_file "$count"; exit;"

But of course it is dang slow.


This does not work:

timeout 2 bash -i -c ". ${BASH_SOURCE}; function_inside_this_file "$count"; exit;" &


It just is stuck forever. HUUUUH????????? I am really going insane. What is so wrong with the & symbol? Any idea please? :(

https://redd.it/1jive1g
@r_bash
Did I miss something

What happened to r/bash did someone rm -rf / from it? I could have sworn there were posts here.

https://redd.it/1jiuztz
@r_bash
GitHub - helpermethod/alias-investigations

This is a small Bash function to detect if an alias clashes with an existing command or shell builtin.

Just source ai and give it a try.

https://github.com/helpermethod/alias-investigations

https://redd.it/1jmkk6m
@r_bash
What is the professional/veteran take on use / over-use of "exit 1" ?

Is it okay, or lazy, or taboo, or just plain wrong to use to many EXIT's in a noscript?

For context... I've been dabbling with multiple languages over the past years in my off time (self-taught, not at all a profession), but noticed in this one program I'm building (that is kinda getting away from me, if u know what I mean), I've got multiple Functions and IF statements and noticed tonight it seems like I have a whole lot of "exit". As I write noscript, I'm using them to stop the noscript when an error occurs. But guarantee there are some redundancies there... between the functions that call other functions and other noscripts. If that makes sense.

It's working and I get the results I'm after. I'm just curious what the community take is outside of my little word...

https://redd.it/1jll0j9
@r_bash
Amateur - Made a shell noscript for reinstallation

I'm back on linux and into distro-hopping, so I made a reinstallation noscript.

I've been noscripting in PowerShell before, but new to Bash. But this project is my learning journey.

Always open to suggestions and tips if anyone is interested. If you have similar noscript please let me know, I'm eager to learn new ways.

https://github.com/dkaaven/Restaller

About the noscript

The install noscript is a terminal UI that helps look through the noscripts I'm making and run them.

install.sh will loop through the noscript folder and display all .sh files by name and the second line (used as a tag).
install-beta.sh supports folders and will replace install.sh soon.

Plan

I want to improve on the noscript part, make functions to reuse code.
Next function to make is a shell detect and add function, that takes the lines of code and add them to all .*rc files that the user has. But avoiding duplication.

I also want to support more distros in the future, but will focus on Debain/Ubuntu based for now, since this is what I use.

https://redd.it/1jldlzp
@r_bash
Automatic management of multiple background processes in a regular shell session?

I need to launch several (say, 4) background processes and have them all stay running while I interact with them. The interactions will be completely async and not in any particular order. I need to be able to do basicly three things:

1) If a background process dies, it's automaticly respawned, unless it's respawning too fast, in which case stop trying to respawn it and print an error message.

2) Functions are generated in the current session to allow me to send commands to the background processes individually, or all at once. Say:

task1 () { echo "${@}" > task1's stdin; }
task2 () { echo "${@}" > task2's stdin; }
all () { echo "${@}" > task1's stdin; echo ${@}" > task2's stdin; }

If the background task is respawned, I need its stdin function to be able to automaticly redirect to the newly spawned version's stdin, not a broken pipe.

and 3) Any output that they generate on their stdout/stderr gets echoed to the screen with a prefix for the background process' name in lower case for stdout traffic, and upper case for stderr traffic. Only process complete lines of output.

Am I barking up the wrong tree to think doing this all in a regular shell session is a good idea, or should I just make this a noscript of its own to REPL this. Having a hard time visuallizing how 1 can satisfy the requirement to keep 2 and 3 targetting the correct. I know I can capture the PIDs of the background tasks with $! and figure I can keep track of the file streams with an associative array like:

declare -A TASKPID
declare -A TASK1
PIPE=(stdin=5 stdout=6 stderr=7)
task1.exe 0<${TASK1PIPE[stdin]} 1>${TASK1PIPEstdout} 2>${TASK1PIPE[stderr]} &
TASK
PIDtask1=$!

But without something else happening asynchronously in the current session (background function?), how would the current session respawn a dead task and clean up its data, without the user having to issue the command directly, which breaks the "immersion".

I'm just hanging out over the edge of all of my prior bash noscripting experience here. This is as a direct result of my learning that there can, indeed, be only one coproc per bash interpretter.

https://redd.it/1jl525f
@r_bash
Introducing "bd" – A Simple Yet Powerful Bash Autoloader

Hey everyone,

I built a tool called `bd` to help with environment management in Bash. It automatically loads noscripts from multiple, different bash.d directories, making it easier to keep your setups modular and organized.

Unlike /etc/profile.d/, bd dynamically loads environment profiles based on the directory you’re in. This makes it great for keeping project-specific Bash settings with the project itself (e.g., in version control) rather than cluttering your personal .bashrc.

# Why use "bd"?

🔹 Automatic Script Loading – Just drop noscripts into a directory, and bd loads them automatically—no manual sourcing needed.
🔹 No Root Access Needed – Works at the user level, making it useful for project-based configurations.
🔹 Keeps Bash Configs Clean – Reduces .bashrc clutter and makes things more maintainable.
🔹 Easy Environment Switching – The right configurations apply automatically as you move between directories.

The GitHub repo has documentation and examples to get started:

🔗 **GitHub: bash-d/bd**

If you manage Bash noscripts in a similar way, I’d love to hear your thoughts! Try it out and let me know what you think.

TL;DR: bd is a small Bash tool that autoloads noscripts from specified directories, making environment management easier. Check it out!

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