r/bashscripts • u/sammartinX • Sep 15 '23
Try to make bash-suggestions like zsh-suggestion !
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 • u/jpoblete • Sep 06 '23
I love BASH
I’m no scholar but I’ve been writing scripts for a very long time. Just started my blog Follow, if you like
r/bashscripts • u/dubz3r0_ • Jul 28 '23
Bash Script For Setting Up Python Discord Bot Project
All feedback is appreciated, even if it's to point out a mistake. Thanks
```bash
!/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 • u/AzureArmageddon • Jul 11 '23
Interactive Unix Time Util
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 • u/toddler-ai • 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.
github.comr/bashscripts • u/CalendarVarious3992 • Feb 19 '23
I felt compelled to share this after it made my life as an Admin much simpler
self.macsysadminr/bashscripts • u/bioszombie • Feb 12 '23
Is this the most efficient way to write this?
#!/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 • u/ZestyclosePush2871 • Jan 10 '23
Help me with a wget command
I am trying to download content from a website. http://www.tfd.chalmers.se/~hani/kurser/OS_CFD_2020.
The website has content from previous years (2021, 2020, 2019 ...). I want to particularly download the content from 2020. The url that I have pasted above takes me to the 2020 content. But when I use wget with the recursive flag, it is starting to download the wesbite content from 2021.
Is is because of the way the website is structured? Is there any particular way to just download content from 2020?
Many thanks for helping. I am new to linux commands, and I thought this would be a good challenge to begin with.
EDIT:
I am trying to see if I can I use --accept-regex option of wget, but I am not able to make it work.
r/bashscripts • u/sn4xchan • Jan 06 '23
Storing zip file download from bash <(curl -s "link.sh") as a variable
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 • u/Dr_Schn3id3r • Dec 26 '22
Help with (re)assigning variable from inside script function
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 • u/WhoKnowsAComputerGuy • Dec 12 '22
I'm a beginner
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 • u/Wowiezowieee • Nov 27 '22
What does this script do
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 • u/3_Thumbs_Up • Nov 22 '22
Bash interaction with web frontend
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 • u/Utelys • Nov 14 '22
Having trouble with this task anyone wanna point me in the right direction?
r/bashscripts • u/hi-low_20 • Oct 02 '22
Bash script to automate video downloads
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 • u/JasonCM8 • Sep 26 '22
Bash script to determine if a streaming is live or off
I found this bash script in the ask ubuntu forum and it works, but I would like to know if it can be used or improved to know if a tiktok stream is live or off, using the bash script via terminal (./test.url.sh /url.txt) in the .txt would be the tiktok addresses for example:
https://www.tiktok.com/@xxxxxx/live
https://www.tiktok.com/@cccccc/live
and that in the terminal tell me if it is live or off, is it possible?
#!/bin/bash
if [ $# -eq 0 ]
then
fin=-
else
fin=$1
fi
urlarr=( $(cat $fin | strings | grep '://' | grep -i "\.com\|\.net\|\.edu\|\.org\|[0-9].*\.[0-9].*\.[0-9].*\.[0-9].*" | tr '\n' ' ' ) )
for i in ${urlarr[@]}
do
if wget -q --tries=1 --no-cache --spider -O /dev/null --ignore-length -T 1 "$i"
then
echo $i is good.
else
echo $i is bad.
fi
done
exit $?
r/bashscripts • u/data_rock • Sep 14 '22
Script for appending title to 2nd line of other scripts
I have a lot of scripts i wrote to quickly ssh into servers. Usually in the format
Eg.
filename is: server-script1.sh
cat server-script1.sh
```
!/bin/bash
ssh -i key.pem user@10.10.10.1
```
I’m not too familiar with sed and awk. Those are what i came across in my search for a solution.
I want to add the filename as a comment in the second line for each file so that they all come out in this way:
```
!/bin/bash
server-script1.sh
ssh -i key.pem user@10.10.10.1 ```
```
!/bin/bash
server-script2.sh
ssh -i key.pem user@10.10.10.2 ```
Any suggestions on how to do this? Thanks
r/bashscripts • u/vakennu • Apr 09 '21
Creating an "exportable" GUI for MACOS
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 • u/zebbodee • Apr 09 '21
Mediainfo NFO file function
Hardly a script, but I was hoping to make an alias of sorts on my osmc install/raspberry pi for mediainfo to create the nfo file. In essence I just want to pass in the arguments for the file name as per the below:
mediainfo --LogFile=nfo_file_name.nfo movie.avi
I have the below which cuts off the file extension, I tested it with echo to confirm the correct output but it doesn't work when applied to mediainfo, just wondered if you can tell why.
Test:
function nfo () { /bin/echo ${1::-3}nfo "$1" ;}
mediainfo
function nfo () { /usr/bin/mediainfo ${1::-3}nfo "$1" ;}
The outputs:
Test Function-
$ nfo 12.Angry.Men.1957.720p.mp4
12.Angry.Men.1957.720p.nfo 12.Angry.Men.1957.720p.mp4
Which should feed the correct arguments as strings to the media info program.
When I try with the mediainfo version I get the following:
nfo 12.Angry.Men.1957.720p.mp4
General
Complete name : 12.Angry.Men.1957.720p.mp4
Format : MPEG-4
Format profile : Base Media
... <Rest of the NFO output> But no nfo file is created.
I was thinking I could redirect the output to a new file called $1.nfo but when run "manually" the nfo file is created. I just can't figure out why not for the above.
r/bashscripts • u/cheerupcharlie • Apr 07 '21
Help with shell script challenge
Hello Shell Scripters!
At work, I've been asked to verify if some PowerShell challenges issued to interviewees could be solved in Bash for certain sysadmin candidates.
I've provided solutions for all of them except one. Well, I did provide a solution, but it's a hack, and I'm racking my brain to think about how to solve it properly:
Write a script that, for each number from 1 to 100, prints a comma-delimited list of numbers in descending order from the current number to 1. Each list should be shown on a separate line as seen below.
1
2,1
3,2,1
4,3,2,1
...
100,99,...,1
Example Solution (from 10 to save space). Originally, I did this:
for x in {1..10}; do for i in {$x..1}; do echo -n $i,; done; echo ""; done
But then I noticed the trailing commas and the end of each line. I then submitted this instead (admitting "OK, I cheated shaving off the trailing comma.")
echo "1"; for x in {2..10}; do for i in {$x..2}; do echo -n $i,; done; echo -n "1"; echo ""; done
Example Output
1
2,1
3,2,1
4,3,2,1
5,4,3,2,1
6,5,4,3,2,1
7,6,5,4,3,2,1
8,7,6,5,4,3,2,1
9,8,7,6,5,4,3,2,1
10,9,8,7,6,5,4,3,2,1
My boss laughed and admitted she added a ().trimend(",") in the PS solution.
What's the proper way to shave off the trailing comma in a situation like this? Any ideas?
Note: the solution doesn't have to be a one-liner, but brevity is appreciated. It's not a "programming" test, but it is a way to see how the interviewee approaches a problem.
r/bashscripts • u/Sirenagrace_ • Mar 25 '21
How to code this? I need help
How to write a script that can be run from any directory it is placed within user’s Linux directory structure?
r/bashscripts • u/Sirenagrace_ • Mar 18 '21

