r_bash – Telegram
Why can't OpenVPN take pass input in a bash cript?

So I have would like to have a noscript like this:

#!/usr/bin/env bash

sudo openvpn --config path/to/my/conf --auth-user-pass "$(pass show openvpn/passwd)"


Doesn't work though:


$ bash my-openvpn-noscript.sh
2023-09-22 13:54:41 Cannot pre-load keyfile (the-key-file-here)
2023-09-22 13:54:41 Exiting due to fatal error

In my mind it should work since the output is the same as a file would be:


$ cat filewithpasswd.txt
username
the-passwd

$ pass show openvpn/passwd
username
the-passwd

It only works if I feed the filewithpasswd.txt instead of with pass-command. Somehow a file and output displayed in pass is different somehow? How can pass be used with openvpn in a bash noscript?

https://redd.it/16p7826
@r_bash
optParse: an options-parsing tool that makes parsing options easy, efficient, and fast to implement

The [CODE](https://github.com/jkool702/forkrun/blob/main/optParse.bash) and a [USAGE EXAMPLE + SPEEDTEST](https://github.com/jkool702/forkrun/blob/main/optParse_test.bash) is hosted on github.

This is a follow-up/continuation to [this](https://www.reddit.com/r/bash/comments/16lpgps/rparse_an_easytouse_shell_noscriptfunction_option/) post about [rparse](https://github.com/jkool702/forkrun/blob/main/rparse.bash), which does regex-based option parsing.

`optParse` is a tool that takes a simple "option parsing definition table" that you define and expands it into a full option parsing function that uses a robust and very efficient "loop over options and run each through a `case` statement" approach. Options are defined using `case` statement syntax (either standard or ext-glob-based).

The "option parsing definition table" is a table containing a lines of the following syntax (1 line per option you want to parse):

<CASE_MATCHES> :: <VAR_TO_ASSIGN> <CMDS_TO_RUN>

NOTES:

* For options without arguments, set `<VAR_TO_ASSIGN>` to `-`
* For options with arguments, they may be passed via with a (space), with an `=`, or with nothing seperating the option and the argument. i.e., `-o $arg` or `--opt $arg` or '-o=$arg' or `--opt=$arg` or `-o$arg` or `--opt$arg` all work.
* Options must begin with a `-` or `+`, but are otherwise matched without restriction.
* when passing options to the function/noscript you are developing, options must be given before any non-option arguments, and passing `--` will stop further inputs from being treated as options.
* Any non-option arguments are saved in a bash array `inFun`

***

EXAMPLE:

source <(genOptParse<<'EOF'
-a --apple :: - flag_a=true
-b --bananna :: var_b
-c --coconut :: var_c flag_c=true
EOF
)
optParse "$@"

The above will generate the following code, which is generates and sources the following optParse function which will parse options for you (run `optParse "$@"`). Note that instead of wrapping things in a `source <(...)` statement, it is more efficient to generate the `optParse` function and copy/paste it directly into the code. However, if the code is in development and options are changing frequently using `source <(...)` is easier to maintain.

declare -a inFun
inFun=()
shopt -s extglob
unset optParse

optParse() {

local continueFlag

continueFlag=true
while ${continueFlag} && (( $# > 0 )) && [[ "$1" == [\-\+]* ]]; do
case "${1}" in
-a|--apple)
shift 1
flag_a=true
;;
-b|--bananna)
var_b="${2}"
shift 2

;;
-b?(=)+([[:graph:]])|--bananna?(=)+([[:graph:]]))
var_b="${1##@(-b?(=)|--bananna?(=))}"
shift 1

;;
-c|--coconut)
var_c="${2}"
shift 2
flag_c=true
;;
-c?(=)+([[:graph:]])|--coconut?(=)+([[:graph:]]))
var_c="${1##@(-c?(=)|--coconut?(=))}"
shift 1
flag_c=true
;;
'--')
shift 1
continueFlag=false
break
;;
@([\-\+])*)
printf '\nWARNING: FLAG "%s" NOT RECOGNIZED. IGNORING.\n\n' "$1"
shift 1
;;
*)
continueFlag=false
break
;;
esac
[[ $# == 0 ]] && continueFlag=false
done
inFun=("${@}")
}

***

There is additionally an optional pre-parser function that will find any option definitions that

1. have no argument, and
2. only serve so set 1+ "flag" variables to
`true`

and will automatically generate+add an analogous `+option` to the option parsing definition table that sets these variable(s) to false instead. in the above example, had we used

source <({ genOptParse_pre | genOptParse; }<<'EOF'

The pre-parser would have added

+a ++apple :: - flag_a=false

to the option parsing definition table; which in turn would have added

+a|++apple)
shift 1
flag_a=false
;;

as an additional `case` match in the `optParse` function.

Comments? Suggestions? Bugs? Let me know. Hope some of you find this useful.

https://redd.it/16q89py
@r_bash
Yo Dawg! I heard you like arrays, so we put some arrays in your arrays...

No but seriously...


In JSON you can nest an array inside an element of an array.


Is this even possible in BASH?


Let's say I have a 2D array.


My2DArray[0,0\] - My2DArray[8,8\]


Can I place an array inside one location of that matrix? Say: My2DArray[4,3\]=(5 7 8 9)?


I am asking for a friend, but before I try it, and the fabric of the universe implodes on itself and reality ceases to follow the laws of Quantum Dynamics.


PS: I am a coder with high levels of anxiety. So I have no friends. Therefore I am asking for myself.

https://redd.it/16qcwf2
@r_bash
POLL: You're on a strangers computer, typing into terminal. You don't know what terminal/settings/OS but it's probably defaults. You see a b that should be a p. You click your mouse on the b and nothing happens. What's your next moves? (Please don't say "backspace x 19")
https://redd.it/16qgrp8
@r_bash
New operator idea: inline loop operator

virsh start {{foo,bar,baz}}

expands to:
for x in foo bar baz; do
virsh start $x;
done


I often decide I want to run a command with multiple inputs after I've already started typing it.. So yeah I can go back and add the for loop wrapper, but the more concise and immediate "loop operator" would be very convenient.

Also some nested loops are even more fun/concise:
$ echo {{foo,bar}} {{baz,boz}}
foo baz
foo boz
bar baz
bar boz

instead of
$ for x in foo bar; do
> for y in baz boz; do
> echo $x $y
> done
> done
foo baz
foo boz
bar baz
bar boz


https://redd.it/16qrjij
@r_bash
Download Firewall Denied IP List using bash?

Hello Guys,

I want to save my firewall IP Denied list from my firewall to a local text file. I figured how to login and save the output of the first screen but got stuck.

I am hoping someone can help me I want to use a .sh noscript file to login to my firewall send several commands such as cli then show security match-policies denied. Which will result in a list that would normally require me to hit the Enter key over 100 times then save the results of the IPs that were denied access to a text file on my local server

https://redd.it/16r8zx8
@r_bash
Introduction to bash

Hello Bash community, I come from a hellish landscape that is Windows 11 + Batch. I am going to be taking a Unix/Linux class at my CC as part of my IT Sysadmin degree, and I am curious to know if there are any good YouTube playlists or free courses that offer a "ground zero" introduction to bash and bash noscripting? When I see bash noscripts, they look quite unfamiliar, and I am sure that there are also oddities in the language as there are in CMD. I have never found myself able to understand regexes much, though I hear this is commonly used in Bash.

https://redd.it/16ri1oi
@r_bash
Help with formatting multi line commands

Can someone kindly confirm if this is formatted correctly. I did hit the Format option on VSCode after installing shell-format extension but I am not sure

psql \
--tuples-only \
--command="SELECT 1 FROM pg_user WHERE usename = '${TARGET_POSTGRES_USERNAME}'" \
"""
dbname=${TARGET_POSTGRES_ROOT_DATABASE_NAME}
host=${TARGET_POSTGRES_HOST}
password=${TARGET_POSTGRES_PASSWORD}
port=${TARGET_POSTGRES_PORT}
sslmode=verify-full
sslrootcert=${POSTGRES_SSL_ROOT_CERT_PATH}
user=${TARGET_POSTGRES_ROOT_USERNAME}
""" | \
grep -q 1 ||
psql \
--command="CREATE USER ${TARGET_POSTGRES_USERNAME} WITH LOGIN NOSUPERUSER INHERIT CREATEDB NOCREATEROLE NOREPLICATION PASSWORD '${TARGET_POSTGRES_PASSWORD}'" \
"""
dbname=${TARGET_POSTGRES_ROOT_DATABASE_NAME}
host=${TARGET_POSTGRES_HOST}
password=${TARGET_POSTGRES_PASSWORD}
port=${TARGET_POSTGRES_PORT}
sslmode=verify-full
sslrootcert=${POSTGRES_SSL_ROOT_CERT_PATH}
user=${TARGET_POSTGRES_ROOT_USERNAME}
"""

https://redd.it/16rjrrz
@r_bash
Linux terminal practice similar to w3 schools

Linux terminal practice similiar to w3 schools style

Hopefully this is the best subreddit for some good ideas/discussions.

I have a number of first line support members in my team where this is their first IT role and they come from a more customer/adminiatration style background.

Our product runs off Linux but the nature of their role means they wont need to interact with it themselves.

Due to the nature of the company i'm not able to provide them access to any Linux servers or even VMs to play with.

I'm looking for something similar to w3 schools where they can become familiar with basic Linux terminal commands e.g. ls, pwd,cd but within a web browser form.

We have a fair bit of down time on the job and so I want to pique their curiosity, get them in the habbit of self learning and also give them some exposure of what the 2nd line team does...Any ideas?

https://redd.it/16rlxl7
@r_bash
Help with a noscript

Hi all, I've decided to write a noscript for a lengthy process at work. I have a main box which I store driver packs for multiple devices, I'd like to copy the content of this directory into other servers.

My plan is to add the new driver files when we get a new model, then run this noscript to copy to the other servers. I'd also like for this to work for when I update existing driver packs. I do not want to copy content that already exists. How can I do this with the following noscript I have started? Hope this makes sense.

&#x200B;

#!/bin/bash
#source directory
sourcedirectory="/images/drivers"

#remote username
remote
user="username"

#array of remote server IPs
remoteservers=("10.xx.xx.xxx" "10.xx.xx.xxx")

#Destination directory on remote servers
destination
directory="/images/drivers"

#specify the user and group ownership for the copied directories
ownership="name:name

#Loop through each remote server and copy the contents
for server in "${remoteservers[@]}"; do
rsync -avs --ignore-existing --chown="$ownership" "$source
directory/" "$remoteuser@$server:$destinationdirectory/"
done

&#x200B;

&#x200B;

https://redd.it/16rw9kl
@r_bash
Video Stripe Preview Generator

# Hello Everyone,

I just finished making a noscript to generate a striped preview image of a video (mp4, mkv, etc.) or image-sequence (gif, etc.) (with the help of FFmpeg), I'll definitely make it better going forward. For now, I'm just trying to debug and hunt down exceptions states and anomalies.

So here's the **REPO** for my Script, have at it and let me know how it performed, and if you find any odd behavior do let me know so that I can patch it up. And I'm also up for a good suggestion.(I know the Script looks bad and a bit UnOptimized and has a lot of sanity checks, but right now my priority is to find all exception/error states and handle it)

&#x200B;

# Some Preview:

Command : video-stripe-preview -vf "WING IT - Blender Open Movie.mp4"

&#x200B;

Default parameters

Command : video-stripe-preview -r 2 -c 4 -l 960 -vf "WING IT - Blender Open Movie.mp4"

&#x200B;

Row = 2 | Column = 4 | Width = 960

Command : video-stripe-preview -r 5 -c 2 -vf "WING IT - Blender Open Movie.mp4"

&#x200B;

Row = 5 | Column = 2

&#x200B;

# Credits :

**WING IT !!** — An Open Film from *blender Studio* was used to generate previews.

# Note:

I'm kinda new to the whole Linux, git, CLI, FFmpeg, etc. so feel free to be informal with the discussion, we'll probably need to have many back and forth before I come to a conclusion.

https://redd.it/16rz17d
@r_bash
Need help with a noscript - Finding out when my car is in the driveway

My car has a Dashcam that will let me download files. There is already a way to synchronize my BlackVue dashcam with a local directory over a LAN. What I want to do is place a laptop in my living room and every 5 minutes see if it can see the Wi-Fi network that my Blackvue camera creates. If it does I want it to connect to that network then call the noscript to start transferring files.

I am not very knowledgeable when it comes to noscripting.

This is what I have written so far. I would appreciate help in cleaning it up.

#!/bin/bash

DashcamAP="" # Name of the wireless network I am looking for

DashcamPA="" # Password of the wireless network I am looking for

# <<Code to drop all wireless networks>>

echo "Looking for network called " $DashcamAP

if test -e "wifiscan.lock"

then

echo "Wifi Scan done Less than 5 minutes ago"

rm -f wifiscan.lock # to delete the lock file

rm -f wifi.list # to delete the list of found networks

rm -f AmIHome # to delete the flag file if the car was home

sleep 5m

touch wifiscan.lock # To show the noscript was recently run

echo "Preparing to scan wif"

sh ./wifitest.sh

else echo "Wifi Scan not done. Scanning now"

touch wifiscan.lock

nmcli dev wifi rescan

nmcli -t -g SSID dev wifi > wifi.list

grep -i $DashcamAP wifi.list > AmIHome

if [ -s AmIHome ];

then touch IAmHome

fi

rm -f wifiscan.lock

if test -e "IAmHome"

then

echo "Network is found"

# << Code to connect to the wireless network >>

# sh ./BlackVueSyncScript -- Will call the SyncScript

else

echo "Network not found"

fi

fi

&#x200B;

&#x200B;

https://redd.it/16scc1q
@r_bash
How to filter files with glob patterns?

Lets say i have these files in dir directory.

file1.jar
file2.jar
file3suffix.jar
file4.txt
...
fileX.someotherextension

I need all `*.jar` files execpt those ended with `
suffix.jar. I've read this [https://www.gnu.org/software/bash/manual/html\_node/Pattern-Matching.html#Pattern-Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html#Pattern-Matching)

... and:

*
ls dir/.jar` gives me all jars
ls dir/!(_suffix.jar) gives me good jars but also files with other extensions

Preferably i would somehow merge these 2 together.

&#x200B;

https://redd.it/16srr4t
@r_bash
rm function does not work

I am trying to delete some text files but I am getting this error :

rm: /path/to/files/* No such file or directory

This is the actual command :

rm -r $PATHTOFILES”*”

Used * wildcard because my usecase requires to all files deleted regardless of file extension.

I am running an airflow DAG to call a shell noscript that delete all files from a local directory, then pull files from an SFTP server and place them within the same directory. Therefore it is the same airflow user creating the directory and placing the files.

Would appreciate any advice, thank you!

https://redd.it/16thf8z
@r_bash
How to run 2x readarray ... < <(...) in parallel ?

Hi folks,

readarray -d '' a < <(my_function)
readarray -d '' b < <(my_function)


Is it possible to run the above simultaneously?

my_function runs complicated find ... -print0.

Thank you.

https://redd.it/16ti9pr
@r_bash
Combined output of commands into variable

I know I can do

value=$(echo "FOO"; echo "BAR")

to get the combined output of the command group and set it to the variable. AFAIU, the commands will be run in a separate shell. Now, I was wondering whether it would be possible to achieve the same thing without starting a new shell, but I couldn't find the right syntax. The closest I got was

value=$({ echo "FOO"; echo "BAR"; })

but I suppose this is not what I wanted. This will run the command group locally in a new shell. The goal was to prevent the creation a new shell in the first place.

Any ideas?

Thanks.

https://redd.it/16tuegx
@r_bash
ndarray: tools for setting up and using N-dimensional / nested arrays in bash

A recent post here inspired me to pick up an old personal project for getting bash to work with N-dimensional/nested arrays. I got it working, so I figured id share it.

The [CODE](
https://github.com/jkool702/bashndarray/blob/main/ndarray.bash) is on github. There are 5 functions:

`nd_usage` gives a brief usage example
nd_create sets up the nameref framework and declares the arrays
`nd_set` writes data into the arrays at the end on the namerefs (the `A_0` and `A_1` arrays in the simple example above)
nd_get reads data out of the arrays. You can define lists/ranges on indices for any dimension and it will output all the data that falls into the n-dimensional slice of the array.
nd_clear unsets all the array and nameref variables

METHODOLOGY

It involves creating a framework of nameref arrays to handle all the dimensions except the last one (which is saved in the arrays themselves. The idea is to do something like

declare -n a_0='A_0'
declare -n a_1='A_1'
A=(a_0 a_1)
A_0=(1 2 3)
A_1=(4 5 6)

So to get the data at (1,2), you do `${A[1]}` which gives `a_1` which namerefs to A_1 then `${A_1[2]}` which gives the actual data. The use of the `a_1` and `a_0` are because bash doesnt directly support doing, say, `declare -n A[0]=A_0`...you have to nameref a dummy variable and then store that in an array.

USAGE EXAMPLE

this is the example that running `nd_usage` prints

# # # # # generate nameref framework.
# note: dont include the last dimension

source <(nd_create -a A 2 3 4)

# # # # # set array values
# pass data to be set on STDIN, and use function inputs to define basename + index ranges

source <(seq 1 $(( 2
3 4 5 )) | ndset A 0:1 0:2 0:3 0:4)

# # # # # extract various slices from the array

nd
get A 0 \@ \@ \@
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
26 27 28 29 30
31 32 33 34 35
36 37 38 39 40
41 42 43 44 45
46 47 48 49 50
51 52 53 54 55
56 57 58 59 60

ndget A \@ 0 \@ \@
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
61 62 63 64 65
66 67 68 69 70
71 72 73 74 75
76 77 78 79 80

nd
get A \@ \@ 0 \@
1 2 3 4 5
21 22 23 24 25
41 42 43 44 45
61 62 63 64 65
81 82 83 84 85
101 102 103 104 105

ndget A \@ \@ \@ 0
1
6
11
16
21
26
31
36
41
46
51
56
61
66
71
76
81
86
91
96
101
106
111
116

# # # # # cleanup

nd
clear A

https://redd.it/16tvadk
@r_bash