r_bash | Unsorted

Telegram-канал r_bash - r_bash

36

Credits: @r_channels & @reddit2telegram

Subscribe to a channel

r_bash

Issue command simultaneously to multiple servers ?

Hi,

I have the below code which loops through a set of server and get the IP addresses in range of 10.42.8 from it, then goes into each server in the IP and runs TSSI command.

function findworkers ()
{
knsw=$(kubectl get nodes -A -o name | grep worker)

for knodew in $knsw;
do
podres=$( echo $knodew | cut -c 6- )
echo "IP Addresses Found in $podres"
ssh -q $podres arp -n | grep 10.42.8 | grep ether | awk '{print $1}'
for rruaddr in $(ssh -q $podres arp -n | grep 10.42.8 | grep ether | awk '{print $1}')
do
ssh -q $podres ssh -q $rruaddr tssi
done
done
}

The output of the above command is as below.

IP Addresses Found in bai-ran-cluster-worker1
10.42.8.11
10.42.8.3
sh: tssi: not found
sh: tssi: not found

IP Addresses Found in bai-ran-cluster-worker2
10.42.8.30
10.42.8.24
TX 1 TSSI: 23.3428 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: 22.8387 dBm
TX 4 TSSI: -inf dBm
TX 1 TSSI: -8.8506 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: -10.0684 dBm
TX 4 TSSI: -inf dBm

What happens is it runs the TSSI all together for all the IP addresses found.

I'm unable to figure out how to run TSSI for each IP so the expected output is

IP Addresses Found in bai-ran-cluster-worker2
10.42.8.30
TX 1 TSSI: 23.3428 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: 22.8387 dBm
TX 4 TSSI: -inf dBm

10.42.8.24
TX 1 TSSI: -8.8506 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: -10.0684 dBm
TX 4 TSSI: -inf dBm

Any thoughts on how to write the loop for this ?

Thanks..

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

Читать полностью…

r_bash

Can someone please describe everything that happens in this syntax and why?



date '+%Y-%m-%d|whoami||a #' |whoami||a #|" |whoami||a # 2>&1

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

Читать полностью…

r_bash

Book technical reviewer needed

Hello,

I'm a security consultant and penetration tester. I'm writing a book titled "Bash Shell Scripting for Pentesters". My publisher needs book technical reviewers. From what I understand, the task is basically reading the chapters and checking that the code runs and the content is technically correct.

It doesn't pay, but they do print your name in the book as TR (and maybe short bio, not sure about that), you get a free copy of the book, and a 12 month subscription to Packt online with 12 free ebooks.

If you're interested, email AshwinK@packt.com and mention the name of the book.

If you do become a TR for my book, please keep the following in mind:

I have a limited amount of time and deadlines to turn in each chapter (and perform edits later), so don't uncessarily recommend adding content unless it just has to be there. It's more important to check that the content that's already there is correct, clear, and the code works.

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

Читать полностью…

r_bash

Log output of most recent command?

Hey guys, I am working on a cli co-pilot application utilizing chatgpt's api. I am relatively new to bash and to coding as a whole -- this is my first application of any sort of scale.

One of the features I would like to implement is an '--explain-last' flag. The basic functionality is to automatically send the most recent terminal output over to chatgpt to rapidly troubleshoot errors/other problems. Example:

error: ErrorNotFound
$ai --explain-last
This error occurs when you are writing a reddit post and can't think of an error to use as an example.

Although the app does have an interactive mode, this feature is its primary purpose (frankly, to help me learn bash more quickly).

Because terminal output is not stored anywhere on the system, I believe I will have to implement a background service to maintain a last_output.txt snapshot file which will be overwritten each time a new command is issued/output is generated. Because I never know when I will encounter a weird error, I want this process to be entirely frictionless and to integrate quietly behind the scenes.

What is the best way I should do this? Am I thinking about this problem correctly?

Thanks in advance!

Edit: Come to think of it, I will probably send over both the input and the output. Not relevant to this specific task that I am asking about, but maybe a bit more context.

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

Читать полностью…

r_bash

ETL automation testing with unix scripting!

Hi Everyone! What are some good free resources to learn unix scripting for ETL automation testing?

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

Читать полностью…

r_bash

First argument ($1) returning my username instead of what I assign it

Trying to pass an argument to a bash script in Cygwin. I kept getting erroneous results, so I started printing the first argument and assigning it to another variable and I see that no matter what I pass into my script the value of $1 is "USER=123456" where 123456 is my actual username and my home directory path is /home/123456 and my Winblows home dir is C:\\Users\\123456. I see the output of "set" has a line item "USER=123456" so it seems $1 is printing this set value. I'm not sure if this is specific to Cygwin or my bash configuration. Any suggestions?

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

Читать полностью…

r_bash

Merging multiple files into an array when there might not be a trailing \n

I have several text files that I would like to merge into a single array. This works:

arr=$( cat -s foo.txt bar.txt )

But!

When foo.txt (for example) doesn't have a blank line at the end, the first line of bar.txt is added to the last line of foo.txt.

Meaning:

# foo.txt
uno
dos

# bar.txt
tres
quatro

# arr=$( cat -s foo.txt bar.txt )
uno
dostres
quatro

I know that I can do this with multiple arrays, but this seems cumbersome and will be hard to read in the future:

fooArr=$( cat -s foo.txt )
barArr=$( cat -s bar.txt )
arr=( "${foo@}" "${bar@}")

Is there a better way to combine the files with one cat, AND make sure that the arrays are properly delimited?

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

Читать полностью…

r_bash

Adding spaces in the date command?

SOLVED. I just needed to add single quotes to the format. export day="$(date '+%a, %b %d, %Y')" Thank you for the replies.

I'd like to set `day` as a variable with the following format "Tue, Sep 17, 2024".

I found the codes: export day="$(date +%a, %b %d, %Y)", but I don't understand how to add the padding.

The man page mentions padding with underscores and zeros but I'm clearly not doing it correctly. Ex.: `echo $day -> Tue,0Sep017,02024` `echo $day -> Tue,_Sep_17,_2024`

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

Читать полностью…

r_bash

Dot files management and bashrc for different servers

So, I am trying to use gnu stow to install my dotfiles. This seems to work for most of my config, except for the .bashrc. Here I work with multiple servers and also with my laptop. Thus, I cannot use the same .bashrc for all of them. I am thinking of using multiple files like

.bashrc_s1
.bashrc_s2
...


and some sort of master bashrc with:

if [[ "$(hostname)" == "s1" ]];then
source .bashrc_s1
...
fi


is this a good approach? What have you out there tried and got it to work?

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

Читать полностью…

r_bash

Condition to remove ANSI characters in case of commands following a "|"

In my script I have some options that show colored messages.

If I prefix these with "> text.txt" or ">> text.txt" or a "| less" (by the way "less" is already included in these options), the output will also show the ANSI codes used.

I have already experimented with a filter using "sed", but who will unknowingly use the above symbols and commands, how will they have a "clean" output?

Is there a way to let the script know that one of the above characters or commands is in use?

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

Читать полностью…

r_bash

I need help I don't know why /home/minecraft doesn't include all the files

#!/bin/bash



# Defining variables

PROJECT_ID="alexuni2"

VM_NAME="minecraft-server"

DISK_NAME="minecraft-disk2"

IP_NAME="mc-server-ip"

NETWORK_NAME="minecraft-network"

REGION="us-central1"

ZONE="us-central1-a"

BUCKET_NAME="minecraft-backup"

MINECRAFT_DIRECTORY="/home/minecraft"

SERVER_JAR_URL="https://launcher.mojang.com/v1/objects/d0d0fe2b1dc6ab4c65554cb734270872b72dadd6/server.jar"



# Set the project ID for gcloud commands

gcloud config set project $PROJECT_ID



# Step 1: Create the VPC with automatic subnetting

echo "Creating VPC with automatic subnetting..."

gcloud compute networks create $NETWORK_NAME --subnet-mode=auto --project=$PROJECT_ID



echo "Creating Cloud Storage Bucket..."

gsutil mb -l $REGION -p $PROJECT_ID gs://$BUCKET_NAME/



# Step 2: Create a static external IP address

echo "Creating static external IP..."

gcloud compute addresses create $IP_NAME --region=$REGION --project=$PROJECT_ID



# Step 3: Create the VM Instance with a blank disk and external static IP

echo "Creating VM instance."

gcloud compute instances create $VM_NAME \\

--zone=$ZONE \\

--machine-type=e2-medium \\

--network=$NETWORK_NAME \\

--tags=minecraft-server \\

--boot-disk-size=10GB \\

--boot-disk-type=pd-ssd \\

--boot-disk-device-name=$DISK_NAME \\

--address=$IP_NAME \\

--no-service-account \\

--no-scopes \\

--metadata=startup-script-url=https://storage.googleapis.com/cloud-training/archinfra/mcserver/startup.sh,\\

shutdown-script-url=https://storage.googleapis.com/cloud-training/archinfra/mcserver/shutdown.sh \\



echo "Attaching additional 50 GB SSD disk..."

gcloud compute instances attach-disk $VM_NAME \\

--disk=$DISK_NAME \\

--zone=$ZONE \\

--project=$PROJECT_ID



# Step 4: Create the Firewall Rules

echo "Creating firewall rules..."

gcloud compute firewall-rules create minecraft-allow-ssh \\

--direction=INGRESS \\

--priority=1000 \\

--network=$NETWORK_NAME \\

--action=ALLOW \\

--rules=tcp:22 \\

--source-ranges=0.0.0.0/0 \\

--project=$PROJECT_ID



gcloud compute firewall-rules create minecraft-allow-internal \\

--direction=INGRESS \\

--priority=1000 \\

--network=$NETWORK_NAME \\

--action=ALLOW \\

--rules=all \\

--source-ranges=10.128.0.0/20 \\

--project=$PROJECT_ID



gcloud compute firewall-rules create minecraft-allow-icmp \\

--direction=INGRESS \\

--priority=1000 \\

--network=$NETWORK_NAME \\

--action=ALLOW \\

--rules=icmp \\

--source-ranges=0.0.0.0/0 \\

--project=$PROJECT_ID



gcloud compute firewall-rules create minecraft-rule \\

--direction=INGRESS \\

--priority=1000 \\

--network=$NETWORK_NAME \\

--action=ALLOW \\

--rules=tcp:25565 \\

--source-ranges=0.0.0.0/0 \\

--target-tags=minecraft-server \\

--project=$PROJECT_ID



# Step 5: SSH into the VM

echo "SSH into VM: gcloud compute ssh $VM_NAME --zone=$ZONE"



# Step 6: Format and Mount the Disk

echo "Mounting and formatting disk..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="sudo mkfs.ext4 -F -E lazy_itable_init=0,lazy_journal_init=0,discard /dev/disk/by-id/google-$DISK_NAME"

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="sudo mkdir -p $MINECRAFT_DIRECTORY"

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="sudo mount -o discard,defaults /dev/disk/by-id/google-$DISK_NAME $MINECRAFT_DIRECTORY"



# Verify the disk is mounted

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="df -h"



# Step 7: Install Java, Screen, and Other Packages

echo "Installing Java, screen, and wget..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="sudo apt-get update && sudo apt-get install -y openjdk-11-jre-headless screen wget"



# Step 8: Download Minecraft Server JAR

echo "Downloading Minecraft server JAR..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="cd $MINECRAFT_DIRECTORY && sudo wget $SERVER_JAR_URL"



# Step 9:

Читать полностью…

r_bash

Why is the output getting mixed up? I've done tons of troubleshooting but nothing has worked. I followed a script from a textbook so I expected it to just function, and not reverse the order of the numbers. I can tell it has to do with the third period but can't tell why or how.

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

Читать полностью…

r_bash

Guys, I need help with this assignment. No chat GPT
https://redd.it/1fgqcgg
@r_bash

Читать полностью…

r_bash

FOSS project is looking for BASH enthusiasts

https://preview.redd.it/lgbrquf1kkod1.png?width=996&format=png&auto=webp&s=1063d8906c4a2753b09e25c44568d386373b226f

We are excited to introduce the next generation of the Armbian Config tool! This redesigned and lightweight tool is central to managing single-board computers, offering a wide range of features for both hardware-specific and general system configuration.

# Key Advantages:

* Extremely lightweight with minimal dependencies
* Redesigned from scratch for better performance and flexibility
* JSON-based menu structure with options for TUI, CLI, or API

# Quick Recap

The `armbian-config` tool has been essential for configuring single-board computers, combining our long-term expertise in Linux and the embedded world. However, the old version had become bulky and difficult to maintain, prompting us to redesign it from the ground up. This new version offers better performance, flexibility, and robustness. We’re calling on the community to help test and complete it before the upcoming release!

You can help by installing the developer version for testing:

echo "deb [signed-by=/usr/share/keyrings/armbian.gpg] stable main" \
| sudo tee /etc/apt/sources.list.d/armbian-development.list > /dev/null
sudo apt update
sudo apt install armbian-configng
https://armbian.github.io/configng

Then, execute:

sudo armbian-configng

Check help with:

sudo bin/armbian-configng --help

*Note: This is a developer version meant for testing purposes only.*

# Users: We Need Your Feedback!

This tool is not yet production-ready, and we expect issues to arise. We encourage you to submit bug reports and feature requests as you encounter them. Our team will address these based on priority and feasibility.

* [**Submit Bug Report**](https://github.com/armbian/configng/issues/new?assignees=&labels=Bug&projects=&template=1-bugreport.yml&title=%5BBug%5D%3A+)
* [**Request a Feature**](https://github.com/armbian/configng/issues/new?assignees=&labels=Feature+Request&projects=&template=2-feature.yml&title=%5BFeature+Request%5D%3A+)

# Developers: Show your talent!

We’re looking for developers to contribute to this project! If you have skills in application design, function development, or code improvement, we’d love to have your input. This new tool has been completely redesigned, so it’s more than just copy-pasting from the old `armbian-config`.

As a token of our appreciation, contributors of non-trivial code will be entered into a draw to [win a mini PC or a high-end desktop workstation](https://www.armbian.com/newsflash/armbian-khadas-are-rewarding-contributors/). Stick around to help maintain the tool, and we can even discuss monthly compensation.

Head over to GitHub to contribute: [https://github.com/armbian/configng](https://github.com/armbian/configng)
Propose changes by opening a pull request!

Thank you for your support!

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

Читать полностью…

r_bash

I have about 100 function in my .bashrc. Should I convert them into scripts? Do they take unnecessary memory?

As per title. Actually I have a dedicated .bash_functions file that is sourced from .bashrc. Most of my custom functions are one liners.

Thanks.

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

Читать полностью…

r_bash

I created a bash script that sets bright color wallpapers during the day and dark color wallpapers during the night. Only requires a folder with wallpaper images as argument.
https://github.com/TimoKats/CircadianWallpaper

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

Читать полностью…

r_bash

yeet: A BPF tool for observing bash script activity.

You just install it and can SQL activity right out of the kernel.

yeet/execsnoop">yeet/execsnoop" rel="nofollow">https://yeet.cx/@yeet/execsnoop

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

Читать полностью…

r_bash

How does adding a new value to an array pass back to the caller?

Hello, I'm facing a problem when trying to implement an extension to some bash code.

Currently, a file is parsed for key/value pairs and they are collected as dynamic names with something like this in the end:

scopes+=("$current_scope")
variables+=("$variable")
values+=("$value")

At the end, in a different function, I iterate those arrays and collect my expected names.

The extension entails parsing some array and structures of strings, rather than only key/value.

I got to the point of internalising the parsed tokens and found out that I would be needing to eval the assignment, since (ignore the dumb quoting here):

"${arr_name}[$arr_idx]"="${arr_val}"

Can't be expanded at the correct time (Gives "unknown command" error, but copy-pasting the expansion printed in the error is accepted on an interactive shell).

This lead to this portion of my script were I expand the things only when they are in the expected format:

if [[ "$arr_var" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && [[ "$arr_val_idx" =~ ^[0-9]+$ ]]; then

# Safe assignment using eval after validation

eval "${arr_var}[$arr_val_idx]=\"$(printf '%q' "$arr_val")\""

And for structures, the same thing later:

if [[ "$struct_name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && [[ "$struct_var_name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then

# Safe assignment using eval after validation

eval "${struct_name}[$struct_var_name]=\"$(printf '%q' "$struct_val")\""


This seems fine, and at the end of my function I can try to read a test value:

mytry="${scope_foo[bar]}"
printf "TRY: {$mytry}\n"

This works as expected, and the value is there.

The issue arises from the fact that the definition seems to be local to the function where the eval happens.
If I put the previous test outside of the function doing the eval, it does not work.

My question is, why does the "scopes+=("thing")" works as expected after the assignign function returns, but the eval does not?

To test this behaviour, i tried:

myfn() {
arr=a; idx=0; val=foo;
eval "${arr}[$idx]=\"$(printf '%q' "$val")\""
}
$ myfn
$ echo ${a[0]}
>foo

This works as expected and the fact the function returns doesn't seems to matter, the value is there.

Can I get some guidance?

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

Читать полностью…

r_bash

How can I adjust my PS1 to have time on right side?

Hello,

I have a specific PS1 and I'd like to add a timestamp right adjusted on the right side of the terminal per new shell line. I can easily put \t or \T inline and it works fine but when I try to offset it with a function it blows up and doesn't work. it seems the function just runs once.


#Color codes
Reset="\[\e[0m\]"
Red="\[\e[0;31m\]"
Green="\[\e[0;32m\]"
Blue="\[\033[0;34m\]"
Yellow='\[\033[0;33m\]'

terraform_ws() {
#Check if .terraform/environment file exists and that we have a terraform executable.
if [ -f .terraform/environment ] && command -v terraform &> /dev/null; then
local workspace
workspace="$(< .terraform/environment)"
echo "[${Blue}$workspace${Reset}]"
fi
}

__kube_ps1() {
if command -v kubectl > /dev/null 2>&1; then
CONTEXT="$(kubectl config current-context | awk -F'/' '{print $NF}')"
if [ -n "$CONTEXT" ]; then
echo "(${Yellow}k8s:${CONTEXT}${Reset})"
fi
fi
}

ps1_pre_exec() {
# Make user@hostname in PS1 colorful. Red if non zero and green if zero.
if [ $? != 0 ]; then
echo "${Red}\u@\h${Reset} \w$(terraform_ws) $(__kube_ps1)"
else
echo "${Green}\u@\h${Reset} \w$(terraform_ws) $(__kube_ps1)"
fi
}

ps1_cursor() {
echo "\n${Yellow}> ${Reset}"
}

update_timestamp() {
local date_str=$(date +'%Y-%m-%d %H:%M:%S')
local date_len=${#date_str}
local term_width=$(tput cols)
printf "\e[${term_width}s\e[${term_width - ${date_len}}D${date_str}"
}

#Define PS1
PROMPT_DIRTRIM=2
PROMPT_COMMAND='__git_ps1 "$(ps1_pre_exec)" "$(update_timestamp) $(ps1_cursor)"'




all I get is the proper date printed out in the top right on the first go around of a login shell.

Note if I just put on \t where $(update_timestamp) is it works fine. Also PS1 cusor goes to another line and my actuall prompt looks like

eggman@eggman-2455 ~/.dotfiles/link (k8s:tacobell) (master %|u=) [02:50:51]
>


My goal is to have that timestamp on the far right away.

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

Читать полностью…

r_bash

GitHub - mdeacey/universal-os-detector: A Bash script for universal OS detection
https://github.com/mdeacey/universal-os-detector/

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

Читать полностью…

r_bash

Opinions sought regarding style: single vs. double quotes

I’m looking for style suggestions on single vs. double quoting. I am not asking about functionality (i.e. when is double quoting necessary). My current style is as follows:

var1=“${foo}/${bar}”
var2=‘this is a string’
var3=“foo’s bar”

All normal strings are single quoted (var1) unless they have an embedded single quote (var3), and all strings that need expansion are double quoted (var2).

This is consistent in my mind, but when I look at lots of bash scripts written by others, I see that they use double quotes almost exclusively. This is also correct and consistent. Note that I looked at some of my 10-20 year old scripts and in those days, I was using double quotes for everything.

Is there any good reason for using one style over another, or does personal preference rule?

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

Читать полностью…

r_bash

I need your opinions on scron (the code written in it)

https://github.com/omarafal/scron

I'm not exactly sure where to post this, I hope this is the right place as I need any feedback I can get on my bash scripting code.

So as the title suggests, I made a cli tool that basically uses cron for scheduling commands but adds a couple of things; logging for the scheduled commands and simplifies the date/time part of cron making it a bit more human-readable.

It's a mix of bash scripting and python but mostly bash scripting.

I want to emphasize that cron is already easy to use, the syntax is far from hard by a mile but some people (including myself) took a biiiit of some time to get the hang of it. So I made this in hopes that it would make scheduling commands a bit more easier and quicker I guess. It in no way replaces cron, if you want to make more complex "timing", use cron, this is called "simple cron" for a reason, to schedule things on the go.

Please do go a tiny bit easy on me lol, this is my first time doing something like this or even posting at all. I'm open to any suggestions, feedback, and comments.

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

Читать полностью…

r_bash

Cucking bored gibbme some linux command line homework

Like practical skills using bash scripts. Command line tools like find, awk, sed etc. And how am I supposed to learn about sed and awk? What book is best. I am currently in amazon.in and can't find any books lesser than 100$(equivalent).

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

Читать полностью…

r_bash

Bash script cannot run JavaScript file with top level await

I am trying to make a systemd timer that runs a script every 5 minutes for notifications to my phone based on an api, and I have successfully checked that the timer and the script work separately. For some reason, though, whenever I have the systemd timer point to the script.sh and run it, and if I do sudo systemctl status script.service, it provides an error: await is a reserved word. I suspect this is because it is a top level await, which for some reason bash can't do? The code it runs in the file is node ./script.js, and I have debugged everything I can think of. Even trying to put all of my code in an await function and then doing a then catch on it doesn't work.
Any help would be greatly appreciated, and if this is the wrong subreddit please let me know!

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

Читать полностью…

r_bash

init the server

echo "initialize the server..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="cd $MINECRAFT_DIRECTORY && sudo java -Xmx1024M -Xms1024M -jar server.jar nogui && \\

sudo chmod 777 eula.txt && \\

echo "eula=true" | sudo cat > eula.txt && \\"



# Step 10: Start the Minecraft Server in Screen

echo "Starting Minecraft server in a screen session..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="cd $MINECRAFT_DIRECTORY && sudo screen -dmS mcs java -Xmx1024M -Xms1024M -jar server.jar nogui && \\

sudo screen -d mcs && \\

sudo screen -r mcs"





# Step 11: Create Backup Script

echo "Creating backup script..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="sudo tee $MINECRAFT_DIRECTORY/backup.sh > /dev/null <<EOL

#!/bin/bash

screen -r mcs -X stuff '/save-all\\n/save-off\\n'

/usr/bin/gsutil cp -R ${BASH_SOURCE%/*}/world gs://$BUCKET_NAME-minecraft-backup/\\$(date '+%Y%m%d-%H%M%S')-world

screen -r mcs -X stuff '/save-on\\n'

EOL"



# Step 12: Make the Backup Script Executable

echo "Making backup script executable..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="sudo chmod +x $MINECRAFT_DIRECTORY/backup.sh"



# Step 13: Schedule Backup to Run Every 8 Hours

echo "Scheduling backups every 8 hours..."

gcloud compute ssh $VM_NAME --zone=$ZONE --project=$PROJECT_ID --command="(crontab -l 2>/dev/null; echo '0 */8 * * * $MINECRAFT_DIRECTORY/backup.sh') | crontab -"



echo "Minecraft server setup complete. Network, VM, disk, firewall, and backups are configured."



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

Читать полностью…

r_bash

How to check if background while loop exits early?

I have a bluetooth dmenu script that enables the service then prompts me to select devices to connect. I have my devices auto-connect when service is enabled. I want to make it smarter--when a device connects within 3 seconds (they usually auto-connect practically instantly), do not show prompt and quit the script early when device connects, else show it and continue on with script further prompting the user.

It seems I need a while loop in the background to start counting for the timeout, right? I have something like this:

# ... code to enable bluetooth

# background while loop
declare -i i=0 timeout=3

# quit loop early if there are connected devices
while (( i <= timeout )) || (( ${#devices_connected[@]} )); do
i+=1
sleep 1
done &

pid=$!

# ... code to get `devices_connected`, expected to run as soon as
# background while loop starts so it can start seeing connected devices

if wait "$pid" && (( i < 2)); then
echo "exit now"
exit
else
echo "continue with script"
fi

Is this even the right approach? The code doesn't work because `i` is modified within while loop so it value is not kept.

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

Читать полностью…

r_bash

If you pipe a list of files, what bash command do you pipe it to, for it to move those files to another directory?

E.g. ls | mv ... what?

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

Читать полностью…

r_bash

After "Hello World", I figured "MTU Test" would be a good second script
https://github.com/michealespinola/mtutest/blob/main/mtutest.sh

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

Читать полностью…

r_bash

Best Practices: Multiple spaces in a $(...) for readability

Let's say that I do this in an attempt to make it easier for me to read the script:

foo=$(nice -n 19 ionice -c 3 \
find /foo/ -maxdepth 1 -type f -exec du -b {} + | awk '{sum += $1} END {print sum}')

In case it doesn't post the way I typed it, there's a \\ followed by a line break, then 6 spaces on the second line to make it line up with the first line.

I'm not having an errors when I run it, but is this something that I should worry about becoming an error later on? I don't use bash that often, and I dread having an error in 3 or 4 years and having no idea why.

Not that most of you can see the future... I guess I'm just asking about "best practices" O:-)

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

Читать полностью…

r_bash

Script with Watch command shows unwanted characters ?

Hi,

I have a bash script that gives the below out.

SERVICE MNXT STATUS
enodebl2 [ RUNNING ]
l1run.sh RUNNING
l1appnbiot.sh [ STOPPED ]

When the script is run with `watch` command, the output show the below characters.

***** SERVICE MNXT STATUS ***** enodeb
l2 ^[1;32m RUNNING ^[0m l1run.sh [ ^[1;32m RUNNING ^[0m ] l1appnbiot.sh ^[1;31m STOPPED ^[0m

What is causing this, and how to get rid of them ?

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

Читать полностью…
Subscribe to a channel