r_bash – Telegram
Weird Loop Behavior? No -negs allowed?

Hi all. I'm trying to generate an array of integers from -5 to 5.

for ((i = -5; i < 11; i++)); do
newoffsets+=("$i")
done

echo "Checking final array:"
for all in "${new
offsets@}"; do
echo " $all"
done

But the output extends to positive 11 instead. Even Bard is confused.

My guess is that negatives don't truly work in a c-style loop.

Finally, since I couldn't use negative number variables in the c-style loop, as expected, I just added some new variables and did each calculation in the loop and incrementing a different counter. It's best to use the c-style loop in an absolute-value manner instead of using its $i counter when negatives are needed, etc.

Thus, the solution:

declare -i viewportsize=11
declare -i view
radius=$(((viewportsize - 1) / 2))
declare -i lower
bound=$((viewradius * -1))
unset new
offsets

for ((i = 0; i < viewportsize; i++)); do
# bash can't employ negative c-loops; manual method:
new
offsets+=("$lowerbound")
((lower
bound++))
done

&#x200B;

https://redd.it/1aepy2i
@r_bash
Maintain list of env variables for both shell and systemd

I have a bunch of applications autostarted as systemd user services and I would like them to inherit environment variables defined in the shell config (.zprofile because these are rarely changed). I don't want to maintain two identical list of variables (one for login shell environment and one for systemctl import-environment <same list of these variables>).

I thought about using systemd's ~/.config/environment.d and then have my shell export everything on this list, but there are caveats mentioned here (I won't pretend I fully understand it all), hence why I'm thinking of just going with the initial approach (the shell config is also more flexible allowing setting variables conditionally based on more complicated logic). Parsing output of env is also not reliable as it contains some variables I didn't explicitly set and may not be appropriate for importing by systemd.

What is a good way to go about this? I suppose the shell config can be parsed for the variables but it seems pretty hacky. Associative array for env variables, then parse for the keys of the arrays for the variable names for systemctl import-environment? Any help/examples are much appreciated.

https://redd.it/1afawp3
@r_bash
Are there terminal apps like Fig but for windows?

I am looking for a nice-looking command line like Fig with features like autocomplete, are there windows alternatives?

https://redd.it/1affapj
@r_bash
What is the best way to run a server polling noscript for few days only, every 1 minute? Will it cause any hamper to server status?

host=www.google.com
port=443
while true; do
currenttime=$(date +%H:%M:%S)
r=$(bash -c 'exec 3<> /dev/tcp/'$host'/'$port';echo $?' 2>/dev/null)
if [ "$r" = "0" ]; then
echo "[$current
time] $host $port is open" >>tori.txt
else
echo "$current_time $host $port is closed" >>tori.txt
fi
sleep 60
done


This is the noscript. It runs every 1 minute. I was planning to use setsid ./noscript.sh but I didn't find a way to exit that process easily. So, I am not doing that. Should I run it as a cronjob(It doesn't make much sense to run this as a cronjob though. as it's already sleeping for 60 seconds. Anything you can think of?)

https://redd.it/1afjbg7
@r_bash
Running a command inside another command in a one liner?

Im not too familiar with bash so i might not be using the correct terms. What im trying to do is make a one liner that makes a PUT request to a page with its body being the output of a command.

Im trying to make this

date -Iseconds | head -c -7

go in the "value" of this command

curl -X PUT -H "Content-Type: application/json" -d '{"UTC":"value"}' address


and idea is ill run this with crontab every minute or so to update the time of a "smart" appliance (philips hue bridge)

https://redd.it/1afmquq
@r_bash
Need to create a loop that make a mkdir -p with the openssl rand -hex 2 output.

Hi guys.
Need to create a loop that make a mkdir -p with the openssl rand -hex 2 output.
I try this
\#!/bin/bash
var=$(openssl rand -hex 2)
for line in $var
do
mkdir "${line}"
done
But interact once and then stop!
I need to fullfill every possible combination which openssl rand -hex 2 gives.

Short history: need create hex directory from 0000 to FFFF

&#x200B;

Thanks

https://redd.it/1afrne9
@r_bash
why is this noscript running every second(even multiple times per second)?

host=www.google.com
port=443
while true; do
current_time=$(date +%H:%M:%S)
r=$(bash -c 'exec 3<> /dev/tcp/'$host'/'$port';echo $?' 2>/dev/null)
if [ "$r" = "0" ]; then
echo "[$current_time] $host $port is open" >> log_file.txt
else
echo "[$current_time] $host $port is closed" >> log_file.txt
fi
done

I put it into a cronjob every 1 hour or whatever, it'll always run every 1 second and sometimes multiple times per second.

https://redd.it/1ag2sg9
@r_bash
Is it possible to get the exit code of mv in "mv $folder $target &"

Is it possible to get the exit code of the mv command on the 2nd last line without messing up the progress bar function?

#!/usr/bin/env bash

# Shell Colors
Red='\e0;31m' # ${Red}
Yellow='\e[0;33m' # ${Yellow}
Cyan='\e[0;36m' # ${Cyan}
Error='\e[41m' # ${Error}
Off='\e[0m' # ${Off}

progbar(){
# $1 is pid of process
# $2 is string to echo
local PROC
local delay
local dots
local progress
PROC="$1"
delay="0.3"
dots=""
while [[ -d /proc/$PROC ]; do
dots="${dots}."
progress="$dots"
if [ ${#dots} -gt "10" ]; then
dots=""
progress=" "
fi
echo -ne " ${2}$progress\r"; sleep "$delay"
done
echo -e "$2 "
return 0
}

action="Moving"
sourcevol="volume1"
targetvol="/volume2"
folder="@foobar"

mv -f "/${sourcevol}/$folder" "${targetvol}" &
progbar $! "mv ${action} /${sourcevol}/$folder to ${Cyan}$targetvol${Off}"

https://redd.it/1ag3qiz
@r_bash
Running commands written in file

I am not familiar with advanced bash commands at all. I know the decent way for asking for help would be having at least a half-baked solution, but i have no idea how to do this. I would like to easily run prehook commands before testing for each project, and for that I would like to create a bashrc (zshrc) alias that searches the /test.config file for the commands that are in it, and runs them in sequence.

The format in the file is

{pre_hooks, [
{ct, "command1"},
{ct, "command2"}
]}.

The number and content of the commands is different for each project, and the the file contains a lot of thigs besides this.

I have tried to search it but could not find a relevant result. I will of course check what any given solution does, i want to learn this stuff. Thanks for the help!

https://redd.it/1aga2vn
@r_bash
Variable not global

I have the following code in my noscript and I can't figure out why pkgs_with_links (not pkg_with_link, which is local) is not accessible globally:

printreleasenotes() {
mapfile -t pkgs < <(comm -12 <( sort "$conf" | cut -d' ' -f 1) <( awk '{ sub("^#.| #.", "") } !NF { next } { print $1 }' "$cache" | sort))

if ((${#pkgs@})); then

local url

printf "\n%s\n" "# Release notes:"
for package in "${pkgs@}"; do
while read -r line; do
pkgswithlink="${line%% }"
if [[ "$package" == "$pkgs_with_link" ]]; then
url="${line##
}"
printf "%s\n" "# $(tput setaf 1)$pkgswithlink$(tput sgr0): $url"
pkgswithlinks+=("$url")
break
fi
done < "$conf"
done

printf "%s" "all my links:" "${pkgswithlinks@}"
fi
}

Quick google search shows piping involves a subshell and that variables define inside will not be accessible globally. But the while loop does not involves any pipes.

Any ideas and the recommended way to make it accessible globally? Also is there any point in using declare to initialize a variable? Would it be a good idea to initialize all variables intended to be used globally at the beginning of the noscript so that for maintaining the noscript in the future it's easier to see all the global variables and not accidentally add in code involving a new variable that might be named the same as the global variable?

https://redd.it/1aglq82
@r_bash
can you make a text game in bash?

i just randomly started learning bash from youtube 4 fun although it'd be useful too for what i am doing and my job in the future, and now i have a question, can you make a decent text game in bash? i'd be quite fun to do so

https://redd.it/1agnvoh
@r_bash
Alias for Executable in Makefile

How do I make an executable an alias? So if I had an executable called ./out, and I wanted to run call "out2" to run the executable instead, how'd I do it?

I want to know because I want to run an executable file without having to use a command that starts with "./"

https://redd.it/1agpwug
@r_bash
Dynamic FFmpeg build noscript with extra codecs activated

This noscript represents the result of significant effort to compile FFmpeg while incorporating numerous additional programs into its code all done in Bash.

When you execute the noscript multiple times, it will automatically track the current version of each program. If a newer version is detected, it will update them accordingly. This ensures that you consistently have access to the latest code when building and running FFmpeg.

The noscript will detect if you have Nvidia GPU's and ask if you want to install the CUDA SDK toolkit. It will also detect AMD and install header files for it's GPU.

&#x200B;

Supported Codecs

GitHub Script

https://redd.it/1agri1v
@r_bash
Why does this math expression throw an error and how can I catch it?

The purpose is to convert a string to +ve int. It works except for if the string begins with a number.

echo "$(( "9" ))"

>9

echo "$(( "99" ))"

> 99

echo "$(( "word" ))"

> 0

echo "$(( "word9" ))"

> 0

echo "$(( "9word" ))"

> bash: 9word: value too great for base (error token is "9word")

echo "$(( "99word" ))"

> bash: 99word: value too great for base (error token is "99word")


I don't much care if "9word" fails but I'd like for it to evaluate to 0.

https://redd.it/1ahqmmw
@r_bash
Help with a noscript

Hello everyone. I have problems with this noscript (not sure if it is the noscript itself). I created a cron job with sudo (otherwise it does not send the system to sleep). However, the system does not wake on demanded time, i.e., the noscript only works to send system to sleep.
I have already checked bios and it is configured.

This is code!

# Path to the log file
LOG_FILE="/home/user/folder/Logs/nameofnoscript.txt"

# Set sleep time (23:00h) and wake up time (06:00h)
SLEEP_TIME="23:00:00"
WAKE_UP_TIME="06:00:00"

# Get current date
CURRENT_DATE=$(date +"%Y-%m-%d")

# Convert sleep and wake up times to timestamps
SLEEP_TIMESTAMP=$(date -d "$CURRENT_DATE $SLEEP_TIME" +%s)
WAKE_UP_TIMESTAMP=$(date -d "$CURRENT_DATE $WAKE_UP_TIME" +%s)

# Calculate time difference until next suspension
TIME_DIFFERENCE=$((SLEEP_TIMESTAMP - $(date +%s)))

# Check if sleep time has already passed for today; if so, adjust for tomorrow
if [ $TIME_DIFFERENCE -lt 0 ]; then
SLEEP_TIMESTAMP=$((SLEEP_TIMESTAMP + 86400)) # Add 24 hours (in seconds)
TIME_DIFFERENCE=$((SLEEP_TIMESTAMP - $(date +%s)))
fi

# Log next suspension
echo "Next scheduled suspension for: $(date -d @$SLEEP_TIMESTAMP)" >> $LOG_FILE

# Schedule suspension using rtcwake
sudo rtcwake -m mem -t $SLEEP_TIMESTAMP >> $LOG_FILE 2>&1

# Log suspension completed
echo "System suspended at: $(date)" >> $LOG_FILE

Could anybody help or point me the right direction?

https://redd.it/1ahsvct
@r_bash
Running noscripts from master noscript causes them to fail

I have multiple bash noscripts that run in sequence. Normally they are scheduled as cron jobs and work perfectly. But, we want to change the process in which they are run - basically if one of them fails the others will not execute.

So, I decided to put them in a master noscript which calls the other noscripts in sequence. It checks the exit code from each noscript and only executes the next one if the exit code was 0. It sends an alert via email and SMS if there was an error.

The problem is, the individual jobs run just fine as cron jobs but sometimes fail when run from the master cron job. I added a ton of logging, including the old "$logfile" 2>&1, and there is really no reason for the failure. It just randomly fails. The exit code in the called job is 0, but the master noscript thinks it is not.

Is there some trick to getting something like this to work? Am I doing something stupid here and there is a better way to do it?


#!/bin/bash
logger -s "SCRIPT - FOOBARSCRIPTS - Started at $(date)"
. /home/noscripts/alerts/alerts.function
log
file="/fee/fi/fo.fum"
rm -f /fee/fi/fo.fum
touch /fee/fi/fo.fum
#
/bin/bash /foo/bar/baz.sh >> "$logfile" 2>&1
if [ $? -eq 0 ]; then
logger -s "SCRIPT - FOOBARSCRIPTS - /foo/bar/
baz.sh completed successfully"
else
logger -s "SCRIPT - FOOBARSCRIPTS - Error running /foo/bar/
baz.sh"
sendalert FOOBARSCRIPTS
exit 99
fi
#
/bin/bash /foo/bar/
qux.sh >> "$logfile" 2>&1
if $? -eq 0 ; then
logger -s "SCRIPT - FOOBARSCRIPTS - /foo/bar/qux.sh completed successfully"
else
logger -s "SCRIPT - FOOBARSCRIPTS - Error running /foo/bar/qux.sh"
sendalert FOOBARSCRIPTS
exit 99
fi
logger -s "SCRIPT - FOOBARSCRIPTS - Ended at $(date)"

https://redd.it/1ai2wzg
@r_bash
How to get the output of a program as finally seen on the screen?

Hi,

I have a program (foo) that outputs something while in progress, then deletes the current line to write the final output:

in progress foo bar<DELETE WHOLE LINE>done foo bar

So the final string seen on the screen is [done] foo bar.

I'd like to call this program from a bash noscript. The problem I am facing is:

echo "Result: $(foo)" does not result in: Result: [done] foo bar

Instead, the prefixed string "Result: " is deleted: [done] foo bar

How can I achieve an output like: Result: [done] foo bar

https://redd.it/1aimagi
@r_bash
Block, I-beam, or Underscore. What's your kink?

Can't tolerate block, underscore tolerable, but beam is the boss.

https://redd.it/1ain39t
@r_bash
[update] forkrun (the insanely fast pure-bash loop parallelizer) just got updated to v1.1 and got a new feature!!!

Earlier today I pushed a larger update to the main [forkrun](https://github.com/jkool702/forkrun) branch on github, bumping it up to forkrun v1.1.

For those that missed it, [here](https://www.reddit.com/r/bash/comments/19985k2/presenting_forkrun_the_fastest_purebash_loop/?utm_source=share&utm_medium=web2x&context=3) is the initial (v1.0) `forkrun` release thread here on /r/bash.

***

**The main "new feature" introduced in forkrun v1.1 is the ability to split up stdin based on the "number of bytes read"**. Previously, you could only split up stdin by the "number of lines read" (or, more generally, by the "number of delimiters read"). Two new flags have been introduced to facilitate this capability: `-b <bytes>` and `-B <bytes>`:

* `-b <bytes>`: this flag causes `forkrun` to read up to `<bytes>` at a time from stdin. However, if less than `<bytes>` is available on stdin when a given worker coproc is reading data it will not wait and will proceed with less than `<bytes>` data
* `-B <bytes>`: this flag causes `forkrun` to read exactly `<bytes>` at a time from stdin. If less than `<bytes>` is available on stdin when a given worker coproc is reading data it will wait and will not proceed until it accumulates `<bytes>` of data or all of stdin has been used.
* for both flags, `<bytes>` can be specified using a trailing `k`, `m`, `g`, `t`, or `p` (for `1000^{1,2,3,4,5}`) or `ki`, `mi`, `gi`, `pi`, or `ti` (for `1024^{1,2,3,4,5}`). Adding the trailing `b` and/or using capital letters is accepted, but does not change anything (e.g., `64kb`, `64KB`, `64kB`, `64Kb`, `64k` and `64K` all mean 64,000 bytes).

There is also a minor enhancement in the `-I` / `--INSERT` flag's functionality, and (of course) a handful of minor bug fixes and even a few more minor optimizations.

***

Its been awesome to hear from a couple of you out there that `forkrun` is being used and is working well! As always, let me know of any bugs you encounter and I'll try to find am squash them ASAP. If `forkrun` is missing a feature that you would find useful feel free to suggest it, and if I can figure out a good way to add it I will.

https://redd.it/1aj2na5
@r_bash
bash command overwritten by later command

Under what conditions can a bash command be overwritten by a later command?

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