r/bashscripts • • Sep 06 '23

I love BASH

9 Upvotes

I’m no scholar but I’ve been writing scripts for a very long time. Just started my blog Follow, if you like

https://bashydata.wordpress.com


r/bashscripts • • Dec 26 '20

I am learning Bash and I will code your scripts for free.

7 Upvotes

I am learning to code in Bash and I already have several scripts done that work perfectly. I have run out of ideas of what to do and the book examples bore me so if you propose me something that you need I will code it for you with pleasure for free.

Only a few conditions:

- Make a small description here in the forum. I will answer you if I accept it or not. I will give priority based on my skills and preferences, not on the order of arrival.

- Only small and not too complex scripts. I prefer to help little to many than much to one. I will also try to do different things if possible.

- Specification and details best by private or email. Please take your time to make it as detailed as possible so that I don´t have to ask around.

- If you are in a hurry, it is better to find another way. I have a job and will code it in my free time.

- Keep in mind that I am not an expert and there is a possibility that after some time I will be unable to make it work properly. In that case you will have to find someone better than me to do the job.

- I will take my time to code and test it carefully, but I do not admit any responsibility if the script damages your files or systems. You should set up a secure test environment to test it.

That's all.


r/bashscripts • • Apr 09 '21

Creating an "exportable" GUI for MACOS

6 Upvotes

I'm looking for recommendations for solutions to create an exportable GUI for my shell scripts. Exportable = copying to other computers with no additional software on the target computers needed.

This is for MACOS and if I get around using the Apple app store that would be best.


r/bashscripts • • Feb 12 '21

[Blog] Bash variables — Things that you probably don’t know about it

6 Upvotes

Hey,

Two days ago I wrote this blog exploring the scope of the Bash variables and the types. I'm explaining their differences, how and when to use each one of them. Feel free to give any feedback/suggestion/* :)

See on Medium: https://medium.com/unboxing-the-cloud/bash-variables-things-that-you-probably-dont-know-about-it-8a5470887331?sk=26693ca772a0c54c99d3712303560ed4

See on my Website: https://www.lozanomatheus.com/post/bash-variables-things-that-you-probably-don-t-know-about-it

Sorry, I'm pretty new on Reddit, I accidentally deleted the original post...


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 • • 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 11 '23

Interactive Unix Time Util

5 Upvotes

My first real bash script that does anything so feedback welcome. There's probably a more intelligent program or script out there that does this and more perfectly but I couldn't find it so I just wrote one. I wrote this also because I wanted to get away from loading up the same janky old websites for the same purpose.

#!/bin/bash
# NOTE: sh (aka posix shell) is incompatible; echo -n option doesn't work

echo "Modes:"
echo "  [1] Current unix time"
echo "  [2] Convert from unix time"
echo "  [3] Convert to unix time"
echo -n "Select mode: "
read mode
echo

case $mode in
    "1")
	    echo -n "Current unix time: "
	    date -j +%s
    ;;
    "2")
	    echo -n "Enter unix time: "
	    read time

	    echo -n "Formatted time: "
	    date -j -r "$time" "+%d %b %Y %H:%M:%S %Z"
	    # Q: Why %Z works while %z doesn't?
    ;;
    "3")
	    echo "Example input: 01 Jan 1970 00:00:00 +0000"
	    echo "Warning: Input format is strict!"
	    echo -n "Enter full date and time: "
	    read time

	    echo -n "Unix time: "
	    date -j -f "%d %b %Y %H:%M:%S %z" "$time" +%s
	    # BUG?: SGT is given as +0730 on my machine when it's +0800 legally
    ;;
esac

r/bashscripts • • Dec 30 '20

Some ticks/tips for Bash script - HTTP request with a Bash native function -- Get IP Address without ip/ifconfig

5 Upvotes

Hello there,

A few weeks ago I started my blog which I'll focus on Tips and Tricks. I wrote only two posts until now, soon I'll bring more. The idea is to bring some stuff that I use/know on a daily basis and it may be useful for others too. I'm trying to keep as simple as possible with some practical examples (+ external links that could explain in-deep, in case someone wants to know more :) ).

Any feedback is more than welcome :)

How to send a TCP request with Bash native feature (e.g.: you can do test an HTTP endpoint without installing cURL / Wget / etc)
https://medium.com/bash-tips-and-tricks/part01-tcp-udp-request-with-a-native-bash-feature-and-without-curl-wget-9dcef59c30aa

How to get the Linux IP address without ip/ifconfig
https://medium.com/bash-tips-and-tricks/getting-the-linux-ip-address-without-any-package-ifconfig-ip-address-etc-7b1363077964


r/bashscripts • • Mar 29 '21

What’s the error in this code ?

Post image
4 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 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 • • Jun 19 '20

Help with cp command in bash script

4 Upvotes

Hi everyone! I'm having an issue with the cp command to move folders/files to a new disk. When the filename or folder has a \(space) it won't see it as a complete folder name or file and instead takes the first section of the file and then errors on everything else. Can anyone help me with what I'm doing wrong?

#!/bin/bash

###############################################################
#####################      Variables     ######################

### Set the proper source and destination directory location

SOURCE_DIR="/opt/test/old/"
DEST_DIR="/opt/test/new/"

### Set the username and group name to set on copied files
USER='root'
GROUP='root'

###############################################################

########### Do not edit below this untill required  ##########

### Test if source directory exists
### The programm with stop if source not exists

if [ -d ${SOURCE_DIR} ]; then
	echo "Source directory found"
else
	echo "Source directory not found. Please check above variables are set correctly"
	echo "script exited"
	exit 1
fi

### Test if destination directory exists
### The programm will create destination directory if not exists.
### If failed to create directory, the script will terminate 

if [ -d ${DEST_DIR} ]; then 
	echo "Destination directory found, all ok"
else
	echo "Destination directory not found, creating now"
	mkdir -p ${DEST_DIR}
	if [ $? -eq 0 ]; then
		echo "Sucessfully created destination directory."
	else
		echo "Faild to create destination directory. Script exited"
		exit 1
	fi
fi


### Copy all files available on source directory
### After successfully copying file remove it from source directory.

cd ${SOURCE_DIR}

if [ $? -eq 0 ]; then
	for CURRENT_FILE_NAME in `find . -type f`
	do
		cp --parents ${CURRENT_FILE_NAME} ${DEST_DIR}
		if [ $? -eq 0 ]; then
			echo "File ${CURRENT_FILE_NAME} successfully copied."
			rm -f ${CURRENT_FILE_NAME}
		else
			echo "File ${CURRENT_FILE_NAME} failed to copy"
		fi
	done
fi


## Set the permissions after copying files 

sudo chmod 775 -R ${DEST_DIR}
sudo chown ${USER}:${GROUP} -R ${DEST_DIR}


###################  End of Script  ############################

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 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 • • 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 • • Oct 02 '22

Bash script to automate video downloads

3 Upvotes

Looking to make a script to automate video downloads. The process normally goes like this: 1. YouTube-dl 'url-to-vid' (this will download an HTML) 2. Open HTML and search for "data-src" (so far only two lines have returned with this search, one relating to a .mp4 and another .jpg, we need the url for the .mp4) 3. Copy & paste url again with YouTube-dl and then rename the file using the name of the HTML file. 4. rm original HTML file.


r/bashscripts • • Nov 23 '20

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

Thumbnail
gallery
3 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 • • 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 • • 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..."

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 • • 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 • • 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 • • Nov 27 '22

What does this script do

2 Upvotes

I need to explain what this script does for a question on my classwork but my teacher isn't satisfied with my answer. Can anyone provide some insight into what exactly is happening with this script?

#!/bin/bash

if [ -z “$1” -o -r “$2” ]; then

echo “Usage: myscript [file] [size]”

exit 255

fi

SIZE=`ls -l $1 | awk ‘{print $5}’`

if [ $2 -gt $SIZE ]; then

echo “Your size must be smaller than the file size!”

exit 254

fi

CHUNK=$2

TOTAL=0

PASS=0

while [ $TOTAL -lt $SIZE ]; do

PASS=$((PASS + 1))

echo “Creating $1.$PASS …”

dd conv=noerror if=$1 of=$1.$PASS bs=$CHUNK skip=$((PASS – 1)) \

count=1 2>/dev/null

TOTAL=$((TOTAL + CHUNK))

done

echo “Created $PASS files out of $1.”


r/bashscripts • • Nov 14 '22

Having trouble with this task anyone wanna point me in the right direction?

2 Upvotes

So i need to make a script that transfers a backup from one system to another remote system using ssh, but I am not sure how I will be doing this, can anyone give some tips to help me complete this task?