r_bash – Telegram
dyetide/dye - convert color codes from the terminal

Hi All!

I recently finished up a bash noscript project called dyetide/dye. dye is a simple utility that converts hex, rgb, and hsl color codes in the terminal. dyetide uses dye to search through a (css) file and convert said color codes throughout the whole file.

This was an educational project, I know there are better tools (python) out there that could have accomplished this. I just wanted to see what was possible with bash. It turned out...okay! Feel free to try it out. Constructive criticism and suggestions are always welcome, but this will probably be my last extensive bash noscript for a while, so don't expect much more work on this going forward (we'll see, I've come to really enjoy bash noscripting).

Special thanks are specified in the README, comments, and man pages. Thanks to all in r/bash that helped me hash out some of the details and made helpful suggestions along the way!

P.S. If you'd rather not get the noscript from github for some reason, here is the mirror repo on codeberg.

https://redd.it/zzlkdm
@r_bash
I need to change this noscript so that if nothing is selected it stops

I have this noscript that I use to get a list of pdfs and view them in dmenu or fzf and then open the selected in Evince. The problem is that its gonna open Evince even if I don't select a noscript. I don't know how to fix it, I know its bound to be simple but I couldn't find anything in my bash bible.
I know that : means do nothing in bash but I have no idea how to tell the noscript that if the user didn't select anything do :
Thank you for your time and any help is appreciated.

# List PDFs in given directory and opens selection in Evince

# Change to PDFs path
cd $HOME/Downloads/Documents/ || return

# List only the files with .pdf format
book=$(find . -name "*.pdf" | dmenu -p "Select Book")

# Open selected file in Evince
evince "$book" &

# Get terminal PPID and close terminal when the noscript is done
PPPID=$(awk '{print $4}' "/proc/$PPID/stat")
kill "$PPPID"


https://redd.it/10051kd
@r_bash
Anyone with bash get shopt -s lithist to work?

I'm running 4.4.12 under Cygwin (latest version as of this writing) and can't get lithist to work. cmdhist is also set.

Under Linux running bash 5.0.17 it works for that login session. If I log off then log back in, the multiline commands are broken out into different commands again.

https://redd.it/100jdbu
@r_bash
Standard or simplified way to pass all parameters of a function to a command

I have a few functions where I'd like to easily pass 0 or more arguments to a function and have those passed to a single command with quoting and escaping intact.

For example:

function useless()
{
less $*
}

But if I call:

useless 'this is first' 'this is second'

It effectively calls less with 6 arguments instead of two:

less this is first this is second

What I want is:

less 'this is first' 'this is second'

Of course I can write a loop in `useless()` to build the command line, but I'm wondering if there's something built-in I'm missing that would be simpler.

https://redd.it/100kev0
@r_bash
[Help] Bash Array Question(s)

I'm parsing the content of a file or files. There will always be at least one (1), and up to four (4) of these files, ordered sequentially, e.g. **syno_mac_address1**, **syno_mac_address2**. The content of each file will always be a unique MAC address, e.g.: **001132623d3f**, **001132623d40**

Here's my approach to extracting these MAC addresses:

# GNU bash, version 4.4.23(1)-release (x86_64-pc-linux-gnu)

mac_address=( $(cat /proc/sys/kernel/syno_mac_address{1..4}))

and then printing these address:

for i in "${!mac_address[@]}"; do
printf '%s\n' "LAN $i ${mac_address[$i]}"
done

Here's sample output:

**LAN 0 001132623d3f**

**LAN 1 001132623d40**

This almost does what I'd like, except there's mismatch between the LAN number (the OS counts from `1`, **not** `0`). The desired output would be:

**LAN 1 001132623d3f**

**LAN 2 001132623d40**

But I'm not sure how to approach that. In addition, (ShellCheck)[shellcheck.net] complains about the way I declare the array, e.g.: **Prefer mapfile or read -a to split command output (or quote to avoid splitting)**, but the proposed solutions don't give me the output I expect.

I am also wondering if there's a more succinct way to handle this e.g.:

mac_address() {

MAC=$(cat /proc/sys/kernel/syno_mac_address{1..4})
printf "%s\n" "$MAC"
}

with some slight modification, e.g.: `printf '%s\n' "${mac_address[@]/LAN/ }"`. The problem I have there is that I am not sure how to add a count.

Thanks.

https://redd.it/100woy5
@r_bash
Howto measure uptime of hosts in local network (lightweight)?

Hi,I'm looking for a simple lightweight tool that can measure hosts uptime in hours/minutes per day in my local network (I guess ping can be used for that). I'm just looking for a simple report (HostA: X hours/minutes up on Monday, etc...) The remote hosts are windows so Im looking for a solution that doesn't require running a client on the host.
I need to get insight in uptime hours per day on a few hosts in my network.I'm planning to use my Raspberry PI (running Rasbian/pihole) for that.
I have Nagios running now but that's not really reporting what I'm looking for (it's just polling every now and then).
Could you please advise what to use? I discovered 'monitorr' on the web but that was written for windows.
Thanks in advance for your help

https://redd.it/1019dra
@r_bash
Script to delete specific files

I have a directory with the following files:

file1.txt
file1.txt.old
file2.txt.old
file3.txt
file3.txt.old
file4.txt.old

My goal is to write a noscript that deletes all *.old files, except if there is a non-old file with the same name. So it would keep file1.txt, file1.txt.old, file3.txt, file3.txt.old in this example. The filenames can contain spaces and letters from A-Z (with accents).

How can I achieve this with a bash noscript?

https://redd.it/1019c5d
@r_bash
find -exec executing on more files than find lists?

Edit: Of course as soon as I posted, I think I figured out I'm an idiot and that it's executing on the directories and I need to include -type f (or ! -type d would be better?), but would love any input from others anyway on the matter!

Will try to exclude extraneous details, but please let me know if more details would help. Basically, I have a folder structure where some files were changed recently. I'd like to archive just those newer files in a way that preserves the folder structure.

(This is because I already archived and compressed the original files, and figure it's easier just to have two archives side by side to avoid recompressing and reuploading.)

I am trying this out:
find . -ctime -2 -exec bash -c 'tar rvf archive.tar "{}"' \;


When I run find . -ctime -2 | wc -l, I get 978. However, running the above command, it archives over 1030 before I stop it, and it looks like it repeats some files.

Could anyone please help explain why it's not just archiving only the 978 newer files that I intend to archive? Alternatively, any better solution to achieve the same goal?

TIA!

https://redd.it/101l27c
@r_bash
cannot get bash to do case-insensitive completion

$ echo $BASH_VERSION
4.4.12(3)-release

$ shopt|grep case
nocaseglob on
nocasematch on

$ bind 'set completion-ignore-case on'

$ compgen -W 'foo Frank' f
foo

$

This is very frustrating. What is the point of having three separate options to ignore case if none of them work? Just to taunt the user?

How can I get bash to do case-insensitive completion?

https://redd.it/101p4vu
@r_bash
Will this also delete directories or just the files in them?

find /home/daphipz/Downloads/* -atime +7 -exec rm {} \;

This should delete all files in my Download directory that were not accessed in roughly the last 7 days (I dont care about the rounding `atime` does). I also want to delete all subdirectories that match this criteria.

Does `find` also check the directories' `atime` and delete them, or do I need to check for empty folders after executing this line?

https://redd.it/102441z
@r_bash
How to get mouse position in bash

I want to get the mouse cursor position using a bash noscript in a row-col format.

I am making a painting program for the terminal where I want to use the mouse to paint. It is for personal use, but I am reusing the code for other public projects later.

Thanks!

https://redd.it/1026eoh
@r_bash
Saving command with pipes output to variable works in terminal but not on noscript

Context

I have a bash noscript that is executed with cron multiples times a day, the bash noscript calls a python program that does a request to an API and saves the Python output to a variable (this output is a string with spaces).

> var1="$(python $pythonfilepath)"

What I'm interested in doing is saving this output to a log file only if it has not been saved before (this API is updated once daily, but not at the same time every day). So I read the last line of the log file with
> var2="$(tail -1 $logpath)"

And then I compare var2 with var1 and if they are different I save the new value to the file.

**Issue**

There is a weird issue that I can't tell so far if it is on my end or the API, there are some occasions where after updating the value a few minutes later when the noscript is executed again it obtains the value of the day before (some type of cache issue or something like that) so when the noscript compares the value obtained with the last line, they are different, and it saves the old value again, and then a few minutes later it saves the value of that day again.

**My attempt at fixing it**

What I tried to do was changing the second command to
> var2=$(cat $log
path | grep "$var1")

so if the value in var1 is found with grep it outputs that line and the comparison of var1 and var2 can be done and do the rest of the noscript, but this command does not work inside the noscript, it only works on my tests directly on the terminal

https://redd.it/102r751
@r_bash
Help With sed Variable String Manipulation

Hey All!

I am having some trouble manipulating a string contained in a variable using sed and was hoping someone could give me some pointers. I need to replace the `https://` portion of the `ORIGINALURL` variable with `rewrite (?i)^`

The end result being the following: `rewrite (?i)^ example.org/resouces/testing/pages/store`

I want to store the above end result in a separate variable to be called later.

I keep getting stuck on the syntax of sed because I am working with special characters making sed misinterpret things. Any guidance would be appreciated!

ORIGINALURL='https://example.org/resouces/testing/pages/store'
SEDREPLACEMENT='https://example.org'
SEDRAPLACEMENT2='rewrite (?i)^'

EDITEDORIGINALURL=$(echo $ORIGINALURL | sed -e "s\/$SEDREPLACEMENT\/$SEDREPLACEMENT2/g")

When running the `EDITEDORIGINALURL` variable, I receive a `sed: -e expression #1, char 36: unterminated \`s' command` error.

https://redd.it/10365pg
@r_bash
Help with Bash Script - Works from the command line but not via Cron

Greetings, I am having a difficult time with a bash noscript to run daily to backup a database (among other things) The primary issue is that when I test manually, it \*seems\* to work. However, when run from cron, the noscript runs but doesn't do anything. Here is my noscript:


#!/bin/bash

#Definitions
DATE=$(date +%Y%m%d)
DATETIME=$(date +%Y%m%d-%T)
DIR_MONGO="/media/RAID5/graylog/backup/mongodb/"
DIR_CONF="/media/RAID5/graylog/backup/conf/"
DIR_ELASTIC="/media/RAID5/graylog/backup/elasticsearch/"
CLEAN_MONGO="find $DIR_MONGO* -type d -mtime +90 -exec rm -rf {} \;"
CLEAN_CONF="find $DIR_CONF* -type d -mtime +90 -exec rm -rf {} \;"
CLEAN_ELASTIC="find $DIR_ELASTIC* -type d -mtime +90 -exec rm -rf {} \;"
MONGODUMP="/usr/bin/mongodump --quiet -o $DIR_MONGO$DATE"
CONFDUMP="cp /etc/graylog/server/server.conf $DIR_CONF$DATE"
ELASTICDUMP="/usr/local/bin/multielasticdump --direction=dump --input=http://localhost:9200 --output=$DIR_ELASTIC$DATE --type=mappging"
LOG_FILE="/home/ubuntu/graylog/logs/$DATETIME.log"
BODY=$LOG_FILE

# Log Everything
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3' 0 1 2 3
exec 1>$LOG_FILE 2>&1
#Everything below will log to $LOG_FILE


#Create Logfile
if test -f "$LOG_FILE";
then
echo "File Found"
else
touch $LOG_FILE
fi

#Cleanup Mongo
if test -d "$DIR_MONGO";
then
$CLEAN_MONGO
fi

#Cleanup Conf
if test -d "$DIR_CONF";
then
$CLEAN_CONF
fi

#Cleanip Elastic
if test -d "$DIR_ELASTIC";
then
$CLEAN_ELASTIC
fi

#Mongo
if test -d "$DIR_MONGO$DATE";
then
$MONGODUMP
else
mkdir -p "$DIR_MONGO$DATE"
$MONGODUMP
fi

#CONF
if test -d "$DIR_CONF$DATE";
then
$CONFDUMP
else
mkdir -p "$DIR_CONF$DATE"
$CONFDUMP
fi

#Elastic
echo "This is going to take a long, long, long time"
if test -d "$DIR_ELASTIC$DATE";
then
$ELASTICDUMP
else
mkdir -p "$DIR_ELASTIC$DATE"
$CONFDUMP
fi

echo "Done?"

#Send Notice
if test -f "$LOG_FILE";
then
echo "" | mutt -i "$BODY" -s "Graylog Backup Report" -- "recipient@foo.bar"
else
echo "" | mutt -s "ERROR - Graylog Backup Report - No Log File Found" -- "recipient@foo.bar"

So, the first issue (and this may cause subsequent issues) when running the cleanup portion of the noscript I get these errors:

find: missing argument to `-exec'
find: missing argument to `-exec'
find: missing argument to `-exec'

The next issue(s) are that it doesn't actually backup anything.

The log file looks like this:


File Found
find: missing argument to `-exec'
find: missing argument to `-exec'
find: missing argument to `-exec'
This is going to take a long, long, long time
Done?

Which doesn't look like its logging everything but thats a tertiary issue (*N.B.:* *I don't fully understand that portion of the noscript; that is a product of google-foo*)

Thank you kindly for any assistance you can provide :)

https://redd.it/1034il5
@r_bash
Elegant way to add to a string within an associative array?

     I'm using GNU bash, version 5.1.16(1)-release-(x86_64-pc-linux-gnu)x.

     I'm after an elegant way of taking a string element of an associative array, conjoining another string to it, and putting it back into the array. At present I have the following, inelegant code (but I have not managed to find a better method).

strTmp="${job[opts]}"
strTmp="${strTmp} ${rlj_jobs_copy[*]}"
job[opts]=${strTmp}

https://redd.it/103gle7
@r_bash
Something briefly flashes in the taskbar

I'm trying to keep recordings of when microphone exceeds a certain volume. It's running in a terminal in Yakuake

But it's bugging me because on every iteration, something seems to briefly appear in the KDE taskbar which bumps all the taskbar buttons to the side momentarily

It seems to happen as long as I use arecord and wait.

How can I prevent whatever's briefly popping into my taskbar?

#!/bin/bash

# Set the threshold, duration (in seconds), and recording directory
threshold=0.2
duration=10
recording_dir="/mnt/tera/audio/NOISE2"

# Set output options
output_to_console=true
output_to_log=true


# Set trap to handle SIGINT (CTRL+C) signal
trap "echo Exiting...; exit" SIGINT

while :
do
# Record audio for the specified duration
timeout "$duration" arecord -d "$duration" -f S16_LE -c 1 -r 44100 audio.wav &> /dev/null &
pid=$!

# Wait for the arecord command to complete
wait $pid

# Calculate the average audio level
level=$(sox audio.wav -n stat 2>&1 | grep "Maximum amplitude" | awk '{print $3}')

now=$(date +"%Y.%m-%d.%T")

# Save the file and log the timestamp and maximum amplitude
log_entry="$now $level"

if (( $(echo "$level > $threshold" | bc -l) )); then
mv audio.wav "$recording_dir/$now $level.wav"
fi

if $output_to_console; then
echo "$log_entry"
fi

if $output_to_log; then
echo "$log_entry" >> "$recording_dir/audio.log"
fi
done


https://redd.it/103xkt8
@r_bash