r_bash – Telegram
Replace multiple lines with multiple lines?

Given the following input file:

text
text
pattern2
pattern3
text
text
pattern1
pattern2
pattern3
pattern2
pattern3
pattern2
pattern3
text
text

I need to search for "pattern1" and then I need to replace the first occurrence of "pattern2" and "pattern3" with "newpattern2" and "newpattern3" respectively and delete all other occurrences of "pattern2" and "pattern3". The end result I'm after is:

text
text
pattern2
pattern3
text
text
pattern1
newpattern2
newpattern3
text
text

At first I thought I could do this with sed by selecting a range of lines starting with "pattern1" and ending with "pattern3" and then using the c command to replace the whole range but range selecting in sed is non greedy so that won't work. However, I could still use sed to do the replacement but then need to figure out another way to delete all other occurances of "pattern2" and "pattern3" that come after "pattern1".

This is running in a busybox environment so no access to perl or most other fancy tools. Basically sed, awk, and grep are the only file/string manipulation tools I can think of that busybox supports.

https://redd.it/11dl5y0
@r_bash
call PHP Script via bash (instead of cronjob) recursively untill it is finished

How is this possible? At the Moment I am using cronjobs limited to one per min...

https://redd.it/11dkl5n
@r_bash
Q: Is there more then one bash implementations, and on what gcc/clang build targets can it not build?

Found the following article on a subreddit. In the article it claims.

> The chief advantage of Rust here is that it deftly sidesteps any conceivable problems with differing Bash implementations, and because Rust supports a wide range of build targets...

I'm not here to talk about rust vs bash.

But it feels the author is making untruthful claims about bash for example:

1. Is there different bash implementations(not shell)? or the user naively just mixing ash, bash, zsh, fish, etc?

2. Does rust support any build target you cannot build bash for?

Because last time i checked rustc it does not have great platform support except for tier 1, which is laughable compared to where bash can be executed.

If im naive or ignorent about the above topics please guide me in the right directions.

Thanks,

following article: https://determinate.systems/posts/determinate-nix-installer

https://redd.it/11dyr4f
@r_bash
Understanding coreutils fmt command

I don't completely understand why fmt works as it does. Let say we have this piece of text:

By default, blank lines, spaces between words, and indentation are preserved in the output;
successive input lines with different indentation are not joined; tabs are expanded on input and
introduced on output.

When I execute fmt -c <path/to/file_with_this_text> I expect third line indented as the second one but it doesn't happen. Why? While it happens documentation tells:

> Crown margin mode: preserve the indentation of the first two lines within a paragraph, and align the left margin of each subsequent line with that of the second line.

And what paragraph is here? Is it some block of text delimited by one empty lines or not?

https://redd.it/11e2s11
@r_bash
What is wrong with my lockfile?

So, my understanding of a lockfile is a simple file that's created to show that a noscript is running, and to abort any future executions of the noscript if the lockfile exists when they started.

The problem I'm facing is that I implemented a lockfile but when I left it to run, it appears to have ended all instances of my noscript. I came back to no noscripts running, the process incomplete, and the lockfile not being deleted.

Here's what I've written that concerns the lockfile.

At start of noscript:

if [ -f "$LOCKFILE" \]; then

echo "Instance already running. - Exiting"

exit 3

fi

downloaddate=$(date -Iseconds -u)

echo "Download in progress started $downloaddate." > "$LOCKFILE"

And at the end:

rm "$LOCKFILE"

https://redd.it/11e8b8a
@r_bash
Have section of jq a variable?

I have the following in a bash noscript:

jq -n --arg fullTitle "$2" \
--arg shortnoscript "$5" \
--arg speakerName "$7" \
--arg series "$saseries" \
--arg denoscription "$descr" \
--arg eventcategory "$eventcategory" \
--arg socialnoscript "$4" \
'{
"acceptCopyright": true,
"fullTitle": $fullTitle,
"displayTitle": $shortnoscript,
"speakerName": $speakerName,
"subnoscript": $series,
"moreInfoText": $denoscription,
"eventType": $eventcategory,
"socialSharing": [{
"platform": "twitter",
"message": "\"\( $socialnoscript )\"",
"useVideoClip": true
},
{
"platform": "facebook",
"message": "\"\( $socialnoscript )\"'\\n\\n'\( $denoscription )",
"useVideoClip": true
}],
"social_sharing_video_clip": {
"start": 0.0,
"end": 120.0
}
}' \
> $SADATA

I'm looking to have this section completely disappear under certain circumstances:

{
"platform": "twitter",
"message": "\"\( $socialnoscript )\"",
"useVideoClip": true
},

I was thinking that I should somehow make this a variable so that it can go from:

"socialSharing": [{
"platform": "twitter",
"message": "\"\( $socialnoscript )\"",
"useVideoClip": true
},
{
"platform": "facebook",
"message": "\"\( $socialnoscript )\"'\\n\\n'\( $denoscription )",
"useVideoClip": true
}],
"social_sharing_video_clip": {
"start": 0.0,
"end": 120.0
}

to:

"socialSharing": [{
"platform": "facebook",
"message": "\"\( $socialnoscript )\"'\\n\\n'\( $denoscription )",
"useVideoClip": true
}],
"social_sharing_video_clip": {
"start": 0.0,
"end": 120.0
}

How can I do this, or is there a better way than making a section of jq a variable?

https://redd.it/11eiplh
@r_bash
Need progress bar in wget or use curl for large file

I'm in a pickle. Originally, I was using curl in my noscript to upload (see bottom for uploading command):

#!/bin/bash

SRVPATH=/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162
MEDIA_DIR=$SRVPATH/Archive/2023
MEDIA_FILENAME=2023-02-28_11-04-23.mp4
MEDIA_PATH="${MEDIA_DIR}/${MEDIA_FILENAME}"

ENDPOINT="https://api.website.com/v2/media"

JSON="{
\"ID\": \"22823239276459\",
\"uploadType\": \"original-video\",
\"originalFilename\": \"${MEDIA_FILENAME}\"
}
"

UPLOAD_RESPONSE=$(
curl -s \
-H "X-API-Key: <myAPIKEY>" \
-H "Content-Type: application/json" \
-X POST \
-d "$JSON" \
$ENDPOINT
)

GET_URL_SNIPPET="
import json
import sys
print(json.loads(sys.stdin.read())['uploadURL'])
"

URL=$(echo $UPLOAD_RESPONSE | python -c "$GET_URL_SNIPPET" )

echo $URL

curl --progress-bar \
-H "X-API-Key: ${API_KEY}" \
-X POST \
--data-binary "@$MEDIA_PATH" \
$URL \
|& cat

Everything worked great when uploading a small mp4 and I could see the progress bar moving along. When I go to upload a large mp4, say, 2.3 GB on my 2 GB RAM system, I get `curl: option --data-binary: out of memory`. Using `-T` resulted in `405: Method Not Allowed` and using Using `-F` resulted in `File must be uploaded as HTTP body`.

Enter wget:

wget --header "X-API-Key: ${API_KEY}" --post-file $MEDIA_PATH $URL

#instead of

curl --progress-bar \
-H "X-API-Key: ${API_KEY}" \
-X POST \
--data-binary "@$MEDIA_PATH" \
$URL \
|& cat

Works to upload a large file. But I have tried:

wget --header "X-API-Key: ${API_KEY}" --show-progress --upload-file $MEDIA_PATH $URL
wget --header "X-API-Key: ${API_KEY}" --progress=bar --upload-file $MEDIA_PATH $URL
wget --header "X-API-Key: ${API_KEY}" --progress=bar:force --post-file $MEDIA_PATH $URL
wget --header "X-API-Key: ${API_KEY}" --progress=dot --post-file $MEDIA_PATH $URL
wget --header "X-API-Key: ${API_KEY}" --progress=dot:mega --post-file $MEDIA_PATH $URL
wget -v --header "X-API-Key: ${API_KEY}" --post-file $MEDIA_PATH $URL

And none of these will show the progress bar while the file is uploading. I can see the progress bar AFTER the file is uploaded:

https://upload.website.com/path
--2023-02-28 19:23:03-- https://upload.website.com/path
Resolving upload.website.com (upload.website.com)... 12.345.678.912
Connecting to upload.website.com (upload.website.com)|12.345.678.912|:443... connected.

And then after it's finished uploading:

HTTP request sent, awaiting response... 201 Created
Length: 94 [text/plain]
Saving to: ‘path’

path 100%[=================================================================>] 94 --.-KB/s in 0s

2023-02-28 19:23:48 (3.34 MB/s) - ‘path’ saved [94/94]

Am I SOL and have to settle for no progress bar? I'm looking for either a way to use curl to upload a large file, or wget to show the progress bar.

https://redd.it/11eo8vp
@r_bash
Multiple conditions help

Hi everyone. I would like to apologize in advance. I am only a beginner and I have to learn bash for a class that I'm doing. I'm not here to get answers, of course. I'm here to understand what I'm doing and learn from my mistakes.

This is currently what I have written out. I do not know what to do with multiple conditions, so I just wrote out a bunch of elifs. This obviously did not work and now I don't know what to do.

\#!/bin/bash

read -p "Please enter shipping weight: " var

echo "Your number is $var"

if [ "$var" -le 2 \]

then

echo "Price is 1.10"

elif [ "$var" -ge \] && [ 2 "$var" -le 5 \]

then

echo "Price is 2.20"

elif [ "$var" -ge 6 \] && [ "$var" -le 10 \]

then

echo "Price is 3.70"

elif [ "$var" -ge 10 \]

then

echo "Price is 3.80"

fi

&#x200B;

The actual question for my homework in question, purely for context of what I'm supposed to be doing:

&#x200B;

Just for context.

https://redd.it/11evq69
@r_bash
Help with regular expressions

I have downloaded some videos but the program used for downloading has appended some random string in brackets at the end of the filename. I want to remove that random string. I tried renaming the files using:

❯ mmv -n '* [*] .mp4' '#1.mp4'

* [*] .mp4 -> #1.mp4 : no match.

Nothing done.

I believe that what I'm writing means "match whatever (and a blank space) up to the first opening bracket, then match whatever again up to first closing bracket and finally match a blankspace and the .mp4 extension. Replace all that with just the first whatever-matching.:

This however returns a "no match" error.

Perhaps this has something to do with the fact that the names of the files are pretty obscure. They are greek characters and contain a lot of white spaces, so perhaps it needs more precise handling. However, I'm not sure. This is the output of the "ls -a" command.

❯ ls -a

.

..

'2021 03 04 15 37 53 [JdSDGDNC2Uo].mp4'

'2η Ενισχυτική Matlab 2021 03 23 18 46 58 [lfzYHsF0QVc].mp4'

'2η ενισχυτική εξάσκηση σε MATLAB [TLuW6SK3XCc].mp4'

'Απεικονιση1 2021 02 25 [mUEzmJWkPKk].mp4'

'Ιατρική Απεικόνιση 11 3 [puElBwRAXxU].mp4'

'Ιατρική Απεικόνιση 18 3 [xJKXG5RcaQ0].mp4'

Any help is well appreciated. Feel free to ask for clarifications.

https://redd.it/11f0g8p
@r_bash
Janitor V1 | Tronnoscript for Linux

Here's what I've got.
It's supposed to behave similar to Tronnoscript for Windows, but it stops after the very first task.

I put it together using ChatGPT because I don't know what I'm doing. I'm starting to understand how this works, but I need some help.

Are you guys able to help me spot where I'm going wrong?

#!/bin/bash



# Create an array of tasks with corresponding flags



tasks=("Update system" "Clean up temporary files" "Check for ClamAV malware" "Check for rkhunter malware" "Remove old log files" "Check and repair file system errors" "Clean up apt cache" "Clear system memory cache" "Optimize disk usage" "Reboot if needed")



flags=(-s -c -v -r -l -f -a -m -o -b)



# Display a checklist of tasks to the user and prompt for input



echo "Please select which tasks to run by entering the corresponding flags:"



echo ""



for (( i=0; i<${#tasks@}; i++ )); do



echo " ${flagsi} - ${tasksi}"



done



echo ""



# Read user input and set corresponding variables



read -p "Enter task flags (default=all): " inputtasks



input
tasks=${inputtasks:-"all"}



# Check for invalid task flags



for flag in $(echo $input
tasks | tr "," " "); do



if [ ! "${flags[@}" =~ "${flag}" && $flag != "all" ]]; then



echo "Error: Invalid task flag: $flag"



exit 1



fi



done



# Set variables based on user input

systemupdate=false

clean
tempfiles=false

clamav
scan=false

rkhunterscan=false

remove
logs=false

checkfilesystem=false

cleanaptcache=false

clearmemorycache=false

optimizediskusage=false

rebootifneeded=false



IFS=',' read -ra taskflags <<< "$inputtasks"

for flag in "${taskflags[@]}"; do

case "$flag" in

-s|all) system
update=true;;

-c|all) cleantempfiles=true;;

-v|all) clamavscan=true;;

-r|all) rkhunter
scan=true;;

-l|all) removelogs=true;;

-f|all) check
filesystem=true;;

-a|all) clean
aptcache=true;;

-m|all) clear
memorycache=true;;

-o|all) optimize
diskusage=true;;

-b|all) reboot
ifneeded=true;;

*) echo "Error: Invalid task flag: $flag"; exit 1;;

esac

done



# Step 1: System update

system
updatefunc() {

echo "Updating system..."

sudo apt update && sudo apt upgrade -y

echo "System updated."

wait

}



# Step 2: Clean temp files

clean
tempfilesfunc() {

echo "Cleaning temp files..."

sudo rm -rf /tmp/

sudo rm -rf /var/tmp/

echo "Temp files cleaned."

}



# Step 3: Check and install/update ClamAV

clamavscanfunc() {

echo "Checking ClamAV..."

if ! command -v clamscan &> /dev/null

then

echo "ClamAV not found. Installing ClamAV..."

sudo apt install clamav -y

else

echo "ClamAV found. Updating ClamAV..."

sudo freshclam

fi



echo "Running ClamAV scan..."

sudo clamscan -r / --exclude-dir=/sys/fs/cgroup --exclude-dir=/run/media --exclude-dir=/proc

if ! command -v clamscan &> /dev/null

then

echo "ClamAV was not initially installed. Uninstalling ClamAV..."

sudo apt remove clamav -y

fi

}



# Step 4: Check and install/update rkhunter

rkhunterscanfunc() {

echo "Checking rkhunter..."
Janitor V1 | Tronnoscript for Linux

Here's what I've got.
It's *supposed* to behave similar to Tronnoscript for Windows, but it stops after the very first task.

I put it together using ChatGPT because I don't know what I'm doing. I'm starting to understand how this works, but I need some help.

Are you guys able to help me spot where I'm going wrong?

#!/bin/bash



# Create an array of tasks with corresponding flags



tasks=("Update system" "Clean up temporary files" "Check for ClamAV malware" "Check for rkhunter malware" "Remove old log files" "Check and repair file system errors" "Clean up apt cache" "Clear system memory cache" "Optimize disk usage" "Reboot if needed")



flags=(-s -c -v -r -l -f -a -m -o -b)



# Display a checklist of tasks to the user and prompt for input



echo "Please select which tasks to run by entering the corresponding flags:"



echo ""



for (( i=0; i<${#tasks[@]}; i++ )); do



echo " ${flags[i]} - ${tasks[i]}"



done



echo ""



# Read user input and set corresponding variables



read -p "Enter task flags (default=all): " input_tasks



input_tasks=${input_tasks:-"all"}



# Check for invalid task flags



for flag in $(echo $input_tasks | tr "," " "); do



if [[ ! "${flags[@]}" =~ "${flag}" && $flag != "all" ]]; then



echo "Error: Invalid task flag: $flag"



exit 1



fi



done



# Set variables based on user input

system_update=false

clean_temp_files=false

clamav_scan=false

rkhunter_scan=false

remove_logs=false

check_file_system=false

clean_apt_cache=false

clear_memory_cache=false

optimize_disk_usage=false

reboot_if_needed=false



IFS=',' read -ra task_flags <<< "$input_tasks"

for flag in "${task_flags[@]}"; do

case "$flag" in

-s|all) system_update=true;;

-c|all) clean_temp_files=true;;

-v|all) clamav_scan=true;;

-r|all) rkhunter_scan=true;;

-l|all) remove_logs=true;;

-f|all) check_file_system=true;;

-a|all) clean_apt_cache=true;;

-m|all) clear_memory_cache=true;;

-o|all) optimize_disk_usage=true;;

-b|all) reboot_if_needed=true;;

*) echo "Error: Invalid task flag: $flag"; exit 1;;

esac

done



# Step 1: System update

system_update_func() {

echo "Updating system..."

sudo apt update && sudo apt upgrade -y

echo "System updated."

wait

}



# Step 2: Clean temp files

clean_temp_files_func() {

echo "Cleaning temp files..."

sudo rm -rf /tmp/*

sudo rm -rf /var/tmp/*

echo "Temp files cleaned."

}



# Step 3: Check and install/update ClamAV

clamav_scan_func() {

echo "Checking ClamAV..."

if ! command -v clamscan &> /dev/null

then

echo "ClamAV not found. Installing ClamAV..."

sudo apt install clamav -y

else

echo "ClamAV found. Updating ClamAV..."

sudo freshclam

fi



echo "Running ClamAV scan..."

sudo clamscan -r / --exclude-dir=/sys/fs/cgroup --exclude-dir=/run/media --exclude-dir=/proc

if ! command -v clamscan &> /dev/null

then

echo "ClamAV was not initially installed. Uninstalling ClamAV..."

sudo apt remove clamav -y

fi

}



# Step 4: Check and install/update rkhunter

rkhunter_scan_func() {

echo "Checking rkhunter..."
if ! command -v rkhunter &> /dev/null

then

echo "rkhunter not found. Installing rkhunter..."

sudo apt install rkhunter -y

sudo rkhunter --update

else

echo "rkhunter found. Updating rkhunter..."

sudo rkhunter --update

fi



echo "Running rkhunter scan..."

sudo rkhunter --check

if ! command -v rkhunter &> /dev/null

then

echo "rkhunter was not initially installed. Uninstalling rkhunter..."

sudo apt remove rkhunter -y

fi

}



# Step 5: Remove logs

remove_logs_func() {

echo "Removing logs..."

sudo find /var/log -type f -delete

sudo find /var/log -type f -iname *.gz -delete

echo "Logs removed."

}



# Step 6: Check file system

check_file_system_func() {

echo "Checking file system..."

sudo fsck -Af -M

echo "File system check completed."

}



# Step 7: Clear apt cache

clean_apt_cache_func() {

echo "Clearing apt cache..."

sudo apt clean

echo "Apt cache cleared."

}



# Step 8: Clear memory cache

clear_memory_cache_func() {

echo "Clearing memory cache..."

sudo sync && sudo echo 3 | sudo tee /proc/sys/vm/drop_caches

echo "Memory cache cleared."

}



# Step 9: Optimize disk usage

optimize_disk_usage_func() {

echo "Optimizing disk usage..."

sudo fstrim -v /

echo "Disk usage optimized."

}



# Step 10: Reboot if needed

reboot_if_needed_func() {

if [ -f /var/run/reboot-required ]; then

echo "Reboot required. Rebooting now..."

sudo reboot

else

echo "No reboot required."

fi

}



# Execute selected tasks

echo "Executing selected tasks..."



if [ "$system_update" = true ]; then

echo "Updating system packages..."

system_update_func

fi



if [ "$clean_temp_files" = true ]; then

echo "Cleaning up temporary files..."

clean_temp_files_func

fi



if [ "$clamav_scan" = true ]; then

echo "Checking for ClamAV malware..."

clamav_scan_func

fi



if [ "$rkhunter_scan" = true ]; then

echo "Checking for rkhunter malware..."

rkhunter_scan_func

fi



if [ "$remove_logs" = true ]; then

echo "Removing old log files..."

remove_logs_func

fi



if [ "$check_file_system" = true ]; then

echo "Checking and repairing file system errors..."

check_file_system_func

fi



if [ "$clean_apt_cache" = true ]; then

echo "Cleaning up apt cache..."

clean_apt_cache_func

fi



if [ "$clear_memory_cache" = true ]; then

echo "Clearing system memory cache..."

clear_memory_cache_func

fi



if [ "$optimize_disk_usage" = true ]; then

echo "Optimizing disk usage..."

optimize_disk_usage_func

fi



echo "Done."

https://redd.it/11fkp5r
@r_bash
Basic scope question

Hello. I am relatively new to bash and ran into a stupid newb issue dealing with variable scope.

The noscript I was writing sets up several environment-related things depending on the machine’s role.

The idea is that I’d source a ‘common’ environment, and then depending on the machine I’d run source other noscripts specific to their role.

Where I went wrong was that I reused variable several variable names from my main noscript in each of the environments. So when I went from the ‘common’ environment setup and on to the contextual environment setup it carried along with it the modified variables leading to side effects.

I really did not want to have to come up with new variable names for variables that were essentially doing the same thing, just in different contexts, so instead I just wrapped each noscript into a function and made each variable local.

This worked, but is this the ‘correct’ way? Is there a more concise way to ensure variable stay put?

https://redd.it/11fq49x
@r_bash
Here you are useifytech

Hello, too much to post in a comment I guess.

Use diff, between my version, and yours.

You'll want to remove the test code I added to see too that the menu system now runs in a while loop, or change the text, and maybe the flags at least.

You'd really want to make it able to handle command line flags as well, and just run through the noscript without showing any menus.
Left as an exercise to you!

#!/bin/bash

# Create an array of tasks with corresponding flags

tasks=("Update system" "Clean up temporary files" "Check for malware (ClamAv)" "Check for rootkits, backdoors and possible local exploits (rkhunter)" "Remove old log files" "Check and repair file system errors" "Clean up apt cache" "Clear system memory cache" "Optimize disk usage" "Reboot (if needed)" "Loop test" "Quit Janitor V1")

flags=(-s -c -v -r -l -f -a -m -o -b t q)



# Step 1: System update
system_update_func() {
echo "Updating system..."
sudo apt update && sudo apt upgrade -y
echo "System updated."
wait
}

# Step 2: Clean temp files
clean_temp_files_func() {
echo "Cleaning temp files..."
sudo rm -rf /tmp/*
sudo rm -rf /var/tmp/*
echo "Temp files cleaned."
}

# Step 3: Check and install/update ClamAV
clamav_scan_func() {
echo "Checking ClamAV..."
if ! command -v clamscan &> /dev/null
then
echo "ClamAV not found. Installing ClamAV..."
sudo apt install clamav -y
else
echo "ClamAV found. Updating ClamAV..."
sudo freshclam
fi

echo "Running ClamAV scan..."
sudo clamscan -r / --exclude-dir=/sys/fs/cgroup --exclude-dir=/run/media --exclude-dir=/proc
if ! command -v clamscan &> /dev/null
then
echo "ClamAV was not initially installed. Uninstalling ClamAV..."
sudo apt remove clamav -y
fi
}

# Step 4: Check and install/update rkhunter
rkhunter_scan_func() {
echo "Checking rkhunter..."
if ! command -v rkhunter &> /dev/null
then
echo "rkhunter not found. Installing rkhunter..."
sudo apt install rkhunter -y
sudo rkhunter --update
else
echo "rkhunter found. Updating rkhunter..."
sudo rkhunter --update
fi

echo "Running rkhunter scan..."
sudo rkhunter --check
if ! command -v rkhunter &> /dev/null
then
echo "rkhunter was not initially installed. Uninstalling rkhunter..."
sudo apt remove rkhunter -y
fi
}

# Step 5: Remove logs
remove_logs_func() {
echo "Removing logs..."
sudo find /var/log -type f -delete
sudo find /var/log -type f -iname *.gz -delete
echo "Logs removed."
}

# Step 6: Check file system
check_file_system_func() {
echo "Checking file system..."
sudo fsck -Af -M
echo "File system check completed."
}

# Step 7: Clear apt cache
clean_apt_cache_func() {
echo "Clearing apt cache..."
sudo apt clean
echo "Apt cache cleared."
}

# Step 8: Clear memory cache
clear_memory_cache_func() {
echo "Clearing memory cache..."
sudo sync && sudo echo 3 | sudo tee /proc/sys/vm/drop_caches
echo "Memory cache cleared."
}

# Step 9: Optimize disk usage
optimize_disk_usage_func() {
echo "Optimizing disk usage..."
sudo fstrim -v /
echo "Disk usage optimized."
}

# Step 10: Reboot if needed
reboot_if_needed_func() {
if [ -f /var/run/reboot-required ]; then
echo "Reboot required. Rebooting now..."
sudo reboot
else
echo "No reboot required."
fi
}
while true; do
# Display a checklist of tasks to the user and prompt for input

echo "Please select which tasks to run by entering the corresponding flags:"

echo ""

for (( i=0; i<${#tasks[@]}; i++ )); do

echo " ${flags[i]} -
${tasks[i]}"

done

echo ""

# Read user input and set corresponding variables

read -p "Enter task flags (default=all): " input_tasks

input_tasks=${input_tasks:-"all"}

# Check for invalid task flags

for flag in $(echo $input_tasks | tr "," " "); do

if [[ ! "${flags[@]}" =~ "${flag}" && $flag != "all" ]]; then

echo "Error: Invalid task flag: $flag"

exit 1

fi

done

# Set variables based on user input
errthang=false
system_update=false
clean_temp_files=false
clamav_scan=false
rkhunter_scan=false
remove_logs=false
check_file_system=false
clean_apt_cache=false
clear_memory_cache=false
optimize_disk_usage=false
reboot_if_needed=false

IFS=',' read -ra task_flags <<< "$input_tasks"
for flag in "${task_flags[@]}"; do
case "$flag" in
all) errthang=true;;
-s|all) system_update=true;;
-c|all) clean_temp_files=true;;
-v|all) clamav_scan=true;;
-r|all) rkhunter_scan=true;;
-l|all) remove_logs=true;;
-f|all) check_file_system=true;;
-a|all) clean_apt_cache=true;;
-m|all) clear_memory_cache=true;;
-o|all) optimize_disk_usage=true;;
-b|all) reboot_if_needed=true;;
t ) continue ;;
q ) break 2 ;;
*) echo "Error: Invalid task flag: $flag"; exit 1;;
esac
done

#Verbose
# set -x
# Execute selected tasks
echo "Executing selected tasks..."

if [ "$errthang" = true ]; then
echo "Updating system packages..."
system_update_func
wait
clean_temp_files_func
wait
clamav_scan_func
wait
rkhunter_scan_func
wait
remove_logs_func
wait
check_file_system_func
wait
clean_apt_cache_func
wait
clear_memory_cache_func
wait
optimize_disk_usage_func
fi

if [ "$system_update" = true ]; then
echo "Updating system packages..."
system_update_func
fi

if [ "$clean_temp_files" = true ]; then
echo "Cleaning up temporary files..."
clean_temp_files_func
fi

if [ "$clamav_scan" = true ]; then
echo "Checking for ClamAV malware..."
clamav_scan_func
fi

if [ "$rkhunter_scan" = true ]; then
echo "Checking for rkhunter malware..."
rkhunter_scan_func
fi
if [ "$remove_logs" = true ]; then
echo "Removing old log files..."
remove_logs_func
fi

if [ "$check_file_system" = true ]; then
echo "Checking and repairing file system errors..."
check_file_system_func
fi

if [ "$clean_apt_cache" = true ]; then
echo "Cleaning up apt cache..."
clean_apt_cache_func
fi

if [ "$clear_memory_cache" = true ]; then
echo "Clearing system memory cache..."
clear_memory_cache_func
fi

if [ "$optimize_disk_usage" = true ]; then
echo "Optimizing disk usage..."
optimize_disk_usage_func
fi
# set +x
clear
done
echo "Done."

https://redd.it/11g142q
@r_bash
I've implemented working parser in Bash + Sed from the ground and wrote unit tests for it

It allows to extract command name, denoscription, tags, tokens for code examples and their denoscriptions.

Here is my implementation. It works straightforward: parser validates page layout and checks more details user requests for. For instance if I wanna get some tag from page (to get link to the official tool documentation) parser will check not just layout, but also whether written tags are right.

And that's how it looks like right now:


https://preview.redd.it/pgngxz09jbla1.png?width=1587&format=png&auto=webp&v=enabled&s=e3e8160086d637375dd55fd8c85408c60fddf93f

In other words I've proved myself that it's possible to right some cool stuff in Bash and Sed. ;)

https://redd.it/11g1b5q
@r_bash
zentest, small simple solution for testing code.

ZENTEST
-------

### Overview

A minimal test setup, that is taken out of a larger context.
There are so many ways to perform tests, I needed one I
could use standalone, in a loop like so:

for f in fileA FileB fileC ; do
.git/test-runner.sh $f > logs/$f-$(date +%s).log
done

I can also invoke the tests from my build Makefile in a
rule like so:

fileA:
shellcheck -xe $@
.git-test-runner.sh $@

Or, I can call it up from my .git precommit hook, if it fits
the bill, file name wise, that a file that is under testing,
is about to be committed.

### Organization

Everything is initiated/executed with the project root, as
the current working directory $PWD.

Every source file, that is to be tested, has its own little
makefile with the different tests. The make in use is
GNUmake, so that the .ONESHELL directive works, so that you
can yourself decide if the test passes or fails, in fact,
every rule in the makefile will work as a little shell
noscript. (Otherwise every commandline in a makefile is executed in its own shell.)

In project root, we have a workdir directory, which holds
temporary project files, and a tests directory, that
contains all the small makefiles, and what else of files,
that are needed to perform the tests in the makefiles.


The test-runner.sh is a very simple noscript, that only
figures out the correct makefile to run from the test/
directory. It bails if it doesn't find a suitable makefile,
I plan to make a copy of my template-makefile then, and open
it in $EDITOR.

### What is left out here:

The error messages, I like to get the errors into a format
that I can load into a quick fix list in Vim, so when my
tests fails, I deliver errors in the unix error format.
That is outside of the scope here, but easy to implement!

### "Source code".


#!/bin/bash
# Preliminaries: output is redirected up front to $TESTERRORS
# Context: We are executed from the root of our project, i.e. right
# inside the directory that contains the project.
# We have a "tests" folder within the project directory, that contains
# makefiles, one for every file that is to be tested.
# each makefile is named as the same as the file in question,
# which means that every file of your project, that is to be tested
# needs to have a unique stem name.

PNAME="${0##/}"
if [[ $# -ne 1 ]] ; then
echo -e "
$PNAME : I need a file name to test\nTerminating..."
exit 2
fi

if [[ "${1}" != "${1/.//}" ]] ; then
makefname="$( basename "${1}" "${1#
.}")"mk
else
makefname="${1}".mk
fi


if [ ! -r tests/"$makefname" ] ; then
echo -e "$PNAME : tests/$makefname doesn't exist.\nCan't test ${1}!\
\nTerminating..."
exit 2
else
make -f tests/"$makefname"
exit $?
fi

The makefiles is equally simple, below is a simple template.
makefile. Here is a small superb make
tutorial


.ONESHELL:
all: ./workdir/step3 clean

./workdir/step1:
@noscript1 ./workdir/step1
touch ./workdir/step1

./workdir/step2: ./workdir/step1
@noscript1 ./workdir/step2
touch ./workdir/step2
exit 1

./workdir/step3: ./workdir/step2
@noscript1 ./workdir/step3
touch ./workdir/step3


clean:
rm ./workdir/step1 ./workdir/step2 ./workdir/step3

Last updated:23-03-02 15:06

https://redd.it/11g3mnv
@r_bash
My cat entered the following into git bash and it put my editor into some sort've other commandline

p[-0.4kjmn.cf yy;bknmg#f'g 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9Function Key 9OAFunction Key 9i

Typing in p[ seems to trigger it but I don't know what it is, any ideas?

https://redd.it/11g7uma
@r_bash
Diff 2 Files Without Knowing Exact Names

I want to diff two files, but I do not know the exact names.

The use case is, we are using DevOps pipelines that download a pre and post configuration file.

I would know what the files start with but the ending will be a date time string that I would not know.

Looking for help with a noscript that finds the files and does a diff of the later version vs the earlier version.

Names would be something like this:

name20230302T142605
name
20230302T142803

Any thoughts on how to do this?

https://redd.it/11gauho
@r_bash