r/bashscripts • • Nov 22 '22

Bash interaction with web frontend

1 Upvotes

Long story short, because of a weird quirk with my ISP I want to restart my router automatically every night. I have a Linux server on my lan, so ideally, I would simply have my server run a script that does this for me.

In order to restart my router manually, I need to login to my router, press, a button in the top left corner, and then confirm my choice. That's it. I assume there are some Linux tools that can already do something like this, but I'm uncertain where to start.

The log in page seems like the big hurdle here. Otherwise i guess it could be done with a curl oneliner.


r/bashscripts • • Dec 12 '22

I'm a beginner

2 Upvotes

Trying to script something I would manually do. Can you help me clean it up and show me best practice? The end goal to all this will be to add in dnf upgrade and downgrade as well as remove and install. But just keeping it simple since it will mostly be rinse and repeat.

!/bin/bash

Hosts that this script applies to

ALLHOSTS="WS01 WS02 WS03 SRV01 SVR02 SVR03"

Set RPM variable for script

set_rpm() { echo Set RPM: read rpm }

Function to Search for RPM variable on a host

check_rpm() { if rpm -qa | grep "$rpm" /dev/null; then Cat /proc/sys/kernel/hostname rpm -qa "rpm fi }

this is redundant but I want to keep the formula for future things for now

select_01() { Select_rpm }

SSH to each host and check for rpm

select_02() { for HOSTNAME IN $ALLHOSTS;do ssh -qa -tt $HOSTNAME "$ (typeset -f); check_rpm" | tee log.rpms done }

Start of menu selection

press_enter() { echo "" echo -n "Press Enter to continue" read clear }

until [ "Selection" = "0" ]; do clear echo "Please select what you want to complete" echo "" echo ". 1. -. Set rpm variable " echo ". 2. -. Check for rpm" echo -n " Enter Selection" read selection case $selection in 1) clear ; select_01 ; press_enter ;; 2) clear ; select_02 ; press_enter ;; 0) clear ; exit ;; esac done


r/bashscripts • • Feb 12 '23

Is this the most efficient way to write this?

2 Upvotes

#!/bin/bash

# import global vars

source .env

funcSpaceCheck ()

{

`# check space on NAS`

`DRIVE_SPACE=$(ssh "$USERNAME"@"$REMOTE_SERVER" df -h | grep "$GREP_SEARCH_STR" | tr -s ' ')`

`DRIVE=$(grep "$GREP_SEARCH_STR" <<< "$DRIVE_SPACE" | cut -d ' ' -f 1 | xargs)`

`TOTAL_SPACE=$(grep "$GREP_SEARCH_STR" <<< "$DRIVE_SPACE" | cut -d ' ' -f 2 | xargs)`

`USED_SPACE=$(grep "$GREP_SEARCH_STR" <<< "$DRIVE_SPACE" | cut -d ' ' -f 3 | xargs)`

`SPACE_REMAINING=$(grep "$GREP_SEARCH_STR" <<< "$DRIVE_SPACE" | cut -d ' ' -f 4 | xargs)`

`USED_SPACE_PERCENTAGE=$(grep "$GREP_SEARCH_STR" <<< "$DRIVE_SPACE" | cut -d ' ' -f 5 | xargs)`

`USED_SPACE_PERCENTAGE_INT=$(grep "$GREP_SEARCH_STR" <<< "$DRIVE_SPACE" | cut -d ' ' -f 5 | xargs| sed 's/%//')`
`echo "Hard Drive:		" "$DRIVE"`

`echo "Total Hard Drive Space:	" "$TOTAL_SPACE"`

`echo "Used Space:		" "$USED_SPACE"`

`echo "Space Remaining:	" "$SPACE_REMAINING"`

`echo "Percentage Used:	" "$USED_SPACE_PERCENTAGE"`

}

funcCopyFiles ()

{

`# secure copy ISO files to NAS`

`scp ./*.iso* "$USERNAME"@"$REMOTE_SERVER":"$REMOTE_FOLDER"`
`echo "ISO files have been moved to" "$REMOTE_SERVER"` 

}

funcDeleteLocal ()

{

`#remove ISO files from local folder`
`COUNT=$(find ./*.iso* 2>/dev/null | wc -l 2>/dev/null | wc -l)`

`if [ "$COUNT" != 0 ]; then` 

	`rm -rf ./*.iso*`

	`echo "ISO files have been removed from $(pwd)"`

`else`

	`echo "No ISO files in folder. Nothing deleted."`

`fi`	

}

clear

funcSpaceCheck

`if [[ "$USED_SPACE_PERCENTAGE_INT" -ge 95 ]]; then`

	`echo "Not enough space!!! Please obtain more storage space to continue operation!"`

`else`

	`funcCopyFiles`

	`funcDeleteLocal`

`fi`

r/bashscripts • • Feb 19 '23

I felt compelled to share this after it made my life as an Admin much simpler

Thumbnail self.macsysadmin
3 Upvotes

r/bashscripts • • Mar 02 '23

Download Toddle for FREE: Toddler is a bash script that extracts all the TODO comments across your codebase into a markdown file.

Thumbnail
github.com
3 Upvotes

r/bashscripts • • Feb 25 '18

A cool bash animated colored title bar

3 Upvotes

Just wrote this up for a script I was working on and figured I’d share it Incase there was someone out there like me wanting to do something like this

Cool bash animated title bar:

clear;export x=5;export columns=$(tput cols);x=$((($columns)/4 + 4));export y=$((($columns)/2 - $x));for i in {16..21} {21..16} {16..21} {21..16} {16..21} {21..16} {16..21} {21..16}; do tput cup 4 $y;echo -en "\033[48;5;${i}m \033[0m";echo -en "\033[48;5;${i}m \033[0m";tput cup 8 $y;echo -en "\033[48;5;${i}m \033[0m";echo -en "\033[48;5;${i}m \033[0m";y=$(($y+1));sleep 0.06;done;x=$((($columns)/2 - 10));tput cup 5 $x; echo -e "\033[1;34mApp Name\033[0m";tput cup 6 $x; echo -e "\033[1;34mAuthor: Your Name\033[0m";tput cup 7 $x; echo -en "\033[1;34mVersion: 1.0.0 \033[1;31mbeta\033[0m";tput cup 12 0;unset columns;unset x;unset y;echo -e "\n"


r/bashscripts • • Dec 24 '20

How to grep a variable

1 Upvotes

Hello guys i am new in bash scripting. Currently I am writing a script to automating docker container. It has three functions kill all docker container, start a new container on a port and show the link(eg. http://127.0.0.1:333 etc.).to run all these i need to check whether a port is listening or not. To do that I first used sudo lsof command with -i:$PORT but it didnt worked so next i used netstat -tulpn with grep $PORT it also didn't worked. it shows some error on grep. Can somebody please help me on this. How can I check a port from a variable whether listening or not. And one more thing the command should be like this ./docker-test 3000 Or ./docker-test kill to kill all running container. Somebody plzz help


r/bashscripts • • Nov 23 '20

Simple random increment Bash script project... What am I doing wrong?

Thumbnail
gallery
3 Upvotes

r/bashscripts • • Dec 02 '20

I created a Bash script to automatically update GoDaddy domains from the Linux CLI.

Thumbnail
self.linux
4 Upvotes

r/bashscripts • • Aug 19 '20

XXD from multiple files of the same extension

1 Upvotes

Hey all

So I have a question in regards to a useless, but fun, project.

The script so far

#!/bin/bash

d2s=$(find $HOME/test -type f -name "*.d2s")
charname="$(xxd -u -p -l16 -s 20 assone.d2s | tr '0' 'n'| xxd -r -p)"
charclass="$(xxd -u -p -l1 -s 40 "$d2s")"
echo "Character Name: $charname"
echo "Character Class: $charclass"

What I am doing with it:

I have a bunch of files, in this case .d2s files (save games). In it is data stored like Character Name, Char Class, level, etcetera. So what this does is extract the data so I can show this in a simple bash script and from there ... well do what I can do in the game as well. :P This part is actually quite easy as long as I pay proper attention.

What is working:

If I extract the data from a file directly named in the lines (charname/charclass) it works and it shows me the output. So far I get the char name and the char class and I can print this out.

What I want:

Use the find command to, for now, find the .d2s characters (could be more, could be less) inside my test folder. (I choose $HOME/test as I already have backups and just want to focus on this directory, the end result would be different in terms of finding)

What the error shows when I run the script when I run it with the "$d2s" variable:

xxd: /home/charlie/test/amaone.d2s
/home/charlie/test/necone.d2s
/home/charlie/test/assone.d2s: No such file or directory
Character Name: assone
Character Class:

In other words, the class won't show up, yet the files are found and listed correctly.

Is there a way how I can just read the output of all the files?


r/bashscripts • • Aug 30 '20

hello "if i see a specified msg on terminal , then i need to do a task"

1 Upvotes

hello .. i am trying to write a script and i am stuck at one point .Here is the scenario .. i need to mount an iso and trigger a installation .. after a later point of time , it prompts in the terminal to mount ISO2.

Now i have written the script to mount iso1 and trigger the installation , but how can i include the part " that if i see "msg" on terminal , mount ISO2

Need urgent help .. Thanks a lot in advance!


r/bashscripts • • Aug 27 '20

I got sick of manually creating markdown files for each blog post in Jekyll, so I created a bash script to do it! Enjoy, link is in the comments.

6 Upvotes

r/bashscripts • • Aug 19 '20

Append $PWD to provided input

3 Upvotes

Good day /r/bashscripts i am tring to practice bash scripting but couldn’t figure out how to append the output of $PWD to a provided input like this examble below

tar -czvf $oname.tar “$PWD/$iname”

if i use this it will start at the parent directory not the intended directory. what am I messing here?


r/bashscripts • • Aug 11 '20

Teleporter

4 Upvotes

Here's a simple bash-script I made; realizing I want to 'teleport' from folder to folder just by calling their nick-name. Aliases didn't cut it, because I found myself having to open .bashrc every time I wanted to add/remove a script. This helps me do that (rather quickly) on the terminal itself.

Basically, the idea is to cd into your favorite folder, and add it as a teleport-point by typing

t a work

then get to work folder from anywhere in your folder by typing

t work

change the work folder by going to the new folder you want to assign and typing

t r work

t a work

samuelj123/teleporter

I want to keep this simple and modular while being a little more user-friendly. Suggestions?


r/bashscripts • • Aug 28 '20

play midi from a tar.gz file

1 Upvotes

Hey all,

So I have a very odd question. Is it possible to play media from a tar.gz file? In this case I got about 30K+ midi files compressed and I was just wondering if playing these files can be done without being extracted.

The closest I got is using the following line to find the files inside the tar.

tar -xvf midi.tar.gz --to-command "find . -type f -name "*.mid" | wildmidi"

But all that does is state the following error

ERROR: No midi file given
Usage: wildmidi [options] filename.mid
tar: 2514: Child returned status 1
midi/piano/Wonderboy_3_Melody_Piano.mid

So basically it won't pipe to wildmidi (the player I use) even though it finds the files.

Also vim is not an option in this case to browse the files.

Yes, I know, a very odd question and I am doubtful there is a solution, but if there is, it would be awesome. ^_^


r/bashscripts • • Nov 07 '19

Need help with scripting

1 Upvotes

I have this script that I am working on and need help.

I don't know what to do I check it over several times and need someone else to look it over

#!/bin/bash

echo "beginning storage check..."

exec >> ~/storage_report.txt

echo "Date : $(date)"

echo "------------------"

part=$(df -h | awk '{print $1}' | grep '/dev')

for z in ${part[*]}

do

checkper=$(df -h | grep $z | awk '{print $5}' | cut -d '%' -f1)
if \[ $checkper -ge 95 \] && \[ $checkper -le 100 \]; then

		echo "$z is $checkper% full."

	else

		echo "ALERT: $z is $checkper$ full! recommended immediate action!"

	elif \[\[ $checkper -ge 95 \]\] && \[\[ $checkper -le 100 \]\]; then

echo "CAUTION: $z is $checkper% full! Consider freeing up some space."

		elif \[\[ checkper -lt 50 \]\]; then

		echo "$z is $checkper% full. No action needed."

	else

		echo "Encountered an error. status code: $?" >&2

		exit $?

fi

done

echo "storage check complete. Report saved to storage_report.txt" >&2


r/bashscripts • • Mar 08 '20

Editing the PS1 variable

2 Upvotes

This is the question I have:

This sounds like I have to use an if statement but I don't know how that works, what do I do?


r/bashscripts • • Jan 01 '23

Bibtex files

1 Upvotes

Could you guys help me with my task for the uni? I should to write a bash script, that helps one to serach for the author etc.

I need a command line that helps me do that

here is an example for bibtex


r/bashscripts • • Jan 06 '23

Storing zip file download from bash <(curl -s "link.sh") as a variable

2 Upvotes

The idea is to download a zip file from that script and then move that said file to a different location after the script finishes.

Can anyone point me in the right direction at least?


r/bashscripts • • Nov 22 '19

Help with Cron

1 Upvotes

So I have a very simple script that I would like to run.

#!/bin/bash

sudo apt update -y

sudo apt full-upgrade -y

reboot echo "Update successful : $(date)" >> /tmp/update/log

I am trying to run this with cron, which looks like this

* * * * * bash /home/me/Documents/Scripts/update.sh

I cannot get this to run and am not quite sure where I am going wrong. Any assistance would be appreciated.


r/bashscripts • • Jul 10 '20

what am i missing? auto-start cron script

1 Upvotes

so my bash scripting is terrible apparently what am i doing wrong
my makerun variable is not being handled properly

#!/bin/bash
#INFO: this script should be run with cron or manually .
displaystart='Xvfb :99' & #required to start deusex otherwise wine crashes (starts virtual display on port :99)
displayexport='export DISPLAY=:99' & #export for a virtual display on port :99 for our current cli session
process='Deusex.exe' #proccess that the script is looking for every couple seconds
makerun=/usr/bin/wine "/home/deusex/.wine/drive_c/Program Files/dxmp-cdx/System/DeusEx.exe DXMP_PoolParty.dx??Mutator=DXMapVote100.MVMutator -server" #command that we are running if not found running already

if ps ax | grep -v grep | grep $process > /dev/null
then
    exit
else
    $displaystart &
    $displayexport &
    "$makerun" &
    echo "SCRIPT REBOOTED GAME SERVER AS IT APPEARS IT HAS CRASHED ¯_(ツ)_/¯  Time of fuck up: $(date)" >> /home/deusex/crashlog.log
fi

exit

thanks for any help


r/bashscripts • • Oct 27 '17

Nested if statements

2 Upvotes

Can someone help me out. Not sure why the nested if are not hitting even though the files exist

if [ ! -d node_modules ]; then
    echo "node modules@@@@@@"
    if [ -f yarn.lock ]; then
        echo "We have Yarn"
        yarn install
    elif [ -f package-lock.json ]; then
      echo "we have package lock"
      npm install
    else
      yarn install
    fi
fi

r/bashscripts • • Dec 26 '22

Help with (re)assigning variable from inside script function

3 Upvotes

Hello everybody,

I have read a lot of different ubuntu and linux guides about bash scripting, but I cant solve my problem.

So I wanted to ask you for help with the following simple dummy code:

#!/bin/bash

# FUNCTIONS

change_variable(){
	variable=${value_one}
	echo ${variable}
}

# MAIN

readonly value_one=1
readonly value_zero=0

variable=${value_zero}

(change_variable)
echo ${variable}

The output is:

XPS-9315:~/Dokumente$ ./test_script 
1
0

So my question is, why can I not reassign the variable with a new value from insight the function?

PS: Does not help if I define/declare the variables before the function definition.

Thank you very much and kind regards :)


r/bashscripts • • Sep 15 '23

Try to make bash-suggestions like zsh-suggestion !

5 Upvotes

So I try to make a bash-suggestion program that has features like zsh-autosuggestion. I tried making the two-three scripts in bash but It doesn't fulfil the requirements like zsh-autosuggestion so can you suggest or atleast have any suggestion whether this tool is necessary for only-bash-users who don't want to use any other shells and tools like this ofcourse open-sourced.

Can you suggest some ideas for creating that bash-suggestion script that will work beyond the zsh-suggestion's features !


r/bashscripts • • Jul 28 '23

Bash Script For Setting Up Python Discord Bot Project

2 Upvotes

All feedback is appreciated, even if it's to point out a mistake. Thanks


#!/usr/bin/env bash

# This script sets up a python discord bot project with required files, dependencies, and virtual environment.

# Define global variables
SCRIPT_NAME="bot-setup"
INSTALL_LOG="$PWD/.install.log"

# Function to log errors to the .install.log file
function log_error() {
    local line_number=$1
    local error_message=$2

    # Log the error to .install.log in the current working directory
    echo "Error occurred in line $line_number: $error_message" >> "$INSTALL_LOG"
}

# Function to create build directory and name bot
function mk_build_dir() {
    local build_location="$1"
    local bot_name="$2"

    # Check if the build_location is an absolute path
    if [[ ! "$build_location" = /* ]]; then
        log_error $LINENO "Please provide an absolute path for the build location."
        exit 1
    fi

    # Check if the build_location directory exists
    if [ ! -d "$build_location" ]; then
        log_error $LINENO "Build location directory does not exist."
        exit 1
    fi

    mkdir -p "$build_location/$bot_name" || log_error $LINENO "Failed to create the build directory"
    BOT_PROJECT_DIR="$build_location/$bot_name"
    cd "$BOT_PROJECT_DIR" || log_error $LINENO "Failed to change to the build directory"
}
export BOT_PROJECT_DIR="$build_location/$bot_name"

# Start the setup
INITIAL_SCRIPT_RUN_DIR="$PWD"
echo "Script Starting In: $INITIAL_SCRIPT_RUN_DIR"
sleep 2
clear

# Choose the build location
echo "Would you like to choose a different build location? (y/n)"
read -r build_location_answer

if [ "$build_location_answer" = "y" ]; then
    echo "Please enter the build location you would like to use:"
    read -r build_location
else
    build_location="$INITIAL_SCRIPT_RUN_DIR"
fi

echo "Create custom bot name? (y/n)"
read -r bot_name_answer

if [ "$bot_name_answer" = "y" ]; then
    echo "Please enter the bot name you would like to use:"
    read -r bot_name
else
    bot_name="discord_bot"
fi

echo "Creating: $build_location/$bot_name"
mk_build_dir "$build_location" "$bot_name"
sleep 2
clear

# Define path to the bot project directory
BOT_PROJECT_DIR="$build_location/$bot_name"

# Function to download a file using wget or curl
function download_file() {
    local url="$1"
    local target="$2"

    if command -v wget &> /dev/null; then
        wget -O "$target" "$url" || log_error $LINENO "Failed to download file using wget"
    elif command -v curl &> /dev/null; then
        curl -o "$target" "$url" || log_error $LINENO "Failed to download file using curl"
    else
        log_error $LINENO "Neither wget nor curl found. Cannot download the file."
    fi
}


# Create project files
echo "Creating project files: config.ini, requirements.txt, bot_functions.py, and responses.py."
touch "$BOT_PROJECT_DIR/config.ini" \
"$BOT_PROJECT_DIR/requirements.txt" \
"$BOT_PROJECT_DIR/bot_functions.py" \
"$BOT_PROJECT_DIR/responses.py" \
"$BOT_PROJECT_DIR/TODO.md" || log_error $LINENO "Failed to create project files"

# Download the bot.py quickstart file
echo "Checking for wget or curl..."
if ! download_file "https://gist.githubusercontent.com/awilcox-pydev/06addfa02b1f70897bb2c44af852a5de/raw/49de8b6b8244c4e208065ca87d1476f5d88d0c9b/bot_quickstart.py" "$BOT_PROJECT_DIR/bot.py"; then
    echo "Unable to download the bot.py quickstart. Skipping..."
else
    echo "Bot.py quickstart downloaded successfully."
fi

# Create the requirements.txt file with the required packages
echo -e "cryptography>=latest\ndiscord.py\nconfigparser>=latest\n" > "$BOT_PROJECT_DIR/requirements.txt" || log_error $LINENO "Failed to create requirements.txt"

# Create a virtual environment
if ! command -v virtualenv &> /dev/null; then
    echo "virtualenv not found, installing..."
    python3 -m pip install --user virtualenv || log_error $LINENO "Failed to install virtualenv"
fi

# Ask for virtual environment name
echo "Would you like to choose a different virtual environment name? (y/n)"
read -r virtualenv_answer

if [ "$virtualenv_answer" = "y" ]; then
    echo "Please enter the virtual environment name you would like to use:"
    read -r VIRTUAL_ENV_NAME
else
    VIRTUAL_ENV_NAME="venv"
fi

# Create the virtual environment
if [ ! -e "$VIRTUAL_ENV_NAME/bin/activate" ]; then
    echo "Creating virtual environment..."
    python3 -m virtualenv "$VIRTUAL_ENV_NAME" || log_error $LINENO "Failed to create virtual environment"
fi


# Create config.ini with default content
DEFAULT_INI_FILE_CONTENTS="[General]\n\n[Paths]\nvirtual-env: $BOT_PROJECT_DIR/$VIRTUAL_ENV_NAME"
echo -e "$DEFAULT_INI_FILE_CONTENTS" > "$BOT_PROJECT_DIR/config.ini" || log_error $LINENO "Failed to create config.ini"

# Add .venv and script name to .gitignore
echo "$VIRTUAL_ENV_NAME/" >> "$BOT_PROJECT_DIR/.gitignore"
echo "$SCRIPT_NAME" >> "$BOT_PROJECT_DIR/.gitignore"

# Install the required packages using pip
pip install -r "$BOT_PROJECT_DIR/requirements.txt" || log_error $LINENO "Failed to install required packages"

cd "$BOT_PROJECT_DIR" || log_error $LINENO "Failed to change to the project directory"

# Set up Completed!
echo "Setup Completed!"
echo "Now, you have your project set up. Check the TODO.md file in $BOT_PROJECT_DIR for the next steps."
echo "You can also check out the README.md file in the project root for more information."
echo "Bye..."