How does adding a new value to an array pass back to the caller?
Hello, I'm facing a problem when trying to implement an extension to some bash code.
Currently, a file is parsed for key/value pairs and they are collected as dynamic names with something like this in the end:
scopes+=("$current_scope")
variables+=("$variable")
values+=("$value")
At the end, in a different function, I iterate those arrays and collect my expected names.
The extension entails parsing some array and structures of strings, rather than only key/value.
I got to the point of internalising the parsed tokens and found out that I would be needing to eval the assignment, since (ignore the dumb quoting here):
"${arr_name}[$arr_idx]"="${arr_val}"
Can't be expanded at the correct time (Gives "unknown command" error, but copy-pasting the expansion printed in the error is accepted on an interactive shell).
This lead to this portion of my noscript were I expand the things only when they are in the expected format:
if [[ "$arr_var" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && [[ "$arr_val_idx" =~ ^[0-9]+$ ]]; then
# Safe assignment using eval after validation
eval "${arr_var}[$arr_val_idx]=\"$(printf '%q' "$arr_val")\""
And for structures, the same thing later:
if [[ "$struct_name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && [[ "$struct_var_name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
# Safe assignment using eval after validation
eval "${struct_name}[$struct_var_name]=\"$(printf '%q' "$struct_val")\""
This seems fine, and at the end of my function I can try to read a test value:
mytry="${scope_foo[bar]}"
printf "TRY: {$mytry}\n"
This works as expected, and the value is there.
The issue arises from the fact that the definition seems to be local to the function where the eval happens.
If I put the previous test outside of the function doing the eval, it does not work.
My question is, why does the "scopes+=("thing")" works as expected after the assignign function returns, but the eval does not?
To test this behaviour, i tried:
myfn() {
arr=a; idx=0; val=foo;
eval "${arr}[$idx]=\"$(printf '%q' "$val")\""
}
$ myfn
$ echo ${a[0]}
>foo
This works as expected and the fact the function returns doesn't seems to matter, the value is there.
Can I get some guidance?
https://redd.it/1fld2ks
@r_bash
Hello, I'm facing a problem when trying to implement an extension to some bash code.
Currently, a file is parsed for key/value pairs and they are collected as dynamic names with something like this in the end:
scopes+=("$current_scope")
variables+=("$variable")
values+=("$value")
At the end, in a different function, I iterate those arrays and collect my expected names.
The extension entails parsing some array and structures of strings, rather than only key/value.
I got to the point of internalising the parsed tokens and found out that I would be needing to eval the assignment, since (ignore the dumb quoting here):
"${arr_name}[$arr_idx]"="${arr_val}"
Can't be expanded at the correct time (Gives "unknown command" error, but copy-pasting the expansion printed in the error is accepted on an interactive shell).
This lead to this portion of my noscript were I expand the things only when they are in the expected format:
if [[ "$arr_var" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && [[ "$arr_val_idx" =~ ^[0-9]+$ ]]; then
# Safe assignment using eval after validation
eval "${arr_var}[$arr_val_idx]=\"$(printf '%q' "$arr_val")\""
And for structures, the same thing later:
if [[ "$struct_name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]] && [[ "$struct_var_name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
# Safe assignment using eval after validation
eval "${struct_name}[$struct_var_name]=\"$(printf '%q' "$struct_val")\""
This seems fine, and at the end of my function I can try to read a test value:
mytry="${scope_foo[bar]}"
printf "TRY: {$mytry}\n"
This works as expected, and the value is there.
The issue arises from the fact that the definition seems to be local to the function where the eval happens.
If I put the previous test outside of the function doing the eval, it does not work.
My question is, why does the "scopes+=("thing")" works as expected after the assignign function returns, but the eval does not?
To test this behaviour, i tried:
myfn() {
arr=a; idx=0; val=foo;
eval "${arr}[$idx]=\"$(printf '%q' "$val")\""
}
$ myfn
$ echo ${a[0]}
>foo
This works as expected and the fact the function returns doesn't seems to matter, the value is there.
Can I get some guidance?
https://redd.it/1fld2ks
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Book technical reviewer needed
Hello,
I'm a security consultant and penetration tester. I'm writing a book noscriptd "Bash Shell Scripting for Pentesters". My publisher needs book technical reviewers. From what I understand, the task is basically reading the chapters and checking that the code runs and the content is technically correct.
It doesn't pay, but they do print your name in the book as TR (and maybe short bio, not sure about that), you get a free copy of the book, and a 12 month subnoscription to Packt online with 12 free ebooks.
If you're interested, email AshwinK@packt.com and mention the name of the book.
If you do become a TR for my book, please keep the following in mind:
I have a limited amount of time and deadlines to turn in each chapter (and perform edits later), so don't uncessarily recommend adding content unless it just has to be there. It's more important to check that the content that's already there is correct, clear, and the code works.
https://redd.it/1flfvt9
@r_bash
Hello,
I'm a security consultant and penetration tester. I'm writing a book noscriptd "Bash Shell Scripting for Pentesters". My publisher needs book technical reviewers. From what I understand, the task is basically reading the chapters and checking that the code runs and the content is technically correct.
It doesn't pay, but they do print your name in the book as TR (and maybe short bio, not sure about that), you get a free copy of the book, and a 12 month subnoscription to Packt online with 12 free ebooks.
If you're interested, email AshwinK@packt.com and mention the name of the book.
If you do become a TR for my book, please keep the following in mind:
I have a limited amount of time and deadlines to turn in each chapter (and perform edits later), so don't uncessarily recommend adding content unless it just has to be there. It's more important to check that the content that's already there is correct, clear, and the code works.
https://redd.it/1flfvt9
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
yeet: A BPF tool for observing bash noscript activity.
You just install it and can SQL activity right out of the kernel.
https://yeet.cx/@yeet/execsnoop
https://redd.it/1flrjx2
@r_bash
You just install it and can SQL activity right out of the kernel.
https://yeet.cx/@yeet/execsnoop
https://redd.it/1flrjx2
@r_bash
yeet.cx
@yeet/execsnoop
Discover the latest and most popular yeet packages.
Can someone please describe everything that happens in this syntax and why?
date '+%Y-%m-%d|whoami||a #' |whoami||a #|" |whoami||a # 2>&1
https://redd.it/1fm4fsa
@r_bash
date '+%Y-%m-%d|whoami||a #' |whoami||a #|" |whoami||a # 2>&1
https://redd.it/1fm4fsa
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
I created a bash noscript that sets bright color wallpapers during the day and dark color wallpapers during the night. Only requires a folder with wallpaper images as argument.
https://github.com/TimoKats/CircadianWallpaper
https://redd.it/1fmoq94
@r_bash
https://github.com/TimoKats/CircadianWallpaper
https://redd.it/1fmoq94
@r_bash
GitHub
GitHub - TimoKats/CircadianWallpaper: Bash noscript that selects a brighter wallpaper during the day and a darker wallpaper during…
Bash noscript that selects a brighter wallpaper during the day and a darker wallpaper during the night. - TimoKats/CircadianWallpaper
Issue command simultaneously to multiple servers ?
Hi,
I have the below code which loops through a set of server and get the IP addresses in range of 10.42.8 from it, then goes into each server in the IP and runs TSSI command.
function findworkers ()
{
knsw=$(kubectl get nodes -A -o name | grep worker)
for knodew in $knsw;
do
podres=$( echo $knodew | cut -c 6- )
echo "IP Addresses Found in $podres"
ssh -q $podres arp -n | grep 10.42.8 | grep ether | awk '{print $1}'
for rruaddr in $(ssh -q $podres arp -n | grep 10.42.8 | grep ether | awk '{print $1}')
do
ssh -q $podres ssh -q $rruaddr tssi
done
done
}
The output of the above command is as below.
IP Addresses Found in bai-ran-cluster-worker1
10.42.8.11
10.42.8.3
sh: tssi: not found
sh: tssi: not found
IP Addresses Found in bai-ran-cluster-worker2
10.42.8.30
10.42.8.24
TX 1 TSSI: 23.3428 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: 22.8387 dBm
TX 4 TSSI: -inf dBm
TX 1 TSSI: -8.8506 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: -10.0684 dBm
TX 4 TSSI: -inf dBm
What happens is it runs the TSSI all together for all the IP addresses found.
I'm unable to figure out how to run TSSI for each IP so the expected output is
IP Addresses Found in bai-ran-cluster-worker2
10.42.8.30
TX 1 TSSI: 23.3428 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: 22.8387 dBm
TX 4 TSSI: -inf dBm
10.42.8.24
TX 1 TSSI: -8.8506 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: -10.0684 dBm
TX 4 TSSI: -inf dBm
Any thoughts on how to write the loop for this ?
Thanks..
https://redd.it/1fmsftd
@r_bash
Hi,
I have the below code which loops through a set of server and get the IP addresses in range of 10.42.8 from it, then goes into each server in the IP and runs TSSI command.
function findworkers ()
{
knsw=$(kubectl get nodes -A -o name | grep worker)
for knodew in $knsw;
do
podres=$( echo $knodew | cut -c 6- )
echo "IP Addresses Found in $podres"
ssh -q $podres arp -n | grep 10.42.8 | grep ether | awk '{print $1}'
for rruaddr in $(ssh -q $podres arp -n | grep 10.42.8 | grep ether | awk '{print $1}')
do
ssh -q $podres ssh -q $rruaddr tssi
done
done
}
The output of the above command is as below.
IP Addresses Found in bai-ran-cluster-worker1
10.42.8.11
10.42.8.3
sh: tssi: not found
sh: tssi: not found
IP Addresses Found in bai-ran-cluster-worker2
10.42.8.30
10.42.8.24
TX 1 TSSI: 23.3428 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: 22.8387 dBm
TX 4 TSSI: -inf dBm
TX 1 TSSI: -8.8506 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: -10.0684 dBm
TX 4 TSSI: -inf dBm
What happens is it runs the TSSI all together for all the IP addresses found.
I'm unable to figure out how to run TSSI for each IP so the expected output is
IP Addresses Found in bai-ran-cluster-worker2
10.42.8.30
TX 1 TSSI: 23.3428 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: 22.8387 dBm
TX 4 TSSI: -inf dBm
10.42.8.24
TX 1 TSSI: -8.8506 dBm
TX 2 TSSI: -inf dBm
TX 3 TSSI: -10.0684 dBm
TX 4 TSSI: -inf dBm
Any thoughts on how to write the loop for this ?
Thanks..
https://redd.it/1fmsftd
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Convert all directories in every command to absolute ones in the bash history
Currently I use
$ cd folder <Ctrl+R>
should allow me to select
To fix this, I modified the
cd() {
if [ -d "$1" ]; then
local dir=$(realpath "$1")
builtin cd "$dir" && history -s "cd $dir"
else
builtin cd "$1"
fi
}
This works, but I want it to work for
https://redd.it/1fmy6n8
@r_bash
Currently I use
fzf with a custom keybinding Ctrl+R to search commands in my bash history. For example:$ cd folder <Ctrl+R>
should allow me to select
cd ./long/path/to/folder. This wonderful way helps me quickly navigate to a directorie or even a file, which is very close to what zoxide does. The only drawback is that ./long/path/to/folder must be an absolute path. To fix this, I modified the
cd command:cd() {
if [ -d "$1" ]; then
local dir=$(realpath "$1")
builtin cd "$dir" && history -s "cd $dir"
else
builtin cd "$1"
fi
}
This works, but I want it to work for
vim and other commands that use directories too. Is there a better way to do this?https://redd.it/1fmy6n8
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Command into remote system works from CLI but not from Bash noscript ?
Hi,
I'm running the below command from my system and it works.
root@bai-ran-cluster-master0# ssh -q bai-ran-cluster-worker1 ssh -q 10.42.8.11 '/tmp/SWWW/a.sh' >> prechecks.log
root@bai-ran-cluster-master0# cat prechecks.log
HELLO
HELLO
HELLO
This works fine, but when I add this command into a Bash file and run it from my system, it does not work.
Code in Bash noscript
worker="bai-ran-cluster-worker1"
ipaddr=10.42.8.11
ssh -q $worker ssh -q $rruip '/tmp/SWWW/a.sh' | tee -a prechecks.log
cat prechecks.log
No error, but nothing happens.
The remote OS is Yocto, and the shell is /bin/sh
I tried the below but its not working, anything else I can check ?
ssh -q $worker ssh -q $rruip 'sh /tmp/SWWW/a.sh' | tee -a prechecks.log
ssh -q $worker ssh -q $rruip '/bin/sh /tmp/SWWW/a.sh' | tee -a prechecks.log
Below is the Shell information from the OS
root@benetelru:~# echo $0
-sh
root@benetelru:~# echo $SHELL
/bin/sh
root@system:~# cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
https://redd.it/1fn1eo5
@r_bash
Hi,
I'm running the below command from my system and it works.
root@bai-ran-cluster-master0# ssh -q bai-ran-cluster-worker1 ssh -q 10.42.8.11 '/tmp/SWWW/a.sh' >> prechecks.log
root@bai-ran-cluster-master0# cat prechecks.log
HELLO
HELLO
HELLO
This works fine, but when I add this command into a Bash file and run it from my system, it does not work.
Code in Bash noscript
worker="bai-ran-cluster-worker1"
ipaddr=10.42.8.11
ssh -q $worker ssh -q $rruip '/tmp/SWWW/a.sh' | tee -a prechecks.log
cat prechecks.log
No error, but nothing happens.
The remote OS is Yocto, and the shell is /bin/sh
I tried the below but its not working, anything else I can check ?
ssh -q $worker ssh -q $rruip 'sh /tmp/SWWW/a.sh' | tee -a prechecks.log
ssh -q $worker ssh -q $rruip '/bin/sh /tmp/SWWW/a.sh' | tee -a prechecks.log
Below is the Shell information from the OS
root@benetelru:~# echo $0
-sh
root@benetelru:~# echo $SHELL
/bin/sh
root@system:~# cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
https://redd.it/1fn1eo5
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Anyway to Tail CLI Terminal output ?
Hi,
I have the below noscript which runs a loop and display on the output.
What I want to do is just see the last 5 lines on the terminal, how can I do this ?
I know about tail but have not found an example where tail is used for Terminal output..
for i in $(seq 1 10);
do
echo $i
sleep 1
done
https://redd.it/1fngur2
@r_bash
Hi,
I have the below noscript which runs a loop and display on the output.
What I want to do is just see the last 5 lines on the terminal, how can I do this ?
I know about tail but have not found an example where tail is used for Terminal output..
for i in $(seq 1 10);
do
echo $i
sleep 1
done
https://redd.it/1fngur2
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
If condition to compare time, wrong result ?
Hi,
I have the below noscript which is to check which system uptime is greater (here greater refers to longer or more elapsed).
rruts=$(ssh -q bai-ran-cluster-worker1 ssh -q 10.42.8.11 'uptime -s')
rrepoch=$(date --date "$rruts" +"%s")
sysuts=$(uptime -s)
sysepoch=$(date --date "$sysuts" +"%s")
epochrru=$rrepoch
echo "RRU $(date -d "@${epochrru}" "+%Y %m %d %H %M %S")"
epochsys=$sysepoch
echo "SYS DATE $(date -d "@${epochsys}" "+%Y %m %d %H %M %S")"
currentdate=$(date +%s)
echo "CURRENT DATE $(date -d "@${currentdate}" "+%Y %m %d %H %M %S")"
rrudiff=$((currentdate - epochrru))
sysdiff=$((currentdate - epochsys))
echo "RRU in minutes: $(($rrudiff / 60))"
echo "SYS in minutes: $(($sysdiff / 60))"
if "$rrudiff" > "$sysdiff"
then
echo "RRU is Great"
else
echo "SYS is Great"
fi
The outcome of the noscript is
RRU 2024 09 20 09 32 16
SYS DATE 2024 02 14 11 45 38
CURRENT DATE 2024 09 23 14 11 10
RRU in minutes: 4598 <--- THIS IS CORRECT
SYS in minutes: 319825 <--- THIS IS CORRECT
RRU is Great <--- THIS IS WRONG
As in the result :
RRU has been up since 20 Sep 2024
SYS has been up since 14 eb 2024
So how is RRU Great, while its minutes are less.
Or what is wrong in the code ?
Thanks
https://redd.it/1fnljy5
@r_bash
Hi,
I have the below noscript which is to check which system uptime is greater (here greater refers to longer or more elapsed).
rruts=$(ssh -q bai-ran-cluster-worker1 ssh -q 10.42.8.11 'uptime -s')
rrepoch=$(date --date "$rruts" +"%s")
sysuts=$(uptime -s)
sysepoch=$(date --date "$sysuts" +"%s")
epochrru=$rrepoch
echo "RRU $(date -d "@${epochrru}" "+%Y %m %d %H %M %S")"
epochsys=$sysepoch
echo "SYS DATE $(date -d "@${epochsys}" "+%Y %m %d %H %M %S")"
currentdate=$(date +%s)
echo "CURRENT DATE $(date -d "@${currentdate}" "+%Y %m %d %H %M %S")"
rrudiff=$((currentdate - epochrru))
sysdiff=$((currentdate - epochsys))
echo "RRU in minutes: $(($rrudiff / 60))"
echo "SYS in minutes: $(($sysdiff / 60))"
if "$rrudiff" > "$sysdiff"
then
echo "RRU is Great"
else
echo "SYS is Great"
fi
The outcome of the noscript is
RRU 2024 09 20 09 32 16
SYS DATE 2024 02 14 11 45 38
CURRENT DATE 2024 09 23 14 11 10
RRU in minutes: 4598 <--- THIS IS CORRECT
SYS in minutes: 319825 <--- THIS IS CORRECT
RRU is Great <--- THIS IS WRONG
As in the result :
RRU has been up since 20 Sep 2024
SYS has been up since 14 eb 2024
So how is RRU Great, while its minutes are less.
Or what is wrong in the code ?
Thanks
https://redd.it/1fnljy5
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Use variable inside braces {}
for NUM in {00..10}; do echo $NUM; done
outputs this, as expected
00
01
02
...
10
However MAX=10; for NUM in {00..$MAX}; do echo $NUM; done
produces this
{00..10}
What am I missing here? It seems to expand the variable correctly but the loop isn't fucntioning?
https://redd.it/1fnro7f
@r_bash
for NUM in {00..10}; do echo $NUM; done
outputs this, as expected
00
01
02
...
10
However MAX=10; for NUM in {00..$MAX}; do echo $NUM; done
produces this
{00..10}
What am I missing here? It seems to expand the variable correctly but the loop isn't fucntioning?
https://redd.it/1fnro7f
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
A noscript that will delete all subdirectories except those which contain pdf or mp3 files
Let's say I have a directory "$my_dir". Inside this directory there are various subdirectories, each containing files. I'd like to have a noscript which, when executed, automatically removes all subdirectories which do not contain pdf or mp3 files. On the other hand, the subdirectories which do contain some mp3 or pdf files should be left untouched. Is this possible?
https://redd.it/1fnxi3i
@r_bash
Let's say I have a directory "$my_dir". Inside this directory there are various subdirectories, each containing files. I'd like to have a noscript which, when executed, automatically removes all subdirectories which do not contain pdf or mp3 files. On the other hand, the subdirectories which do contain some mp3 or pdf files should be left untouched. Is this possible?
https://redd.it/1fnxi3i
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Is there an "official" Usage syntax syntax?
With getopt or getopts I see options treated as optional. That makes sense to me, but making people remember more than 1 positional parameter seems likely to trip up some users. So, I want to have a flag associated with parameters.
Example a with optional options:
Usage: $0 -x <directory> -o <directory> <input>
Is this the same, with required options:
Usage: $0 -x <directory> -o <directory> <input>
Any other suggestions? Is that how I should indicate a directory as an option value?
https://redd.it/1fo7eom
@r_bash
With getopt or getopts I see options treated as optional. That makes sense to me, but making people remember more than 1 positional parameter seems likely to trip up some users. So, I want to have a flag associated with parameters.
Example a with optional options:
Usage: $0 -x <directory> -o <directory> <input>
Is this the same, with required options:
Usage: $0 -x <directory> -o <directory> <input>
Any other suggestions? Is that how I should indicate a directory as an option value?
https://redd.it/1fo7eom
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
RapidForge: Create Web Apps and Automate Tasks with Bash
I've been working on a project called RapidForge that makes it easier to create custom Bash noscripts for automating various tasks. With RapidForge, you can quickly spin up endpoints, create pages (with dnd editor) and schedule periodic tasks using Bash noscripting. It’s a single binary with no external dependencies so deployment and configuration are a breeze.
RapidForge injects helpful environment variables directly into your Bash noscripts, making things like handling HTTP request data super simple. For example, when writing noscripts to handle HTTP endpoints, the request context is parsed and passed as environment variables, so you can focus on the logic without worrying about the heavy lifting.
Would love to hear your thoughts or get any suggestions on how to improve it
https://redd.it/1fpc1po
@r_bash
I've been working on a project called RapidForge that makes it easier to create custom Bash noscripts for automating various tasks. With RapidForge, you can quickly spin up endpoints, create pages (with dnd editor) and schedule periodic tasks using Bash noscripting. It’s a single binary with no external dependencies so deployment and configuration are a breeze.
RapidForge injects helpful environment variables directly into your Bash noscripts, making things like handling HTTP request data super simple. For example, when writing noscripts to handle HTTP endpoints, the request context is parsed and passed as environment variables, so you can focus on the logic without worrying about the heavy lifting.
Would love to hear your thoughts or get any suggestions on how to improve it
https://redd.it/1fpc1po
@r_bash
rapidforge.io
RapidForge | Low-Code Platform for Apps, Automation & Web Development
Build internal tools, automate workflows and create web pages with RapidForge. Ideal for developers, DevOps and SOAR teams seeking a low code solution.
Styling preference for quoting stuff in comments
In shell noscripts, I have lots of comments and quoting is used for emphasis. The thing that is being quoted is e.g. a command, a function name, a word, or example string. I've been using backticks, double, single quote chars all over the place and looking to make it consistent and not completely arbitrary. I typically use double quotes for "English words". backticks for commands (and maybe for functions names), single quotes for strings.
E.g. for the following, should
# "funcA" does this, similar to
Is this a decent styling preference or there some sort of coding style code? Would it make sense to follow this scheme in other programming languages? What do you do differently?
Maybe some people prefer the simplicity of e.g. using "" everywhere but that is a little more ambiguous when it comes to e.g. keywords or basic names of functions/variables.
Also, I used to use lower case for comments because it's less effort, but when it's more than a sentence, the first char of the second sentence must be capitalized. I switched to capitalizing at the beginning of every comment even if it's just one sentence and I kind of regret it--I think I still prefer
Inb4 the comments saying it literally doesn't matter, who cares, etc. 🙂
https://redd.it/1fpglmg
@r_bash
In shell noscripts, I have lots of comments and quoting is used for emphasis. The thing that is being quoted is e.g. a command, a function name, a word, or example string. I've been using backticks, double, single quote chars all over the place and looking to make it consistent and not completely arbitrary. I typically use double quotes for "English words". backticks for commands (and maybe for functions names), single quotes for strings.
E.g. for the following, should
funcA and file2 have the same quotes? # "funcA" does this, similar to
cp file file2. 'file2' is a fileIs this a decent styling preference or there some sort of coding style code? Would it make sense to follow this scheme in other programming languages? What do you do differently?
Maybe some people prefer the simplicity of e.g. using "" everywhere but that is a little more ambiguous when it comes to e.g. keywords or basic names of functions/variables.
Also, I used to use lower case for comments because it's less effort, but when it's more than a sentence, the first char of the second sentence must be capitalized. I switched to capitalizing at the beginning of every comment even if it's just one sentence and I kind of regret it--I think I still prefer
# this is comment. Deal with it because I try to stick with short comments anyway. I never end a comment with punctuation--too formal.Inb4 the comments saying it literally doesn't matter, who cares, etc. 🙂
https://redd.it/1fpglmg
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Any simple way to remove ALL escape sequences (except \r\n) from a screen log?
I am logging the SSH connection within a screen session. I want to parse the log, but all methods in the internet only get me so far. I get garbage letters written to the next line like:
;6R;6R;2R;2R;4R;4R24R24
There is not even any capital R in the log, neither a 6. And they are not just visually glitched to the next line, pressing enter will try to execute this crap.
This garbage comes from loggin in to a MikroTik device via SSH. Unfortunately I need to parse this code in a predictable way. Using cat on the logfile without filtering prints the colors correctly, but this even prints this garbage to the new line. I have absolutely 0 plan, where this comes from. Any idea, how one could get a screen log, that is clean, or a way to parse it in bash in a clean way? I would prefer something lightweight, that is available in typical linux distros, if possible.
https://redd.it/1fpygiu
@r_bash
I am logging the SSH connection within a screen session. I want to parse the log, but all methods in the internet only get me so far. I get garbage letters written to the next line like:
;6R;6R;2R;2R;4R;4R24R24
There is not even any capital R in the log, neither a 6. And they are not just visually glitched to the next line, pressing enter will try to execute this crap.
This garbage comes from loggin in to a MikroTik device via SSH. Unfortunately I need to parse this code in a predictable way. Using cat on the logfile without filtering prints the colors correctly, but this even prints this garbage to the new line. I have absolutely 0 plan, where this comes from. Any idea, how one could get a screen log, that is clean, or a way to parse it in bash in a clean way? I would prefer something lightweight, that is available in typical linux distros, if possible.
https://redd.it/1fpygiu
@r_bash
Reddit
From the bash community on Reddit
Explore this post and more from the bash community
Aligning Two Columns for Files and Directories in Bash from Bottom-Up
[What I am trying to do](https://imgur.com/a/UjzUqXe)
I am working on a bash navigation noscript that displays files and directories side by side in two columns. However, I am stuck on aligning the output properly.
> I am hoping when its finished I can post it here and get some feedback. The noscript has some nice abilities which I have wanted for CLI interaction.
### The Problem:
When you look at the screenshot, the outputs don't align properly at the bottom. I need the files on the left and directories on the right, and both should start from the bottom and grow upwards.
### Why it’s Important:
The main issue I want to solve is that when there are many files, you have to scroll up to see the directories, which defeats the ease of navigation. I want the directories and files to always stay visible, both aligned properly from the bottom, like in my picture.
The main display:
display_items_fileNav() {
# Get terminal height using tput
term_height=$(tput lines)
# Get the outputs of the existing functions
file_output=$(display_files_only) # Get the file output
dir_output=$(display_dir_only) # Get the directory output
# Determine how many lines are used for each output
file_lines=$(echo "$file_output" | wc -l)
dir_lines=$(echo "$dir_output" | wc -l)
# Calculate the maximum of the file and directory lines to ensure both align from the bottom
max_lines=$(( file_lines > dir_lines ? file_lines : dir_lines ))
# Set the start position for both columns so they align at the bottom
start_position=$((term_height - max_lines - 3)) # Reserve 3 lines for the prompt and buffer
# Set the column width for consistent spacing; adjust based on the longest file name
file_column_width=40 # Adjust this as needed
dir_column_width=30 # Adjust this as needed
# Pad the top so the output aligns to the bottom of the terminal
tput cup $start_position 0
# Combine the outputs, aligning the columns side by side
paste <(echo "$file_output" | tail -n "$max_lines") <(echo "$dir_output" | tail -n "$max_lines") | while IFS=$'\t' read -r file_line dir_line; do
printf "%-${file_column_width}s %s\n" "$file_line" "$dir_line"
done
# Print category noscripts (Files and Directories) at the top of each column
echo -e "${NEON_GREEN}Files:${NC}$(printf '%*s' $((file_column_width - 5)) '')${NEON_RED}Directories:${NC}"
# Move cursor to the prompt position and show the prompt
tput cup $((term_height - 1)) 0
}
**The output functions** (I did this because I could not get the reverse order to properly display).
display_dir_only() {
# Get terminal height using tput
term_height=$(tput lines)
# Get directories and files
dirs=($(ls -d */ 2>/dev/null)) # List directories
files=($(ls -p | grep -v /)) # List files (excluding directories)
# Reverse the order of directories and files
dirs=($(printf "%s\n" "${dirs[@]}" | tac)) # Reverse the directories array
files=($(printf "%s\n" "${files[@]}" | tac)) # Reverse the files array
dir_count=${#dirs[@]} # Count directories
file_count=${#files[@]} # Count files
total_count=$((dir_count + file_count)) # Total number of items (directories + files)
# Calculate how many lines we need to "pad" at the top
padding=$((term_height - total_count - 22)) # 6 includes prompt space and a clean buffer
# Pad with empty lines to push content closer to the bottom
for ((p = 0; p < padding; p++)); do
echo ""
done
# Skip file display but count them for numbering
reverse_index=$total_count # Start reverse_index from the total count (dirs + files)
# First, we skip file output but count files
reverse_index=$((reverse_index - file_count))
# Then, display directories in reverse order
[What I am trying to do](https://imgur.com/a/UjzUqXe)
I am working on a bash navigation noscript that displays files and directories side by side in two columns. However, I am stuck on aligning the output properly.
> I am hoping when its finished I can post it here and get some feedback. The noscript has some nice abilities which I have wanted for CLI interaction.
### The Problem:
When you look at the screenshot, the outputs don't align properly at the bottom. I need the files on the left and directories on the right, and both should start from the bottom and grow upwards.
### Why it’s Important:
The main issue I want to solve is that when there are many files, you have to scroll up to see the directories, which defeats the ease of navigation. I want the directories and files to always stay visible, both aligned properly from the bottom, like in my picture.
The main display:
display_items_fileNav() {
# Get terminal height using tput
term_height=$(tput lines)
# Get the outputs of the existing functions
file_output=$(display_files_only) # Get the file output
dir_output=$(display_dir_only) # Get the directory output
# Determine how many lines are used for each output
file_lines=$(echo "$file_output" | wc -l)
dir_lines=$(echo "$dir_output" | wc -l)
# Calculate the maximum of the file and directory lines to ensure both align from the bottom
max_lines=$(( file_lines > dir_lines ? file_lines : dir_lines ))
# Set the start position for both columns so they align at the bottom
start_position=$((term_height - max_lines - 3)) # Reserve 3 lines for the prompt and buffer
# Set the column width for consistent spacing; adjust based on the longest file name
file_column_width=40 # Adjust this as needed
dir_column_width=30 # Adjust this as needed
# Pad the top so the output aligns to the bottom of the terminal
tput cup $start_position 0
# Combine the outputs, aligning the columns side by side
paste <(echo "$file_output" | tail -n "$max_lines") <(echo "$dir_output" | tail -n "$max_lines") | while IFS=$'\t' read -r file_line dir_line; do
printf "%-${file_column_width}s %s\n" "$file_line" "$dir_line"
done
# Print category noscripts (Files and Directories) at the top of each column
echo -e "${NEON_GREEN}Files:${NC}$(printf '%*s' $((file_column_width - 5)) '')${NEON_RED}Directories:${NC}"
# Move cursor to the prompt position and show the prompt
tput cup $((term_height - 1)) 0
}
**The output functions** (I did this because I could not get the reverse order to properly display).
display_dir_only() {
# Get terminal height using tput
term_height=$(tput lines)
# Get directories and files
dirs=($(ls -d */ 2>/dev/null)) # List directories
files=($(ls -p | grep -v /)) # List files (excluding directories)
# Reverse the order of directories and files
dirs=($(printf "%s\n" "${dirs[@]}" | tac)) # Reverse the directories array
files=($(printf "%s\n" "${files[@]}" | tac)) # Reverse the files array
dir_count=${#dirs[@]} # Count directories
file_count=${#files[@]} # Count files
total_count=$((dir_count + file_count)) # Total number of items (directories + files)
# Calculate how many lines we need to "pad" at the top
padding=$((term_height - total_count - 22)) # 6 includes prompt space and a clean buffer
# Pad with empty lines to push content closer to the bottom
for ((p = 0; p < padding; p++)); do
echo ""
done
# Skip file display but count them for numbering
reverse_index=$total_count # Start reverse_index from the total count (dirs + files)
# First, we skip file output but count files
reverse_index=$((reverse_index - file_count))
# Then, display directories in reverse order
Imgur
Discover the magic of the internet at Imgur, a community powered entertainment destination. Lift your spirits with funny jokes, trending memes, entertaining gifs, inspiring stories, viral videos, and so much more from users.
with correct numbering
for ((i = 0; i < dir_count; i++)); do
if [ $reverse_index -eq $current_selection ]; then
printf "${NEON_RED}%2d. %s${NC}/ <---" "$reverse_index" "${dirs[i]}"
else
printf "${NEON_RED}%2d. %s${NC}/" "$reverse_index" "${dirs[i]}"
fi
reverse_index=$((reverse_index - 1))
echo ""
done echo ""}
display_files_only() {
# Get terminal height using tput
term_height=$(tput lines)
# Get directories and files
dirs=($(ls -d */ 2>/dev/null)) # List directories
files=($(ls -p | grep -v /)) # List files (excluding directories)
# Reverse the order of directories and files
dirs=($(printf "%s\n" "${dirs[@]}" | tac)) # Reverse the directories array
files=($(printf "%s\n" "${files[@]}" | tac)) # Reverse the files array
dir_count=${#dirs[@]} # Count directories
file_count=${#files[@]} # Count files
total_count=$((dir_count + file_count)) # Total number of items (directories + files)
# Calculate how many lines we need to "pad" at the top
padding=$((term_height - total_count - 24)) # 6 includes prompt space and a clean buffer
# Pad with empty lines to push content closer to the bottom
for ((p = 0; p < padding; p++)); do
echo ""
done
# Skip directory display but count them for numbering
reverse_index=$total_count # Start reverse_index from the total count (dirs + files)
# First, skip directory display but count directories
# The reverse_index skips by the dir_count, so it correctly places files after.
reverse_index=$((reverse_index))
# Then, display files with correct numbering (including counted but hidden directories)
for ((i = 0; i < file_count; i++)); do
if [ $reverse_index -eq $current_selection ]; then
printf "${NEON_GREEN}%2d. %-*s${NC} <---" "$reverse_index" $COLWIDTH "${files[i]}"
else
printf "${NEON_GREEN}%2d. %-*s${NC}" "$reverse_index" $COLWIDTH "${files[i]}"
fi
reverse_index=$((reverse_index - 1)) # Decrease the reverse_index each time
echo ""
done
# Add an empty line for clean separation between the listing and the prompt
echo ""
}
### Any ideas or suggestions on how to fix this alignment issue?
https://redd.it/1fq69nt
@r_bash
for ((i = 0; i < dir_count; i++)); do
if [ $reverse_index -eq $current_selection ]; then
printf "${NEON_RED}%2d. %s${NC}/ <---" "$reverse_index" "${dirs[i]}"
else
printf "${NEON_RED}%2d. %s${NC}/" "$reverse_index" "${dirs[i]}"
fi
reverse_index=$((reverse_index - 1))
echo ""
done echo ""}
display_files_only() {
# Get terminal height using tput
term_height=$(tput lines)
# Get directories and files
dirs=($(ls -d */ 2>/dev/null)) # List directories
files=($(ls -p | grep -v /)) # List files (excluding directories)
# Reverse the order of directories and files
dirs=($(printf "%s\n" "${dirs[@]}" | tac)) # Reverse the directories array
files=($(printf "%s\n" "${files[@]}" | tac)) # Reverse the files array
dir_count=${#dirs[@]} # Count directories
file_count=${#files[@]} # Count files
total_count=$((dir_count + file_count)) # Total number of items (directories + files)
# Calculate how many lines we need to "pad" at the top
padding=$((term_height - total_count - 24)) # 6 includes prompt space and a clean buffer
# Pad with empty lines to push content closer to the bottom
for ((p = 0; p < padding; p++)); do
echo ""
done
# Skip directory display but count them for numbering
reverse_index=$total_count # Start reverse_index from the total count (dirs + files)
# First, skip directory display but count directories
# The reverse_index skips by the dir_count, so it correctly places files after.
reverse_index=$((reverse_index))
# Then, display files with correct numbering (including counted but hidden directories)
for ((i = 0; i < file_count; i++)); do
if [ $reverse_index -eq $current_selection ]; then
printf "${NEON_GREEN}%2d. %-*s${NC} <---" "$reverse_index" $COLWIDTH "${files[i]}"
else
printf "${NEON_GREEN}%2d. %-*s${NC}" "$reverse_index" $COLWIDTH "${files[i]}"
fi
reverse_index=$((reverse_index - 1)) # Decrease the reverse_index each time
echo ""
done
# Add an empty line for clean separation between the listing and the prompt
echo ""
}
### Any ideas or suggestions on how to fix this alignment issue?
https://redd.it/1fq69nt
@r_bash
Reddit
From the bash community on Reddit: Aligning Two Columns for Files and Directories in Bash from Bottom-Up
Explore this post and more from the bash community