r_bash – Telegram
How does this sed command work?

The command is used to remove all empty lines left at the end of the file. I hope it's alright to ask about sed here, this command is really tricky.

sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' file.txt

https://redd.it/1c2jtul
@r_bash
Recursive noscript with pattern matching issues

I am trying to write a noscript to parse a file, This file contains the following (only a snippet for exmaple)

define service{

name win-ns-check-login-decom-service ; The 'name' of this service template

service_denoscription Windows Login State for Decom Pending

servicegroups windows-ns-service-group

use generic-info-service

hostgroup_name decom-windows-servers,!win-ns-check-login-no-restart

check_command check_ns_args!check_login!"-_Reload 1"

}

​

define service{

name win-ns-check-login-no-restart-service ; The 'name' of this service template

service_denoscription Windows Login State wo Restart

servicegroups windows-ns-service-group

use generic-service

hostgroup_name win-ns-check-login-no-restart

notification_interval 0 ; Only send notifications on status change by default.

notification_options c,r

check_command check_ns_args!check_login!"-_Reload 0"

}

​

define service{

name win-ns-check-activation-service ; The 'name' of this service template

service_denoscription Windows Activation State

servicegroups windows-ns-service-group

use generic-p2-service

hostgroup_name windows-nsclient-servers,win-ns-check-activation,!win-ns-check-login-no-restart,!win-ns-check-login,!exclude-win-check-activate

notification_interval 0 ; Only send notifications on status change by default.

notification_options c,r

check_command check_ns_args!check_login!"-_DoLogin 0"

}

​

I am trying to recursively go through this file with over hundreds of entries and map all of these fields in CSV format, The noscript I have is as such:

\#!/bin/bash

echo "Command_Name,Check_Command,Service_Group,Service_Denoscription,Use,Hostgroup_Name"

for s in "`cat /etc/icinga/objects/services/* | grep -v "#" | sed -n '/{/,/}/{p;/}/q}'`"

do

cn=`echo "$s" | grep "\^name" | awk '{print $2}'`

use=`echo "$s" | grep "use" | awk '{print $2}'`

sg=`echo "$s" | grep servicegroups | awk '{print $2}'`

sd=`echo "$s" | grep service_denoscription | awk '{print $2" " $3" "$4" "$5" "$6}'`

hgn=`echo "$s" | grep hostroup_name | sed 's/ hostgroup_name //g'`

ccom=`echo "$s" | grep check_command | sed 's/ check_command //g'`

echo "$cn,$ccom,$sg,$sd,$use,$hgn"

done

I have tried looking on various forums for awk and sed commands that can recursively go through the file, I am trying to extract the chunks between the "{" and "}" and treat them as their own "object" to grep through and extract the values, however, all I can do is either get the first data chunk OR get between the first { and the last }.... so effectively I get everything in one big chunk. any ideas here? grep -A and -B will not work because those are absolute values for n number of lines and not all entries are formatted the same and may result in cross-contamination from other entries.

the end result should output something like the following:

Command_Name,Check_Command,Service_Group,Service_Denoscription,Use,Hostgroup_Name

win-ns-check-login-decom-service,check_ns_args!check_login!"-_Reload 1",windows-ns-service-group,Windows Login State for Decom Pending,generic-info-service,decom-windows-servers,!win-ns-check-login-no-restart

win-ns-check-login-no-restart-service,check_ns_args!check_login!"-_Reload 0",windows-ns-service-group,Windows Login State wo Restart,generic-service,win-ns-check-login-no-restart

win-ns-check-activation-service,check_ns_args!check_login!"-_DoLogin 0",windows-ns-service-group,Windows Activation State,generic-service,check_ns_args!check_login!"-_DoLogin
Random number generator issue

I am currently trying to code a number generator that generates a number between 1 and 7 every 10 seconds.

Here is my code:

\#!/bin/bash

while true; do

random_number=$(( (RANDOM % 7) + 1 ))

echo "Random number between 1 and 7: $random_number"

sleep 10

done

​

However when i run the code it always just gives me a result of 1. Am I doing something wrong?

https://redd.it/1c2v2uc
@r_bash
In array jobs, how to use argument from $id, such as python.py $id0, $id1 and py.py ../folder/+$id1?

for example, my python file is like

python3 file.py arg1 'arg2'

I code this command in one noscript using array jobs, like

#!/bin/bash
#SBATCH -J array-job
#SBATCH -a 1-4

idlist="PARALIST.txt"
id=head -n $SLURM_ARRAY_TASK_ID $id_list | tail -n 1

in which, PARA_LIST.txt is like

arg1-1, arg2-1
arg1-2, arg2-2
arg1-3, arg2-3
arg1-4, arg2-4

so, each $id is string, $id[0] and %id[1] are also string. But arg1 in file.py is not string. How to implement the following noscript?

#!/bin/bash
#SBATCH -J array-job
#SBATCH -a 1-4

idlist="PARALIST.txt"
id=head -n $SLURM_ARRAY_TASK_ID $id_list | tail -n 1
cd ../folder + $id1
python3 file.py $id0 $id1

Thanks in advance!

https://redd.it/1c2woog
@r_bash
Linux open-source book, Like DevOps

My book about command shell, utils, tips, fast work with awesome programs.

​

Regards: Microsoft, Canonical, Alphabet

https://redd.it/1c2ypv6
@r_bash
Environmental Madness

Making my first ever special little directory for my future Bash-growth-and-development, writing them noscripts like a grown-up, my own beautiful bins, feeling so worldly. This little exchange with the shell amused me more than it should, and so I thought it might be amusing to the fine Bash-humans of Bash-world.

Luckily I had just echo'd $PATH moments before, so a quick kill-yank and the day was saved. There was an instance where I thought: "what, where's my stuff, noooooo". What would I have done, if I'd clobbered it? Dust off grep and go hunting for binary hotspots?

Anyway, it was a minute of my day, but good times were had.

Wishing you all the best in your day.

https://preview.redd.it/7rlbf5qw2auc1.png?width=1280&format=png&auto=webp&s=baa2b4c03bb5a09361435e5916c06aeb43359ebd



https://redd.it/1c36l4h
@r_bash
For a job interview, how would you present a bunch of API cURL commands to oAuth and server endpoints?

Like you have tasks that involve making cURL commands to oAuth and Server endpoints to obtain tokens and do stuff on the API endpoints. In the interview, you guys will present how and what you did. So how would you present this to them. I am thinking docker or Github private.

https://redd.it/1c3a9ti
@r_bash
Intercepting key presses and passing them to a background process

If anyone could assist with this shell noscript I'd appreciate it.

The idea is that `mplayer` is running in the background so that I can detect an "s" key press (to save the current path to file), but in all other cases I want to pass the keyboard input to `mplayer` so that I can still use its controls.

Is this possible? Or is there another approach? I have not been able to solve this ssist with this shell noscript I'd appreciate it.

`for audio_file in "${playlist[@]}"; do`

`mplayer -really-quiet "$audio_file" &`

`mplayer_pid=$!`

`while true; do`

`read -n 1 -t 1 -s key`

`if [ "$key" != "s" ]; then`

`# pass the key press to \`mplayer\` here`

`else`

`echo "$audio_file" >> favorites.txt`

`fi`

`done`

`done`

https://redd.it/1c3c7u7
@r_bash
Looking for assistance - Modifying Matrix code rain

I was wondering if anyone could help me figure this out.

Found this authored by derrick.blarg Matrix Reimagined: Crafting Digital Rain with Bash and ChatGPT – Derrick.Blarg
Check out the article to find a preview.

I'd like to modify this a bit. In essence, I'd like to only loop it twice. That said, on the second loop in the center of the console, spell out a defined string variable with the rain as the loop is ending.

#!/bin/bash

# This noscript creates a Matrix-style falling text effect in the terminal.

# Define strings for extra characters (Japanese Katakana) and extended ASCII characters
extrachars="カキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン"
extended
ascii="│┤┐└┴┬├─┼┘┌≡"

# Define arrays of color codes for a fading green color effect, and a static color
fadecolors=('\033[38;2;0;255;0m' '\033[38;2;0;192;0m' '\033[38;2;0;128;0m' '\033[38;2;0;64;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;16;0m' '\033[38;2;0;8;0m') # Fading green colors
static
color='\03338;2;0;0;0m' # Static dark green color
white_bold='\033[1;37m' # White and bold for the primary character

# Get terminal dimensions
COLUMNS=$(tput cols) # Number of columns in the terminal
ROWS=$(tput lines) # Number of rows in the terminal


# Hide the cursor for a cleaner effect and clear the screen
echo -ne '\033[?25l'
clear

# Function to generate a random character from the set of extra characters and extended ASCII
random_char() {
local chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789${extra_chars}${extended_ascii}"
echo -n "${chars:RANDOM%${#chars}:1}"
}

# Generate a list of 1000 random characters
random_chars=""
for (( i=0; i<1000; i++ )); do
random_chars+=$(random_char) # Add a random character to the end of the string
done

# Initialize a counter for cycling through the random characters
char_counter=0 # Counter for cycling through the random characters

# Initialize arrays to keep track of the position and trail characters of each column
positions=() # Array to store the current position in each column
trail_chars=() # Array to store the trail characters in each column
for (( c=1; c<=COLUMNS; c++ )); do
positions[$c=$((RANDOM % ROWS)) # Random starting position for each column
trailchars[$c]="" # Start with an empty trail for each column
done

# Function to update the display with the falling text effect
update
line() {
local lastpos=0 # Track the last position to optimize cursor movement

for (( c=1; c<=COLUMNS; c++ )); do
# Randomly skip updating some columns to create a dynamic effect
if [ $((RANDOM % 4)) -ne 0 ]; then
continue
fi

local new
char=${randomchars:$charcounter:1} # Select the next character from the random string
charcounter=$(( (charcounter + 1) % 1000 )) # Update the counter, cycling back after 1000

local pos=${positions$c} # Current position in this column
local trail=${trailchars[$c]} # Current trail of characters in this column

trail
chars$c="${newchar}${trail:0:$((ROWS - 1))}" # Update the trail by adding new character at the top

# Render the trail of characters
for (( i=0; i<${
#trail}; i++ )); do
local trail
pos=$((pos - i)) # Calculate the position for each character in the trail
if $trail_pos -ge 0 && $trail_pos -lt $ROWS ; then
local color=${fadecolors[i]:-$staticcolor} # Choose color from the fade array or static color if beyond the
Looking for assistance - Modifying Matrix code rain

I was wondering if anyone could help me figure this out.

Found this authored by derrick.blarg [Matrix Reimagined: Crafting Digital Rain with Bash and ChatGPT – Derrick.Blarg](https://derrick.blog/2023/12/29/matrix-reimagined-crafting-digital-rain-with-bash-and-chatgpt/)
Check out the article to find a preview.

I'd like to modify this a bit. In essence, I'd like to only loop it twice. That said, on the second loop in the center of the console, spell out a defined string variable with the rain as the loop is ending.

#!/bin/bash

# This noscript creates a Matrix-style falling text effect in the terminal.

# Define strings for extra characters (Japanese Katakana) and extended ASCII characters
extra_chars="カキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン"
extended_ascii="│┤┐└┴┬├─┼┘┌≡"

# Define arrays of color codes for a fading green color effect, and a static color
fade_colors=('\033[38;2;0;255;0m' '\033[38;2;0;192;0m' '\033[38;2;0;128;0m' '\033[38;2;0;64;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;32;0m' '\033[38;2;0;16;0m' '\033[38;2;0;8;0m') # Fading green colors
static_color='\033[38;2;0;0;0m' # Static dark green color
white_bold='\033[1;37m' # White and bold for the primary character

# Get terminal dimensions
COLUMNS=$(tput cols) # Number of columns in the terminal
ROWS=$(tput lines) # Number of rows in the terminal


# Hide the cursor for a cleaner effect and clear the screen
echo -ne '\033[?25l'
clear

# Function to generate a random character from the set of extra characters and extended ASCII
random_char() {
local chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789${extra_chars}${extended_ascii}"
echo -n "${chars:RANDOM%${#chars}:1}"
}

# Generate a list of 1000 random characters
random_chars=""
for (( i=0; i<1000; i++ )); do
random_chars+=$(random_char) # Add a random character to the end of the string
done

# Initialize a counter for cycling through the random characters
char_counter=0 # Counter for cycling through the random characters

# Initialize arrays to keep track of the position and trail characters of each column
positions=() # Array to store the current position in each column
trail_chars=() # Array to store the trail characters in each column
for (( c=1; c<=COLUMNS; c++ )); do
positions[$c]=$((RANDOM % ROWS)) # Random starting position for each column
trail_chars[$c]="" # Start with an empty trail for each column
done

# Function to update the display with the falling text effect
update_line() {
local last_pos=0 # Track the last position to optimize cursor movement

for (( c=1; c<=COLUMNS; c++ )); do
# Randomly skip updating some columns to create a dynamic effect
if [ $((RANDOM % 4)) -ne 0 ]; then
continue
fi

local new_char=${random_chars:$char_counter:1} # Select the next character from the random string
char_counter=$(( (char_counter + 1) % 1000 )) # Update the counter, cycling back after 1000

local pos=${positions[$c]} # Current position in this column
local trail=${trail_chars[$c]} # Current trail of characters in this column

trail_chars[$c]="${new_char}${trail:0:$((ROWS - 1))}" # Update the trail by adding new character at the top

# Render the trail of characters
for (( i=0; i<${#trail}; i++ )); do
local trail_pos=$((pos - i)) # Calculate the position for each character in the trail
if [ $trail_pos -ge 0 ] && [ $trail_pos -lt $ROWS ]; then
local color=${fade_colors[i]:-$static_color} # Choose color from the fade array or static color if beyond the
array
if [ $i -eq 0 ]; then
color=$white_bold # First character in the trail is white and bold
fi
if [ $last_pos -ne $trail_pos ]; then
printf "%b" "\033[${trail_pos};${c}H" # Move cursor to the right position
last_pos=$trail_pos
fi
printf "%b" "${color}${trail:$i:1}\033[0m" # Print the character with color
fi
done

positions[$c]=$((pos + 1)) # Update the position for the next cycle
if [ $pos -ge $((ROWS + ${#fade_colors[@]})) ]; then
positions[$c]=0 # Reset position if it moves off screen
trail_chars[$c]=""
fi
done
}

# Main loop for continuous execution of the update_line function
while true; do
update_line
done

# Reset terminal settings on exit (show cursor, clear screen, reset text format)
echo -ne '\033[?25h' # Show cursor
clear
tput sgr0 # Reset text format

&#x200B;

https://redd.it/1c42aov
@r_bash
Which characters (keys) are mostly used for bash language?

Looking to buy a new keyboard, so I would like to know if US international layout would be more useful than my primary language.

https://redd.it/1c4277m
@r_bash
Piped if-condition always returns true, how to fix?

This code uses a pipe in an if statement condition. Somehow, the condition always is true, even when grep doesn't find anything (aka returning 1).
Is this because the first command always returns 0? If so, how can I make sure that the condition is only considered true when all commands in the pipe return 0?

if VBoxManage list hdds | grep --quiet "$VM_NAME"; then
echo "VDI exsists"
else
echo "VDI does not exsist
fi


https://redd.it/1c4j8q0
@r_bash
Patchwork reminder app for bash

The last couple of weeks I refined a super-simple bash noscript starting from a nice `at` example usage.


I wrote more about it here https://blog.carlolobrano.com/posts/2024-04-07-patchwork-reminder-app-bash/

https://redd.it/1c4lpwd
@r_bash
HELP! Unable to run gcloud on git bash.

I have installed gcloud on my windows system, and its not recognizing the gcloud command somehow.

Its working fine when I am using powershell or CMD. What might be the issue.


One possible reason was the python or node version, but both are corrert

https://redd.it/1c5c8hg
@r_bash
Share Your Craft.

I want to upgrade my bash noscripting game. Would highly appreciate if you share what kind of noscript to you write for day to day task. So far I am using two noscript to open bunch of file, one for coding related programes, other one for chilling and gaming programe. I have another to download random wallpaper from the internet. What else I should do?

https://redd.it/1c5bwb0
@r_bash
Defining a function

Guys can someone please tell me what is the difference between
function main{
}
And
main(){
}

https://redd.it/1c5hmwz
@r_bash
Case statement

Does anyone know how to read blank values in case statement. For example

Echo "please enter a number"

Read number

Case $number in

1 ) echo "number is 1" ;;

2 ) echo "number is 2" ;;

*) echo "please enter a number" ;;

esac

What if the user does not input anything.
How do I read that

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