Wait command questions
The following example has a wait command 4 times.
if [ $2 == "local" ]; then
case ${srcOS,,} in
ubuntu|debian)
sudo service plexmediaserver $1
wait
linux)
sudo systemctl $1 plexmediaserver
wait
;;
esac
elif [[ $2 == "remote" ]]; then
case ${dstOS,,} in
ubuntu|debian)
ssh user@IP "service plexmediaserver $1"
wait
linux)
ssh user@IP "systemctl $1 plexmediaserver"
wait
;;
esac
fi
Can I delete the 4 wait commands and add 1 wait command after fi ?
if [ <test> ]; then
command foo
else
command bar
fi
wait
For the
https://redd.it/10j1wgs
@r_bash
The following example has a wait command 4 times.
if [ $2 == "local" ]; then
case ${srcOS,,} in
ubuntu|debian)
sudo service plexmediaserver $1
wait
linux)
sudo systemctl $1 plexmediaserver
wait
;;
esac
elif [[ $2 == "remote" ]]; then
case ${dstOS,,} in
ubuntu|debian)
ssh user@IP "service plexmediaserver $1"
wait
linux)
ssh user@IP "systemctl $1 plexmediaserver"
wait
;;
esac
fi
Can I delete the 4 wait commands and add 1 wait command after fi ?
if [ <test> ]; then
command foo
else
command bar
fi
wait
For the
ssh user@IP command is wait going to wait for ssh or the command?https://redd.it/10j1wgs
@r_bash
reddit
Wait command questions
The following example has a wait command 4 times. if [[ $2 == "local" ]]; then case ${src_OS,,} in ubuntu|debian) ...
( command & )
Anyone able to explain this syntax to run command in background and attached to init
( command & )
Cheers
https://redd.it/10iv1dl
@r_bash
Anyone able to explain this syntax to run command in background and attached to init
( command & )
Cheers
https://redd.it/10iv1dl
@r_bash
reddit
( command & )
Anyone able to explain this syntax to run command in background and attached to init ( command & ) Cheers
How to extract the (unknown) middle part of a filename with fixed beginnings and ends?
I have files with names ABC. The middle part B changes, while A and C are fixed. A ends with a `-`, C starts with a `[`. I have the names in a variable `var`.
I know it is possible to get rid of A with `"${var#*-}"`, leaving BC.
I know it is possible to get rid of C with `"${var%\[*}"`, leaving AB.
Is it possible to combine this into one step, so that only B is left? What would be the best way to have this in a quick oneliner with
for var in *; do <stuff with B>; done
while not knowing the value of B?
https://redd.it/10j9qba
@r_bash
I have files with names ABC. The middle part B changes, while A and C are fixed. A ends with a `-`, C starts with a `[`. I have the names in a variable `var`.
I know it is possible to get rid of A with `"${var#*-}"`, leaving BC.
I know it is possible to get rid of C with `"${var%\[*}"`, leaving AB.
Is it possible to combine this into one step, so that only B is left? What would be the best way to have this in a quick oneliner with
for var in *; do <stuff with B>; done
while not knowing the value of B?
https://redd.it/10j9qba
@r_bash
reddit
How to extract the (unknown) middle part of a filename with fixed...
I have files with names ABC. The middle part B changes, while A and C are fixed. A ends with a `-`, C starts with a `[`. I have the names in a...
how to read file but ignore first and last line?
I have a .txt file which contains hundreds of numbers in a single column.
This file is used for some other program and I don't wanna modify it.
The file looks like:
>
>
>
>
>
>
>
>
>
>
>
Both the first and last lines are not numbers but strings, not sure how ti ignore them while only extracting the number.
>
>
>
>
>
>
>
>
>
>
>
This is what I currently have..
https://redd.it/10jeg9t
@r_bash
I have a .txt file which contains hundreds of numbers in a single column.
This file is used for some other program and I don't wanna modify it.
The file looks like:
>
frequency in wavenumber >
>
1231.123 >
>
222.2222 >
>
3343.4311 >
>
.... >
>
end of fileBoth the first and last lines are not numbers but strings, not sure how ti ignore them while only extracting the number.
>
input="scanned_freq.dat" >
>
# using IFS to remove all leading and trailing whitespace >
>
while IFS= read -r line >
>
do >
>
echo "$line" >
>
done < "$input"This is what I currently have..
https://redd.it/10jeg9t
@r_bash
reddit
how to read file but ignore first and last line?
I have a .txt file which contains hundreds of numbers in a single column. This file is used for some other program and I don't wanna modify...
How to return just directory name of one directory back?
I want to return only the name of the directory that is one directory "up" from the current.
For example, if my current path is:
/dir1/dir2/dir3/dir4/current-dir/
I only want to extract dir4
What would be the best way to do this?
https://redd.it/10jhmi5
@r_bash
I want to return only the name of the directory that is one directory "up" from the current.
For example, if my current path is:
/dir1/dir2/dir3/dir4/current-dir/
I only want to extract dir4
What would be the best way to do this?
https://redd.it/10jhmi5
@r_bash
reddit
How to return just directory name of one directory back?
I want to return only the name of the directory that is one directory "up" from the current. For example, if my current path is: ...
Beginner can't make a simple noscript to work
1 #!/bin/bash
1
2 bt="bluetoothctl info 74:45:CE:90:9C:4F | grep Connected"
3 if [ $bt='Connected: yes' ]
4 then
5 dunstify "headphones connected"
6 else
7 dunstify "unknown error"
8 fi
What is the wrong here? It always prints the 'headphones connected' -line even if my headphones isn't connected.
I know awk would be much better, but I couldn't make that to work. (The "Connected: yes" is the 10th line of that command)
https://redd.it/10jjxd9
@r_bash
1 #!/bin/bash
1
2 bt="bluetoothctl info 74:45:CE:90:9C:4F | grep Connected"
3 if [ $bt='Connected: yes' ]
4 then
5 dunstify "headphones connected"
6 else
7 dunstify "unknown error"
8 fi
What is the wrong here? It always prints the 'headphones connected' -line even if my headphones isn't connected.
I know awk would be much better, but I couldn't make that to work. (The "Connected: yes" is the 10th line of that command)
https://redd.it/10jjxd9
@r_bash
reddit
Beginner can't make a simple noscript to work
1 #!/bin/bash 1 2 bt="bluetoothctl info 74:45:CE:90:9C:4F | grep Connected" 3 if [[ $bt='Connected: yes' ]] 4...
What is the proper way to relatively source a file?
I am in the toplevel directory inside a project. There is a directory
When I run
Why does
I'm on Bash 5.2.15.
https://redd.it/10jipn2
@r_bash
I am in the toplevel directory inside a project. There is a directory
test and inside that is a bash file named test.sh. This file tries to source another bash file in the same directory called testlib.When I run
./test/test.sh, it fails with "file not found" if I do source testlib or source ./testlib inside test.sh, but will work when I do source ${0##*/}/testlib, which I think is hideous even though I know exactly what it's doing (I also think using dirname "$0" there is just as hideous).Why does
source not automatically include the directory of the file trying to do the sourcing so you can do relative sourcing? This seems counterintuitive for some reason (probably because all other languages I've worked with permit it). Is this for security reasons?I'm on Bash 5.2.15.
https://redd.it/10jipn2
@r_bash
reddit
What is the proper way to relatively source a file?
I am in the toplevel directory inside a project. There is a directory `test` and inside that is a bash file named `test.sh`. This file tries to...
Concept: Self configuring noscript in BASH
Smaller noscripts, I place a bunch of declare settingvariable="Setting goes here" at the beginning of my noscript, right after the #!/bin/bash
But what if I could edit those variables without editing the actual file.
I am working towards having ./noscript.sh --config settingvariable fetch the variable and display it's setting, then allow me to either press return to keep it as is, or to type in a new variable.
The question I had is, can I get get a noscript to read and write to itself? This is what I came up with...
Now run it as follows:
$ ./test.sh Hello
$ ./test.sh World
​
$ cat test.sh
https://redd.it/10jowj9
@r_bash
Smaller noscripts, I place a bunch of declare settingvariable="Setting goes here" at the beginning of my noscript, right after the #!/bin/bash
But what if I could edit those variables without editing the actual file.
I am working towards having ./noscript.sh --config settingvariable fetch the variable and display it's setting, then allow me to either press return to keep it as is, or to type in a new variable.
The question I had is, can I get get a noscript to read and write to itself? This is what I came up with...
#!/bin/bash#Name this file test.sh# $ chmod +x test.sh#Usage: $ ./test.sh <comment to insert between START and STOP>###START######STOP###start=$( cat -n test.sh | grep "###START###" | head -1 | awk '{print $1;}' )stop=$( cat -n test.sh | grep "###STOP###" | head -1 | awk '{print $1;}' )echo "Start of config: $start"echo "Stop of config: $stop"sed -i $stop' i #'$1 `test.sh`Now run it as follows:
$ ./test.sh Hello
$ ./test.sh World
​
$ cat test.sh
https://redd.it/10jowj9
@r_bash
Brace expansion syntax bug?
I may be doing this incorrectly:
epitaph64@debian64-laptop:~$ echo -e {1..5}{a,b}"\n"
1a
1b
2a
2b
3a
3b
4a
4b
5a
5b
I've tested this more recently on Ubuntu 22.0.4 using Bash version 5.1.16(1)
Does anyone one know why it's like this? Having the unnecessary spaces for all but the first line of output looks disordered so it seems like a bug...
https://redd.it/10jfhpi
@r_bash
I may be doing this incorrectly:
epitaph64@debian64-laptop:~$ echo -e {1..5}{a,b}"\n"
1a
1b
2a
2b
3a
3b
4a
4b
5a
5b
I've tested this more recently on Ubuntu 22.0.4 using Bash version 5.1.16(1)
Does anyone one know why it's like this? Having the unnecessary spaces for all but the first line of output looks disordered so it seems like a bug...
https://redd.it/10jfhpi
@r_bash
Reddit
r/bash - Brace expansion syntax bug?
Posted in the bash community.
bash noscript to copy password from a different file
Hey everyone, having a project deadline and would love some help please.
i have the below noscript set to run and get the credentials from another file but i keep getting an error saying credentials file cannot be found. would love some help please. i will also take any other ideas for a better noscript.
\#!/bin/bash
fail() { printf "%s\\n" "$2"; exit $1; }
credsfile=/home/njames/.config/windows.credentials
[[ -e "$credsfile" \]\] || fail 1 "Credentials file '$credsfile' not found"
source "$credsfile"
[[ -n "PKR_VAR_vsphere_password" \]\] || fail 1 "PKR_VAR_vsphere_password not set in '$credsfile'"
[[ -n "PKR_VAR_winadmin_password" \]\] || fail 1 "PKR_VAR_winadmin_password not set in '$credsfile'"
packer init .
packer validate .
packer build .
https://redd.it/10jwg35
@r_bash
Hey everyone, having a project deadline and would love some help please.
i have the below noscript set to run and get the credentials from another file but i keep getting an error saying credentials file cannot be found. would love some help please. i will also take any other ideas for a better noscript.
\#!/bin/bash
fail() { printf "%s\\n" "$2"; exit $1; }
credsfile=/home/njames/.config/windows.credentials
[[ -e "$credsfile" \]\] || fail 1 "Credentials file '$credsfile' not found"
source "$credsfile"
[[ -n "PKR_VAR_vsphere_password" \]\] || fail 1 "PKR_VAR_vsphere_password not set in '$credsfile'"
[[ -n "PKR_VAR_winadmin_password" \]\] || fail 1 "PKR_VAR_winadmin_password not set in '$credsfile'"
packer init .
packer validate .
packer build .
https://redd.it/10jwg35
@r_bash
Reddit
r/bash - bash noscript to copy password from a different file
Posted in the bash community.
Why does la invoke ls?
$ la
manifest.json ...
I can't find a symlink from
https://redd.it/10jwazy
@r_bash
$ la
manifest.json ...
I can't find a symlink from
la to ls in /usr/bin.https://redd.it/10jwazy
@r_bash
Reddit
r/bash - Why does la invoke ls?
Posted in the bash community.
how to send a "enter" press?
How do i answer prompts like (y/n), (yes/no) or enter?
https://redd.it/10k24bf
@r_bash
How do i answer prompts like (y/n), (yes/no) or enter?
https://redd.it/10k24bf
@r_bash
Reddit
r/bash - how to send a "enter" press?
Posted in the bash community.
How to insert text after a specific line in a file?
Example
​
specific line
text
text 2
I now want to add "text 3" under "specific line" so it looks like this
specific line
text 3
text
text 2
https://redd.it/10k3fg1
@r_bash
Example
​
specific line
text
text 2
I now want to add "text 3" under "specific line" so it looks like this
specific line
text 3
text
text 2
https://redd.it/10k3fg1
@r_bash
Reddit
r/bash - How to insert text after a specific line in a file?
Posted in the bash community.
Simple, open-source, lightweight stress tool
https://github.com/ddosify/ddosify
https://redd.it/10kdt5g
@r_bash
https://github.com/ddosify/ddosify
https://redd.it/10kdt5g
@r_bash
GitHub
GitHub - getanteon/anteon: Anteon (formerly Ddosify): eBPF-based Kubernetes Monitoring and Performance Testing
Anteon (formerly Ddosify): eBPF-based Kubernetes Monitoring and Performance Testing - getanteon/anteon
Recognize any text or characters at the end of a filename before the extension
I am creating an inotify-tools noscript and this currently works for any file that looks something like `2023-01-24_14-59-22.mp4`:
inotifywait --recursive --monitor --quiet -e moved_to -e close_write --format '%w%f' --include [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9]-[0-9][0-9]-[0-9][0-9].mp4 /watch/folder
Occasionally, an mp4 file might arrive as such: `2023-01-24_14-59-22_edit.mp4` or `2023-01-24_14-59-22_edit_edit.mp4` or other random text or characters at the end of the date/time and before the .mp4 extension. How do I watch for these files as well? I tried `*` or `$` or `\w` and stuff like that and it didn't work, but I'm not entirely understanding the bash documentation. Can someone point me in the right direction?
https://redd.it/10kd8rd
@r_bash
I am creating an inotify-tools noscript and this currently works for any file that looks something like `2023-01-24_14-59-22.mp4`:
inotifywait --recursive --monitor --quiet -e moved_to -e close_write --format '%w%f' --include [0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]_[0-9][0-9]-[0-9][0-9]-[0-9][0-9].mp4 /watch/folder
Occasionally, an mp4 file might arrive as such: `2023-01-24_14-59-22_edit.mp4` or `2023-01-24_14-59-22_edit_edit.mp4` or other random text or characters at the end of the date/time and before the .mp4 extension. How do I watch for these files as well? I tried `*` or `$` or `\w` and stuff like that and it didn't work, but I'm not entirely understanding the bash documentation. Can someone point me in the right direction?
https://redd.it/10kd8rd
@r_bash
Reddit
r/bash - Recognize any text or characters at the end of a filename before the extension
1 vote and 3 comments so far on Reddit
Diff and Grep inside IF statement
Hi Guys
How do I get this command to be either true or false
diff $LAST $CURRENT | grep --exclude-dir=* '^<' >>$EMAILTEXT
Basically if there is no difference between last and current give me a false and if there is a difference give me a true and output the results to email text.
Thanks
https://redd.it/10kitld
@r_bash
Hi Guys
How do I get this command to be either true or false
diff $LAST $CURRENT | grep --exclude-dir=* '^<' >>$EMAILTEXT
Basically if there is no difference between last and current give me a false and if there is a difference give me a true and output the results to email text.
Thanks
https://redd.it/10kitld
@r_bash
Reddit
r/bash - Diff and Grep inside IF statement
Posted in the bash community.
Check for string of command output
How can I check for a string from a command output? For example, if I execute:
MP4Box -info $INPUTFILE
And if the file is incomplete, it outputs:
[iso file] Incomplete box mdat - start 40 size 2998060684
[iso file] Incomplete file while reading for dump - aborting parsing
File has no movie (moov) - static data container
I want my noscript to pick up on the word "Incomplete" or something. For example, my bash noscript:
#!/bin/bash
FILENAME=*.mp4
WATCHDIR=/path/to/directory
/usr/bin/inotifywait \
--recursive \
--monitor \
--quiet \
-e movedto \
-e closewrite \
--format '%w%f' \
--includei "$FILENAME" \
"$WATCHDIR" \
| while read -r INPUTFILE; do
echo ""
echo "Transfer stopped. Checking if mp4 file is complete:"
echo ""
if [ $(MP4Box -info $INPUT_FILE) == "Incomplete" ];
then
echo ""
echo "Transfer interrupted."
else
echo ""
echo "Transfer complete."
fi
done
No matter what happens, I cannot get "Transfer interrupted" to echo out even when I interrupt the transfer and the output shows
I have tried grep, and every which option I can think of, and it won't work for me. What am I doing wrong?
https://redd.it/10knklt
@r_bash
How can I check for a string from a command output? For example, if I execute:
MP4Box -info $INPUTFILE
And if the file is incomplete, it outputs:
[iso file] Incomplete box mdat - start 40 size 2998060684
[iso file] Incomplete file while reading for dump - aborting parsing
File has no movie (moov) - static data container
I want my noscript to pick up on the word "Incomplete" or something. For example, my bash noscript:
#!/bin/bash
FILENAME=*.mp4
WATCHDIR=/path/to/directory
/usr/bin/inotifywait \
--recursive \
--monitor \
--quiet \
-e movedto \
-e closewrite \
--format '%w%f' \
--includei "$FILENAME" \
"$WATCHDIR" \
| while read -r INPUTFILE; do
echo ""
echo "Transfer stopped. Checking if mp4 file is complete:"
echo ""
if [ $(MP4Box -info $INPUT_FILE) == "Incomplete" ];
then
echo ""
echo "Transfer interrupted."
else
echo ""
echo "Transfer complete."
fi
done
No matter what happens, I cannot get "Transfer interrupted" to echo out even when I interrupt the transfer and the output shows
Incomplete file while reading for dump - aborting parsing.I have tried grep, and every which option I can think of, and it won't work for me. What am I doing wrong?
https://redd.it/10knklt
@r_bash
Reddit
r/bash - Check for string of command output
Posted in the bash community.
decrypt a gpg file inside a noscript
would love to get some input on this please. having some issues with getting the noscript to decrypt the gpg file. i am using the file to store passwords i need to to run the noscript. any help would be appreciated. thanks
\#!/bin/bash
\# Decrypt the file using the passphrase
gpg --decrypt-files --batch --yes --passphrase "$(cat passphrase.txt)" encrypted_passwords.gpg -o decrypted_passwords
\# Assign the decrypted passwords to variables
password1="$(cut -d ',' -f1 decrypted_passwords)"
password2="$(cut -d ',' -f2 decrypted_passwords)"
\# first password as an argument
PKR_VAR_vsphere_password= "$password1"
\# second password as an argument
PKR_VAR_winadmin_password="$password2"
https://redd.it/10kunza
@r_bash
would love to get some input on this please. having some issues with getting the noscript to decrypt the gpg file. i am using the file to store passwords i need to to run the noscript. any help would be appreciated. thanks
\#!/bin/bash
\# Decrypt the file using the passphrase
gpg --decrypt-files --batch --yes --passphrase "$(cat passphrase.txt)" encrypted_passwords.gpg -o decrypted_passwords
\# Assign the decrypted passwords to variables
password1="$(cut -d ',' -f1 decrypted_passwords)"
password2="$(cut -d ',' -f2 decrypted_passwords)"
\# first password as an argument
PKR_VAR_vsphere_password= "$password1"
\# second password as an argument
PKR_VAR_winadmin_password="$password2"
https://redd.it/10kunza
@r_bash
Reddit
r/bash - decrypt a gpg file inside a noscript
Posted in the bash community.
Bash aliases best practice
I am a junior/mid data-scientist and developer and it's been years the first thing I do on a new workstation is to add a couple of aliases I cannot live without. But I want to step up a little in terms of best practices. And I have a couple of questions.
The first one: how long can my .bash_aliases file grow? Mine are about 10-20 lines total, but I have so many ideas of adding new stuff. Not sure whether it is a good practice to automate / simplify things to myself or it would just make me forget about the actual syntax of some complex commands.
The second one: do you add custom functions in your .bash_aliases or do they go elsewhere? I have a couple of functions that _really_ are a quick lifehacks such as:
function cds {
cd $1 && ls -lah
}
How would you organize such functions in order to avoid future yourself any headache?
Thanks!
https://redd.it/10kxidg
@r_bash
I am a junior/mid data-scientist and developer and it's been years the first thing I do on a new workstation is to add a couple of aliases I cannot live without. But I want to step up a little in terms of best practices. And I have a couple of questions.
The first one: how long can my .bash_aliases file grow? Mine are about 10-20 lines total, but I have so many ideas of adding new stuff. Not sure whether it is a good practice to automate / simplify things to myself or it would just make me forget about the actual syntax of some complex commands.
The second one: do you add custom functions in your .bash_aliases or do they go elsewhere? I have a couple of functions that _really_ are a quick lifehacks such as:
function cds {
cd $1 && ls -lah
}
How would you organize such functions in order to avoid future yourself any headache?
Thanks!
https://redd.it/10kxidg
@r_bash
Reddit
r/bash on Reddit: Bash aliases best practice
Posted by u/ka1ikasan - No votes and 3 comments
Boredom PS1 project
I decided I was going to learn a bit more about the
I liked the setup a lot, so I used the same configuration on my home work station and the termux installation on my phone.
The setup worked great until I started running the wrong commands on the wrong system. For good reason, as the prompts were identical, I decided to see if I could setup my prompt to show a different prompt for an ssh connection.
I had a fun time getting that to actually work. I was making it more complicated than it needed to be, but wait there's more. Now when I connect to my ssh server it shows the IP address of the login before last rather than the current login. With a remote login it is kind of useless to see that you just logged in but it is useful to see if someone logged in before you... Just in case you know.
Once I got that working I decided to take it to a whole new level of ridiculous... Solely because why not. I wanted to see what it would take to show in my local terminal that there was an active connection. Next was to make the command search for an active connection on my SSH port, if one was active it ran one prompt and if no connection, another. it took some trial and error to get that running correctly. Once it was running, I found that it would only update when a new terminal session was opened or if I sourced .bashrc. Which in and of itself wasn't that bad but there had to be a way to get that info without sourcing or starting a new terminal session.
After a bit more trial and error and research on the topic i found the answer to getting that info to update after each command. The
Now not only will it show an active connection, it will show the last IP to login to that users account. It will also search through a predefined list of known IP addresses and if they match the IP address will be green to denote a known IP and display a custom string so you don't have to look at your own IP addresses. If it returns an unknown IP address it will turn red.
Then to add the finishing touches to this ridiculous project, a red/green light for inactive/active connections respectively, just because I could
I'd like to hear how you all would make it better/different. It was a fun project to learn about the prompt and make sure I used proper escaping. So here is my absolutely, totally, over the top, unnecessary PS1 prompt. Complete with functions and PROMPT_COMMAND
​
# This will show if there is an active SSH connection after each command is executed.
# Shows second to last login of current user; best used with AllowUsers in sshdconfig
psONEssh()
{
if [ "$(last | sed -n '2p' | awk '{ print $3 }')" =~ ("XXX.XXX."*|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX") ]; then
printf %b "\[\\e1;32m\\KNOWN CONNECTION\n"
else
last | sed -n '2p' | awk '{ print $3 }'
fi
}
psONElocal() # Shows the last login from the current user; best used with AllowUsers in sshdconfig
{
if [ "$(lastlog | grep $(whoami) | awk '{ print $3 }')" =~ ("XXX.XXX."*|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX") ]; then
printf %b "\[\\e1;32m\\KNOWN CONNECTION\n"
else
lastlog | grep $(whoami) | awk '{ print $3 }'
fi
}
promptcommand()
{
if [ -n $SSH_CLIENT ]; then
PS1="\[\\e1;31m\\🟢 $(psONEssh)\\[\\e[0m\\]\\[\\e[1;33m\\]\n\w/\n\\[\\e[0m\\]\\[\\e[1;31m\\]𝝅 \\[\\e[0m\\]\\[\\e[1;32m\\] "
else
ss -tn src :8222 | grep ESTAB &> /dev/null
if [ $? -ne "1" ]; then
PS1="\\[\\e[1;31m\\]🟢 $(psONElocal)\[\\e1;33m\\\n\w/\n\[\\e0m\\\[\\e1;31m\\𝝅\[\\e0m\\\[\\e1;32m\\ "
else
PS1="\[\\e1;31m\\🔴
I decided I was going to learn a bit more about the
PS1 prompt. I started out with a nice easy prompt with \w on one line and the prompt with a custom user token 𝝅 rather than the stock $ on the next.I liked the setup a lot, so I used the same configuration on my home work station and the termux installation on my phone.
The setup worked great until I started running the wrong commands on the wrong system. For good reason, as the prompts were identical, I decided to see if I could setup my prompt to show a different prompt for an ssh connection.
I had a fun time getting that to actually work. I was making it more complicated than it needed to be, but wait there's more. Now when I connect to my ssh server it shows the IP address of the login before last rather than the current login. With a remote login it is kind of useless to see that you just logged in but it is useful to see if someone logged in before you... Just in case you know.
Once I got that working I decided to take it to a whole new level of ridiculous... Solely because why not. I wanted to see what it would take to show in my local terminal that there was an active connection. Next was to make the command search for an active connection on my SSH port, if one was active it ran one prompt and if no connection, another. it took some trial and error to get that running correctly. Once it was running, I found that it would only update when a new terminal session was opened or if I sourced .bashrc. Which in and of itself wasn't that bad but there had to be a way to get that info without sourcing or starting a new terminal session.
After a bit more trial and error and research on the topic i found the answer to getting that info to update after each command. The
PROMPT_COMMAND setting was what did the trick. By wrapping the whole command into a function i was able to call it in the PROMPT_COMMAND which gets evaluated after every command runs.Now not only will it show an active connection, it will show the last IP to login to that users account. It will also search through a predefined list of known IP addresses and if they match the IP address will be green to denote a known IP and display a custom string so you don't have to look at your own IP addresses. If it returns an unknown IP address it will turn red.
Then to add the finishing touches to this ridiculous project, a red/green light for inactive/active connections respectively, just because I could
I'd like to hear how you all would make it better/different. It was a fun project to learn about the prompt and make sure I used proper escaping. So here is my absolutely, totally, over the top, unnecessary PS1 prompt. Complete with functions and PROMPT_COMMAND
​
# This will show if there is an active SSH connection after each command is executed.
# Shows second to last login of current user; best used with AllowUsers in sshdconfig
psONEssh()
{
if [ "$(last | sed -n '2p' | awk '{ print $3 }')" =~ ("XXX.XXX."*|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX") ]; then
printf %b "\[\\e1;32m\\KNOWN CONNECTION\n"
else
last | sed -n '2p' | awk '{ print $3 }'
fi
}
psONElocal() # Shows the last login from the current user; best used with AllowUsers in sshdconfig
{
if [ "$(lastlog | grep $(whoami) | awk '{ print $3 }')" =~ ("XXX.XXX."*|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX"|"XXX.XXX.XXX.XXX") ]; then
printf %b "\[\\e1;32m\\KNOWN CONNECTION\n"
else
lastlog | grep $(whoami) | awk '{ print $3 }'
fi
}
promptcommand()
{
if [ -n $SSH_CLIENT ]; then
PS1="\[\\e1;31m\\🟢 $(psONEssh)\\[\\e[0m\\]\\[\\e[1;33m\\]\n\w/\n\\[\\e[0m\\]\\[\\e[1;31m\\]𝝅 \\[\\e[0m\\]\\[\\e[1;32m\\] "
else
ss -tn src :8222 | grep ESTAB &> /dev/null
if [ $? -ne "1" ]; then
PS1="\\[\\e[1;31m\\]🟢 $(psONElocal)\[\\e1;33m\\\n\w/\n\[\\e0m\\\[\\e1;31m\\𝝅\[\\e0m\\\[\\e1;32m\\ "
else
PS1="\[\\e1;31m\\🔴