r_bash – Telegram
Replace hostname

Hi All,

I am planning to replace existing hostname by making simple interactive noscript

#!/bin/bash
echo "Set Hostname"
read name1
name='cat /proc/sys/kernel/hostname'
sed -i 's/$name/$name1/g' /etc/hostname
hostname $name1

The issue here is - it changes hostname. I exit and log back in. I see new hostname. But nothing gets changed in /etc/hostname file. reboot and I am back to old hostname.

​

What am I missing here?

https://redd.it/zexcn4
@r_bash
Finding a 5 digit code for a locked zip file

As the noscript states, I am looking to create a noscript that goes through 0 to 99999 and once it finds the right code it unlocks and unzips the contents. I know the use of a for loop and it will be slow but that's nothing to worry about for my noscript. The locked file is using 7-zip.

https://redd.it/zey4h8
@r_bash
Reading stdin of a parent process from within a child process?

# edit: Excellent solution by oh5nxo

{
coproc {
while read -sn1 -u3 line # original stdin
do
echo "coproc got $line" >&4 # original stdout
done
}
} 3<&0 4>&1 # hackery to "ship" stdin and stdout into coprocess
while sleep 1
do
echo "toplevel doing other things"
done

[https://www.reddit.com/r/bash/comments/zeyt4f/comment/iz9el4q/?utm\_source=share&utm\_medium=web2x&context=3](https://www.reddit.com/r/bash/comments/zeyt4f/comment/iz9el4q/?utm_source=share&utm_medium=web2x&context=3)

# Objective:

Reading `stdin` of the parent process ongoing from within a coproc child process.

* Can't use root
* Can't block the parent process
* Can't use `read` in the parent process because even if it's not blocking for long it's very messy and defeats the purpose of having an unhindered co-running process (see: `read` examples below).

# What I have:

ParentPid=$$
coproc {
exec 1>/proc/$ParentPid/fd/1 2>/proc/$ParentPid/fd/2
printf '\n%s\n' 'COPROC reading...' 2>&1
while true; do
read -n 1
printf 'KEY: >%q<\n' "$REPLY"
done
}

# Output should look like:

...the following when `asdf` is typed or sent into `stdin` of the parent process:

KEY: >a<
KEY: >s<
KEY: >d<
KEY: >f<

# Example output if something isn't working:

asdf

# Solutions that don't work:

/dev/stdin>/proc/$!/fd/0
# bash: /dev/stdin: Permission denied

/dev/stdin>&"${COPROC[1]}"
# bash: /dev/stdin: Permission denied

/proc/$$/fd/0>&"${COPROC[1]}"
# bash: /proc/13852/fd/0: Permission denied

# ___Inside coproc process___
exec /proc/$ParentPid/fd/0>&0
/bin/bash: line 3: exec: /proc/16449/fd/0: cannot execute: Permission denied

Works but blocks the parent process:

while true; do
read -s -n 1
echo -n "$REPLY" >&"${COPROC[1]}"
done

Works but it's sloppy, can leak text onto the tty and lags input if "do other things" takes too long:

while true; do
read -s -t 0.1 -n 999
echo -n "$REPLY" >&"${COPROC[1]}"
# do other things
sleep 0.5
done

Completely at the end of my rope on how to solve this, any help is greatly appreciated.

Big thank you,

https://redd.it/zeyt4f
@r_bash
what is this? !::=::\

Running env in bash in cygwin terminal shows this in my environment variables and I am ashamed to say I don't have any idea what it does or what it's for:

!::=::\

Any ideas?

https://redd.it/zf48j3
@r_bash
I'm preparing for the LPIC-1 exam and I cannot figure out why the correct answers to this question are the marked ones. Can someone help me?
https://redd.it/zf6nte
@r_bash
Why is the output in a different order?

declare -A beatles
beatles=(
singer=John
bassist=Paul
drummer=Ringo
guitarist=George
)

# Loop as written in the O'Reilly book

for musician in singer bassist drummer guitarist
do
echo "The ${musician} is ${beatles$musician}."
done
echo

# My way

for i in "${!beatles@}"
do
printf '%s\n' "The $i is ${beatles${i}}."
done

https://redd.it/zf7g2o
@r_bash
Hello guys! Im writing to here with the last hope. Im doing my first semester in uni and I have to write a bash noscript and I cant do it, I’Ve seen a lot of videos but I just simply dont understand it. I have 15 hours to make it so please, if anyone can help, help!

My homework is called Letter/Email Script (idk whice one, im not native english).
The denoscription to is:
“The program runs in the background and monitors incoming mail, if the subject of the mail is a certain pre-specified text (argument), then the
takes the contents of the letter as the sh shell noscript, executes it, and captures its output and sends it back to the sender. Don't disturb others during rehearsals”

I translated the dinoscription with google so Idk how accurate is it. :(

https://redd.it/zfdik9
@r_bash
Losing my mind trying to add to my startup noscript

Hi folks! I am working on setting up Robot Operating System on Ubuntu 22.04LTS. I need to add an echo line to my startup noscript, so that when I open my terminal it will automatically run a source command to setup the source for ROS.

I can't figure out how to do this - i've just been told that stuff about ~/.bashrc, which I opened in vim. I looked at it and i don't see where I would add the echo line. If anyone can provide advice, or point me towards a helpful resource, I'd greatly appreciate it.

Thanks in advance!

https://redd.it/zfh9p0
@r_bash
Spoof MAC address to random Apple vendor and Change to random IP according to current network ID

# CREATED BY: Zerodark875
# PROOF OF CONCEPT

if [[ $(id -u) -ne 0 ]]; then
echo "Need root. Quiting."
exit 1
fi

if [[ -z ${1} ]]; then
echo "Usage: ${0} [network_device]\nExample: ${0} eth0"
exit 2
fi

net_dev=${1}
current_ip=$(ip addr show ${net_dev} | grep -w inet | awk -F' ' {'print$2'} | cut -f1 -d'/')
network_id=$(echo ${current_ip} | awk -F'.' {'print$1"."$2"."$3'})
current_mac=$(ip link show ${net_dev} | grep -w ether | awk -F" " {'print $2'})
apple_mac_addresses=$(macchanger --list=Apple | cut -f3 -d" " | awk {'if ($1 != ""){print$1}'})
apple_mac_address_length=$(wc -l<<<${apple_mac_addresses})
picked_apple_mac_address=$(expr $(expr ${RANDOM} % ${apple_mac_address_length}) + 1)
vendor_id=$(echo ${apple_mac_addresses} | awk -v line=${picked_apple_mac_address} -F" " {'print$line'})

final_mac_address="${vendor_id}:$(expr $(expr ${RANDOM} % 89) + 10):$(expr $(expr ${RANDOM} % 89) + 10):$(expr $(expr ${RANDOM} % 89) + 10)"
final_ip="${network_id}.$(expr $(expr ${RANDOM} % 254) + 1)"

echo "Generating new ip and Mac address with Apple as vendor ID ;)"
echo "Current IP: ${current_ip} Current MAC: ${current_mac}"
echo ${final_ip} ${final_mac_address}

echo -n "Apply changes to the machine? (N/y):"
read choice
c=$(awk {'print tolower($0)'} <<< ${choice})
if [[ ${c} == "y" ]]; then
echo "Changing mac address to ${final_mac_address}"
ip link set ${net_dev} down
macchanger -m ${final_mac_address} ${net_dev}
ip link set ${net_dev} up
echo "Mac address changed. Waiting 5 seconds for new IP from DHCP server then we change it again"
sleep 5
current_ip=$(ip addr show ${net_dev} | grep -w inet | awk -F' ' {'print$2'} | cut -f1 -d'/')
echo "Deleting current IP ${current_ip}"
ip addr del ${current_ip}/24 dev ${net_dev}
echo "Adding new IP ${final_ip}"
ip addr add ${final_ip}/24 dev ${net_dev}
fi

https://redd.it/zfreok
@r_bash
clustercli command not found, but the command works under the user ?!

Hi,

I'm trying to add some commands to the bash noscript, and it does not seem to be work for some reason.

So I run this command whichi works fine if run manually.

su - mwp_admin
(in mwp_admin) clustercli -a config -i ~/inventory -t v-cluster -s airgap
(in mwp_admin) export KUBECONFIG=~/v-cluster"_config"
(in mwp_admin) kubectl exec -it v5-virtio-cuvnf-0 -n smcu2 -c cuvnf-container bash -- netstat -anp | grep sctp > result.csv

I wanted to add this to a shell noscript and run it. So I wrote this noscript, but its throwing error.

su - mwp_admin -c "clustercli -a config -i ~/inventory -t v-cluster -s airgap;export KUBECONFIG=~/v-cluster\"_config"\;kubectl exec -it v5-virtio-cuvnf-0 -n smcu2 -c cuvnf-container bash;netstat -anp | grep sctp > result.csv"

Error :

bash: clustercli: command not found

Any thoughts ?

https://redd.it/zfuwat
@r_bash
Reset terminal but keep scrollback buffer

Sometimes a program messes up the the terminal, and I have generally used reset to get things back into a normal state if I don't want to completely close the terminal window.

However this also tends to wipe/delete/clear the scroll back buffer.

Is there a way get the terminal back to default settings without wiping the scrollback history?

I know of the clear utility (and it has -x), but I'm not sure if it does the same reseting as reset. None of the options to reset(1) really seem to indicate to me reinitializing the terminal but keeping scroll history.

Thanks for any info.

https://redd.it/zg069a
@r_bash
Consult a “.txt” file and search if a certificate of a given URL its about to expire in certain year

Hi! I wanted to know if you guys would be able to help me on this exercise :)
I’m new on shell noscripting and I know only the basics of it.
However, I have this exercise in which I have to write 2 noscripts.

-The first one requires me to ask the user for an URL, and as an output, provide the expiration dates of a certificate, as well as automatically put that information on a .txt file named “dates.txt”

So far I have been able to do this first noscript and it runs well, where I’m having a little bit of trouble is on the second one.

-The second one asks me for this:

Consult the dates.txt file and search if the certificate of the given URL its about to expire in the 2018.

b) Create an "if/else" statement.
IF the cat command isn't empty (enddate/expiration date of the certificates is 2018), then you must save the information of expire of the URL in a "renew.txt" file assing the text "certificate will expire soon"
ELSE: echo "Nothing to do"

This is the part where I’m having a little bit of trouble with and I wanted to know if you could help me do it, thanks!

https://redd.it/zgakf1
@r_bash
Monitor when ports open and close using diff

#!/usr/bin/bash

#CREATED BY: Zerodark875

#MONITOR PORTS

snapshotstempdir="/tmp"

function usage (){
echo -e "Usage: $(basename ${0}) [interval_in_seconds --help]\n"
echo -e "\tinterval_in_seconds\tHow often to monitor in seconds"
echo -e "\t--help\tThis help menu ;)"

}

function takesnapshot (){
lsof -i -P | grep -iv command
}

if [ -z ${1} ] || [ $(awk '{tolower($0)}' <<< ${1}) == "--help" ]; then
usage
exit 1
fi

interval=${1}

echo "Monitoring started. Interval ${interval}. Ctrl-C to exit"

while :; do
$(takesnapshot>${snapshotstempdir}/oldsnapshot)
sleep ${interval}
$(take
snapshot>${snapshotstempdir}/newsnapshot)
diffsnapshots=$(diff ${snapshotstempdir}/oldsnapshot ${snapshotstempdir}/newsnapshot)
if [[ ! -z ${diff
snapshots} ]];then
echo -e "${diffsnapshots}"
fi
done

I originally wanted the noscript to output custom output instead of just echoing ${diff\
snapshots} but i was having trouble parsing the data. I'll give it another go some other time. In the mean time I kinda like the output of the diff util.

https://redd.it/zgczs4
@r_bash
[First Script] Issues with a command within a variable.

I have the following noscript \[part of it\]

&#x200B;

echo ""
echo "-----------------------------------"
echo "-----------------------------------"
echo "Scan for an IP within system logs!"
echo "-----------------------------------"
echo "-----------------------------------"
sleep 3s
echo "Please provide required IP:"
read ip
echo "------------------------------"
echo "IP provided: $ip - Scanning..."
echo "------------------------------"
sleep 3s

echo "--------------------"
echo "Apache Error Log Results:"
grep1=$(grep $ip /usr/local/apache/logs/error_log)
if [$grep1 -eq ""]
then
echo "No Results Found"
fi
sleep 1s
echo "--------------------"

&#x200B;

And when running it with an example IP I get the following

[root@server1 bashnoscripting]# ./ipsearch.sh

-----------------------------------
-----------------------------------
Scan for an IP within system logs!
-----------------------------------
-----------------------------------
Please provide required IP:
23.111.182.195
------------------------------
IP provided: 23.111.182.195 - Scanning...
------------------------------
--------------------
Apache Error Log Results:
./ipsearch.sh: line 20: [[Tue: command not found
--------------------

&#x200B;

When I run it with [0.0.0.](https://0.0.0.0)[0](https://0.0.0.0) I get the following

Apache Error Log Results:
./ipsearch.sh: line 20: [Binary: command not found
--------------------

&#x200B;

What am I doing wrong here? Any advice would be appreciated.

&#x200B;

Thank you!

https://redd.it/zgiffl
@r_bash
upnup - generate licenses from the command line

upnup

Hi all! I've been using @capainsafia's legit for some time now, and got inspired to rewrite this simple utility in bash.

I haven't written an extensive bash noscript for some time now and wanted to dive in again and try my hand at recreating this nodejs utility in one of my favorite languages.

I humbly present for your consideration upnup. It is more or less a drop in replacement for legit, but written in bash.

If you're not familiar with legit, it essentially generates standard a LICENSE for you from the command line, and upnup more or less does the same thing.

If you'd rather not visit github for some reason, I have the project mirrored on codeberg.

This is only my second time creating a bash noscript that was more than 50 lines, so my code probably leaves a lot to be desired. Constructive criticism is always welcome, and thanks in advance if you took the time to read this and check it out!

https://redd.it/zgip8a
@r_bash
Hey guys, can someone please help me with this? I tried it like 5 times, and it didn't work at all.
https://redd.it/zglfh3
@r_bash
Can someone please help me with this. I am really stuck on this question.
https://redd.it/zgmqe3
@r_bash
Learning Tracks and Certifications

Hi All,

I am trying to gain deeper knowledge on all things Bash, starting with noscripting (I am already proficient with normal use/commands). I took the course from Codecadeny and that was great because it provided excercises and a mock shell that provided guidance on debugging and feedback on errors.

This seems to be very common for programming languages, but most learning websites I can find are strictly audiovisual, with limited excercises and they just provide answers, no interactive shell to debug with.

Is anyone aware of any courses similar to the codecademy one please? Further, are there any certifications or highly rated courses specific to Bash anyone could please recommend? Its fine if these courses are not free.

Im in an industry where navigating Bash is critical and being able to noscript could really improve my earning potential, but there is no benefit right now to taking the next step into a full programming language.

Thanks in advance.

https://redd.it/zgu5bb
@r_bash
Emojis in your PS1! Create a christmas themed PS1

To create a Christmas-themed bash prompt, you can use the PS1
variable to customise your prompt. For example, you could use the following bash code to create a prompt that includes a Christmas tree, some snowflakes, and the current time:

PS1="\n🎄 $(date +"%T") \n☃️ "

This code sets the PS1 variable to a newline, a Christmas tree emoji, the current time in 24-hour format, another newline, a snowflake emoji, and a space.

You can also add additional elements to the prompt, such as the current working directory or your username, by using the \\w and \\u escape sequences, respectively. For example:

PS1="\n🎄 \u@\h \w $(date +"%T") \n☃️ "

This code adds the username and hostname to the prompt, as well as the current working directory.

You can add this code to your .bashrc file to make the changes permanent.

Please note that the appearance of the prompt may vary depending on the font and terminal emulator you are using. Emojis may not display properly on all systems.

Works great in Gnome Terminal though:

&#x200B;

https://preview.redd.it/eypze1v01v4a1.png?width=456&format=png&auto=webp&s=ddb629fd5fa0e29dcd328567e8f0ab74b9d3244a

This post was written as part of my #FoodBankFriday efforts to raise money for my local foodbank. If you found it interesting or useful and would like to show a little appreciation - a small donation would be gratefully recieved!

https://www.justgiving.com/page/fbf-joseph-edmonds

https://redd.it/zgv3l7
@r_bash
Assistance using sed and regex to filter printer queue names

Look for a bit of sed/regex manipulation help here.


Im trying to use the lpstat command to get a list of specific print queues. Once I get a found set of queue names, they will be deleted later.


Criteria

\-Only display the queues that do NOT contain "_IPP" at the end of the queue name (these queues do not need to be deleted later) Im using grep for this now which works.
\-Only display queues that start with "mfp" or "p" (these are my 2 targets to delete later) Trying to use sed but not working.


So in a nutshell, I want to see only printers with the prefix "mfp" or "p" that do NOT contain the "_IPP" suffix.



Example that fails:


queues=$(lpstat -p 2>/dev/null | grep -v _IPP | awk '{print $2}' | sed '/\^mfp/; /\^pb/; /\^pc/')

echo $queues

sed: 1: "/\^$/d; /\^mfp/; /\^pb/; / ...": invalid command code ;

https://redd.it/zh2ouu
@r_bash