r_bash – Telegram
modifying file names

Hi, I'm trying to change the names of my torrent files, but I don't understand why line 14 when I do

`echo "${nameArr[$counter]}"`

it doesn't display the element corresponding to the array index it doesn't even print the part during the iteration :

example on the file : Ant-Man.and.the.Wasp.Quantumania.2023.1080p.MA.WEBRip.DDP5.1.Atmos.x264-CM.torrent

i get this result :

Ant-Man

WEBRip

​


#!/bin/bash

dir=($(find . -maxdepth 1 -name "*.torrent"))
for file in "${dir[@]}" ; do
IFS="." read -a nameArr <<< "$file"
echo "${nameArr[@]}"
boolContinue=true
counter=0
newName=""
arrSize=${#nameArr[@]}
echo "$arrSize"
while [ $boolContinue ] && [ $counter -lt "$arrSize" ]; do
echo "${nameArr[$counter]}"
if [ $counter == 0 ] ; then
newName+=${nameArr[$counter]}
counter+=1
elif [[ ${nameArr[$counter]} =~ ^[0-9]{4}$ ]] ; then
newName+=${nameArr[$counter]}
counter+=1
boolContinue=false
else
newName+=${nameArr[$counter]}
counter+=1
fi
done
done

&#x200B;

https://redd.it/15ai9aq
@r_bash
Using JQ to return the index number where an element in an array has a specific value.

I managed to do this when I was teaching myself JSON and playing with JQ. Now I can't remember how I did this. So any guidance would be of value.


Take the following file: settings.json

{
"BotAPIKey": "SuperSecretKey",
"Channels":
{
"Channel_Name": "First Channel",
"Channel_Short": "ch01",
"Channel_ID": 4004841050681
},
{
"Channel_Name": "Second Channel",
"Channel_Short": "ch02",
"Channel_ID": 4004685917007
}

}

If I use the following:

jq '.Channels | contains("ch02")' settings.json

It returns:

false
true

What I actually need is the index number in the array. In this case it must return 1.

I did achieve this once, a few weeks back, when experimenting, and now I can't repeat the results. Like a fool, I didn't document everything I did.

https://redd.it/15axlk0
@r_bash
command being run last even though its first in the noscript

Hi, I am currently trying to create some simple tmux layouts with bash noscripts, but i seem to have hit the wall. This is the noscript in question:

#!/bin/bash
SESSIONNAME="server"

tmux has-session -t $SESSIONNAME &> /dev/null
RESULT=$?
echo RESULT

if $RESULT != 0
then
echo "Creating..."
tmux new-session -s $SESSIONNAME -d
tmux split-window -h "htop"
else
echo "Session already exists. Attaching..."
tmux attach -t $SESSIONNAME
fi

When i run the noscript, it will fail almost everytime because the command tmux has-session -t $SESSIONNAME &> /dev/null is being run last.

Output with -x flag set:

sh -x server.sh
+ SESSIONNAME=server
+
+ RESULT=0
+ echo 0
0
+ 0 != 0
+ echo Session already exists. Attaching...
echo Session already exists. Attaching...
+ tmux attach -t server
+ tmux has-session -t server
can't find session server
can't find session server

For some reason, the command is being run last, which makes the rest of the noscript pretty much obsolete. Binding wait to the process also doesn't work. Does it have something to do with using /dev/null? I really can't wrap my head around it. I guess it's some basic Bash knowledge that I've missed. Thank you in advance

https://redd.it/15az0b1
@r_bash
How to get values from psql inside the database_name variable but send the errors to error_log file?
https://redd.it/15azejl
@r_bash
Best way to escape a . in an argument?

I'm building a CLI and one of the command needs to edit a JSON config file. We decided it would be good to do command edit settings.roles.<username>.role admin to change for example the role of <username to admin. It works smoothly for all cases except when usernames contains a . (dot).

I'm wondering what would be the best way (if any) to escape the . in a username. Note that it's not possible to prevent usernames from containing a . as our usernames contain domain names.

https://redd.it/15bkgu2
@r_bash
Few questions about this noscript if you don't mind helping a newbie...
https://redd.it/15bqomb
@r_bash
bash command to catch opened url by browser

Hello,

is there any bash command or tool which is able to catch the currently urls opened by browsers (Firefox or/and Chromium)?

TIA

https://redd.it/15bqeb6
@r_bash
Someone explain how this obscure code works please!

Hi everyone!

So I found this code that one of my friends sent me.

:; ______=$? __=${#______} ____=$[__+__] ________=$[__+____] _____=$[____+____]
__________=$[____+_____] _________=$[__+__________] ______________=(
/????/$$/????) ____________=${______________[$______]}
_____________=${____________##*/} _______________=(${____________//\// })
________________=${_______________: -$__:$__}$_____________
___________________=${________________:$______:$________}
___________=${_____________:$______:$__} _________________=${___________^}
. <($___________________<<<__________________=\({$_________________..\
${___________}}\))&&_______=(${__________________[@]:$______:$____$__________})
___=(${_______[@],,})&&${___[$_____]}${___[$____]}${___[$_________]}${___[
$__$_____]} -${___[$_____]} ${_______[ $_________]}${___[${_____}]}${___[$__$__
]}${___[$__$__]}${___[$__$_____]} ${_______[$____$____]}${___[$__$_____]}${___[
$__$_________]}${___[ $__$__]}${___[$________]}\\$______$[$_____#$____$____$__]

So basically it prints "Hello World!". I'm just curious to know how this code works even though it's impractical and hella unreadable. Tried finding explanations, but couldn't get anything. Is there any program that converts text to code made of only special characters like this?

https://redd.it/15bsu5c
@r_bash
Intune Mac Scripting

I work for an MSP provider and am trying to deploy a noscript which will install our RMM agent remotely onto Mac devices.
I've tested the full noscript which works directly on the Mac.

However, it fails when running in intune.

Is anyone able to advise?

Script should download the PKG from URL then run the file.

#! Sudo /bin/bash -c curl -o PKG file name "web URL" ; sudo installer -pkg PKG name -target /

https://redd.it/15bu6jk
@r_bash
My nested for loops don't work

Hi, hope you're all well, I have a tough question here but I don't know what to do

I'm a bioinformatician and I want to convert one notation of RNA secondary structure to a .bed format, so, basically let's say I have this string:

........(((..((.((((((((((((....)))))))).....((((.((.......)).))))))))...)).))).

I want to track all the matching "()" and convert those positions into a new string "pos1-pos2", for example we have a matching () in the positions . In this example we have a match in the 8 and 68 positions, so I want to convert this to "8-68" and do it to all the positions.

To do that I wrote this code:

&#x200B;

EDIT: I tried to ident this right but it won't go, sorry

init_pair=()

final_pair=()

checklist=()

&#x200B;

for ((i=0; i<${#fold_result}; i++)); do

check=false

for j in "${checklist[@]}"; do

if [[ "$j" == "$i" ]]; then

check=true

fi

done

if [[ "$check" == false && "${fold_result:i:1}" == "(" ]]; then

checklist+=( "$i" )

init_bp=$(expr "$i" + "$initial_position")

init_pair+=( "$init_bp" )

fi

done

&#x200B;

for ((i=0; i<${#fold_result}; i++)); do

check=false

for j in "${checklist[@]}"; do

if [[ "$j" == "$i" ]]; then

check=true

fi

done

if [[ "$check" == false && "${fold_result:i:1}" == ")" && "${fold_result:i+1:1}" != ")" ]]; then

checklist+=( "$i" )

final_bp=$(expr "$i" + "$initial_position")

final_pair+=( "$final_bp" )

for ((k=i-1; k<"${#fold_result}"; k--)); do

if [[ "{fold_result:k:1}" == ")" && "${fold_result:k-1:1}" == ")" ]]; then

checklist+=( "$k" )

final_bp=$(expr "$i" + "$initial_position")

final_pair+=( "$final_bp" )

elif [[ "{fold_result:k:1}" == ")" && "${fold_result:k-1:1}" != ")" ]]; then

checklist+=( "$k" )

final_bp=$(expr "$i" + "$initial_position")

final_pair+=( "$final_bp" )

break

fi

done

fi

done

My logic is to define two arrays, one of the init pairs ("(") and other for the final (")"), use a checklist array to track it all. First I take all the "(" characters in a for loop, if the index is already in the checklist the loop continues. The next step is to take the final pairs and match, so I took all the ending positions ")", without any other ")" in the next index and started a nested for loop to go through the indexes before and save it in the array, later I would write those pairing positions.

The problem is this loop doesn't return nothing in the final_bp array, I think it's an infinite loop and I don't know how to proceed. Do you have any idea? I suspect that I'm doing the syntax wrong.

Thanks

&#x200B;

https://redd.it/15bzn37
@r_bash
-n not found, If statement not working

Hello world! I´m trying to make the following code work but it fails at the If statement:


#!/bin/bash
for ip in $(seq 1 15);
do
a=$(ping -c 1 192.168.0.$ip | pcregrep -M '([0-9]{1,3}.{1}){4}.*ping.*\n.*1 received' | grep -o -E '([0-9]{1,3}.{1}){4}');
if -n $a; then
echo $a;
else
:
fi;
done

I´m new to bash, regex and networking. Just doing little projects to learn.

When executing the noscript the output says:

noscript.sh: 6: -n: not found

Any help would be appreciated!

&#x200B;

https://redd.it/15cmgbm
@r_bash
persistent 'bad array subnoscript' with any argument

code:

#!/bin/env bash

main() {
local -i value=0
local -A values=(
a=1 e=1 i=1 o=1 u=1 l=1 n=1 r=1 s=1 t=1 d=2 g=2 b=3 c=3
m=3 p=3 f=4 h=4 v=4 w=4 y=4 k=5 j=8 x=8 q=10 z=10
)
while read -r -n 1 char
do
value+=${values$char}
done <<< "$1"
echo -n $value
}

main "$@"


it's rather a simple code that gets the value of a every character in the positional argument from an array, sums them and finally outputs the final value.

The output is correct but I get the 'bad array subnoscript' for any argument (the characters should exist as key in the array though). What's wrong and how can I resolve it?

https://redd.it/15cm2gt
@r_bash
ionotifywait max number of times per minute?

I am using ionotifywait to monitor a set of files for updates and then using it to trigger a rebuild of some javanoscript files. The issue is that I only want to run at "most" one time per 10 minutes, but I don't want to miss a rebuild either. e.g. a file changes after I did a rebuild I want it to trigger another rebuild at the next 10 minute mark. I'm not actually sure this can be accomplished without threading.

&#x200B;

Currently it looks like this

inotifywait -q -m -r -e modify,delete,create,move ${filesToWatch@} | while read FILE EVENT; do
compile
sleep 0.5
done

Any advice?

https://redd.it/15csttp
@r_bash
Question on bash's regex functionality

I was reading pure bash bible. Under the "Use regex on a string" section, it states one caveat using bash's "=~" operator:
> CAVEAT: This is one of the few platform dependent bash features. bash will use whatever regex engine is installed on the user's system. Stick to POSIX regex features if aiming for compatibility.

But the gnu manual says
> When you use ‘=~’, the string to the right of the operator is considered a POSIX extended regular expression pattern and matched accordingly (using the POSIX regcomp and regexec interfaces usually described in regex(3))

It states bash will use POSIX extended regular expression. It seems to contradict pure bash bible. Am I missing anything here?

https://redd.it/15ddrus
@r_bash
Why is this string comparation not working?

Hi, I'm trying to compare a md5 hash with one saved in a file, the result is that always the hashes are unqual, even when they are equal:

#!/bin/bash
checksum=$(ls <FOLDER> | md5sum)
lastchecksum=$(cat CHECKSUM)
if [ "$checksum" != "$last
checksum" ]; then
echo -n $checksum > CHECKSUM
echo CHECKSUMS ARE UNEQUAL
fi

https://redd.it/15dj7z1
@r_bash
test for empty variable throws an error; why?

I have the following snippet which is supposed to be in `.profile`, executed on login:

# mount unmounted disks if found in system
userdisks=( $(find /dev/disk/by-uuid -type l) )
for disk in "${userdisks[@]}"
do
if [ -z $(findmnt "$disk") ]
then
udisksctl mount -b "$disk"
fi
done`

to look for unmounted disks in the system and mounts any it finds, but I get the following error:

-bash: [: too many arguments

for each (mounted?) disk in the system. What is the issue here? It's probably really easy, but I'm stumped at the moment.

An `echo $(findmnt "$disk") looks like this if it's mounted (variable not empty):

`TARGET SOURCE FSTYPE OPTIONS / /dev/mmcblk0p1 ext4 rw,noatime,errors=remount-ro,commit=600 /var/log.hdd /dev/mmcblk0p1[/var/log] ext4 rw,noatime,errors=remount-ro,commit=600

https://redd.it/15em5pj
@r_bash
How to set each nested JSON property to parent property, slightly modified?

I have the following input JSON:

{
"copyToClipboardCmd": {
"type": "string"
},
"editPreset": {
"type": "string"
},
"edit": {
"type": "string"
},
"editAtLine": {
"type": "string"
},
"editAtLineAndWait": {
"type": "string"
},
"open": {
"type": "string"
},
"openLink": {
"type": "string"
}
}

I wanna add new noscript property for each object (containing type) which value has to be equal to parent key with each <upper-letter> replaced by space<lower-letter>. To make it clear, I need to get this:

{
"copyToClipboardCmd": {
"noscript": "copy to clipboard cmd",
"type": "string"
},
"editPreset": {
"noscript": "edit preset",
"type": "string"
},
...

I use YQ currently.

https://redd.it/15f5g2u
@r_bash
Curl command resulting in "argument list too long" error. How should I reformat my command?

Hi, everyone. As someone who has practically zero experience with APIs (or the curl command), I am struggling to understand how I should fix this error. I have tried different fixes that result in only more errors, although I wonder if it is my syntax that is causing the problems.


Essentially, I need to rewrite the code below so I don't get the "argument list too long" error. I will paste how it looks currently (changing some sensitive information to generic terms):


\-------------------------


curl --location --request POST 'https://oauth.site.com/api/SendCCDA' \\

\--header 'Authorization: 123456789' \\

\--header 'Content-Type: application/json' \\

\--data '"{\\"CCDABase64\\": \\"'"${baseCCDA}"'\\",\\"EncounterId\\": \\"'"${encounterRef}"'\\",\\"Denoscription\\": \\"CCDA for '"${givenName}"' '"${familyName}"'.\\",\\"EncounterDateTime\\": \\"'"${encounterDate}"'\\",\\"PhysicianName\\": \\"Admin\\",\\"ProviderId\\": \\"Admin\\",\\"PracticeId\\": \\"'"${locationArr[0\]}"'\\",\\"FacilityId\\": \\"'"${locationArr[0\]}"'\\",\\"CreatedBy\\": \\"User\\",\\"OrganizationId\\":\\"0\\" ,\\"PatientDetails\\": {\\"PatientID\\": \\"'"${patientDFN}"'\\",\\"MRN\\": \\"'"${patientDFN}"'\\",\\"FirstName\\": \\"'"${givenName}"'\\",\\"LastName\\": \\"'"${familyName}"'\\",\\"DoB\\": \\"'"${birthDate}"'\\",\\"Gender\\": \\"'"${gender}"'\\"}}"'


\------------------------


The idea of the command is that it sends a base64 converted version of a CCDA (xml file) to the identified server. As you can guess, the different variables (like encounterRef or givenName for example) are pulled from the CCDA with prior bash code and put in the proper place within the command.


The issue is with the baseCCDA variable; apparently it results in too much text and the curl command is canceled because of it. I know the command works because if I submit a shorter CCDA file, it works properly. Only when I try to submit a longer CCDA file do I get the error.


What would be the best way to rewrite this? All input is much appreciated. Thanks in advance.

https://redd.it/15fky3b
@r_bash
Set default conda env for terminal, but not for system python use

Hi all. I'm running Linux Mint and do some development with Python. I successfully installed conda, and created my-env that I want bash to use when I open a terminal. Currently, whenever I start a terminal conda shows base as the active (default?) env. If I add `conda activate <my-env>` to my `.bashrc` file, would that mean the Python-based programs on my system would use my-env, or would they still use base to run?

My goal is to separate all my Python development stuff from the system default/global python, but I'm admittedly still a newbie when it comes to Python envs.

https://redd.it/15fpc7u
@r_bash