r_bash – Telegram
Explanation of sed Command

I was wondering if someone could explain the following sed command:

sed --in-place '/text1/{n; s/text2/text3/}' file.txt

It's supposed to replace text2 with text3 but only if it is on a line following a line that contains text1. I get the /text1/ portion which is supposed to select lines with text1 in them. What I can't seem to find an explanation for is why curly braces are used and what n; inside those braces does to make this command only act on a line that follows a line containing text1.

https://redd.it/11d1k3v
@r_bash
How can i check if a file exists with a certain extension

I need to check if a file exists with a specific extension. Like file.chd specifically. However [ -f $file.chd ] doesn't work for example. There are other files of the same name with a different extension that the -f option picks up instead. How should i do this

https://redd.it/11da7sx
@r_bash
where did I go wrong here in my code?

I took an assesment for a job through HackerRank and got this one wrong and I cant go back and look at the actual assesment anymore but its "GRINDING MY GEARS" like Peter Griffin that I got this wrong.

Problem Statement:

complete function mort_calc given the loan amount annual interest and period of loan years, you need to calculate the monthly payment. the loan amount is principle. the annual interest can be converted into normal percent interest per month

#!/bin/bash

mortgagecalculator() {
principal=$1
annual
interestrate=$2
years=$3

# Calculate the monthly interest rate
monthly
interestrate=$(echo "scale=8; $principal + $annualinterestrate + $years" | bc -l)

# Return the monthly payment
echo "$monthly
payment"
}

# sample input
principal=300000
annualinterestrate=0.0375
years=30

# call the function
monthlypayment=$(echo "$principal + $annualinterestrate + $years" | bc)

result=$(printf "%.2f" $monthly
payment)

# output
echo $result
# output: 1389.23


this code is not outputting what its supposed to be down there at the bottom, I cant find where my calculations went wrong.

Thanx in advance ya'll

https://redd.it/11db80x
@r_bash
help noscript is not functioning properly

So here's some of the function of my setup noscript
#!/usr/bin/env bash
# set -x

base_url="https://raw.githubusercontent.com/lime-desu/dootsfile/main"

declare -A PACKAGE_LISTS=(
["pacman"]="${base_url}/noscripts/install/packages/arch.txt"
["apt"]="${base_url}/noscripts/install/packages/debian.txt"
["dnf"]="${base_url}/noscripts/install/packages/fedora.txt"
["xbps-install"]="${base_url}/noscripts/install/packages/void.txt"
)

install_packages() {
for package_manager in "${!PACKAGE_LISTS[@]}"; do
case "$package_manager" in
dnf|apt) package_manager_command="sudo $package_manager install ";;
pacman|xbps-install) package_manager_command="sudo $package_manager -S";;
*) echo "${BLD}${RED}Error:${RST} Unsupported package manager.";;
esac
readarray -t packages < <(curl -fsSL "${PACKAGE_LISTS[$package_manager]}")
package_list=$(printf '%s ' "${packages[@]}")

eval "${package_manager_command} ${package_list}"
bat cache --build
done
}

install_packages


What it does is fetch the packages list from the remote url on the defined associative array and install it.

Now at first glance the function is really fine. trying it out Yes it works, it does install all of the packages defined on the list.txt (even though already installed).

I decided to do some testing i removed some packages (uninstalled bat btop cava chafa delta exa and neofetch). Now I run again the noscript. All of my removed packages doesn't get installed.

Hmm, that's weird there's something wrong, now I did some debugging

+ eval 'sudo dnf install  alacritty bat btop cava chafa util-linux-user curl git-delta exa fd-find foot thefuck fzf git jq kitty lsd mpv neofetch neovim ripgrep stow starship tar tmux unzip wget wl-clipboard zsh '
++ sudo dnf install alacritty bat btop cava chafa util-linux-user curl git-delta exa fd-find foot thefuck fzf git jq kitty lsd mpv neofetch neovim ripgrep stow starship tar tmux unzip wget wl-clipboard zsh
Last metadata expiration check: 1:26:27 ago on Mon 27 Feb 2023 08:07:52 PM PST.
Package alacritty-0.10.1-3.fc37.x86_64 is already installed.
Package util-linux-user-2.38.1-1.fc37.x86_64 is already installed.
Package curl-7.85.0-6.fc37.x86_64 is already installed.
Package foot-1.13.1-1.fc37.x86_64 is already installed.



As you can see on the log the package that I removed are listed clearly (sudo dnf install ... bat btop cava ... git-delta...) and yet why it doesnt get included on the installation any ideas why?

https://redd.it/11dc4fh
@r_bash
Question About sed c Command?

Does anyone know if you select a range of lines with sed and then use the c command, will it replace each line in the range with the text passed to the c command? In other words, if 10 lines are in the range will there be 10 changes? Or will it replace all 10 lines with just one copy of the text passed to the c command?

https://redd.it/11dit6q
@r_bash
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]} -