r_bash – Telegram
Commands executed in a subshell meaning?

My understanding of what a subshell is comes from

https://www.gnu.org/software/bash/manual/bash.html#Command-Execution-Environment

which says that “a subshell is a copy of the shell process,” and that “commands are invoked in a subshell environment that is a duplicate of the shell environment…”

This implies that a subshell looks exactly like the parent shell aside from some minor differences which is different from creating a new shell since the new shell won’t see the previous shell’s shell variables.

So for example a bash noscript is not run in a subshell since it creates a new shell.

Assuming my understanding of what a sub shell is is correct, my confusion stems from

https://www.gnu.org/software/bash/manual/bash.html#Pipelines which says that

“each command in a multi-command pipeline, where pipes are created, is executed in its own subshell, which is a separate process.”


Is a new subshell created for every command “invoked in a subshell environment,” or does it work where builtins or other bash stuff cause a subshell to be created, but a subshell is not created for simple commands and they are the same as running a simple command from the parent shell?


https://redd.it/1aw0o98
@r_bash
I'm trying to make a noscript to enable/disable a gnome extension

Here is my noscript :

!/bin/bash

set -x

STATE="$(gnome-extensions show | grep State)"

if [[ $STATE == *"ENABLED"* \]\]; then

gnome-extensions disable

else

gnome-extensions enable

fi

but it succeeds only in enabling the extension and not disabling it, but I can't find what's wrong...
Do you have a clue ? 🎺

https://redd.it/1awd3ql
@r_bash
I'm trying to make a noscript to enable/disable a gnome extension

Here is my noscript :

#!/bin/bash

STATE="$(gnome-extensions show **window-list@gnome-shell-extensions.gcampax.github.com** | grep State)"

if [[ $STATE == *"ENABLED"* \]\]; then
gnome-extensions disable **window-list@gnome-shell-extensions.gcampax.github.com**
else
gnome-extensions enable **window-list@gnome-shell-extensions.gcampax.github.com**
fi

but it succeeds only in enabling the extension and not disabling it, but I can't find what's wrong...
Do you have a clue ? 🎺


https://redd.it/1awd3qh
@r_bash
I have a lot of folder in my linux machine with a lot of file, find duplicate files and delete them

I have liinux box and I have many many folders and in each folder many many files.

I am sure many of these files are duplicate, for example I have 1.mp4 in folder Videos, in folder Downloads and other folders.

I want bash noscript search all hard drive and find these files and show me and after that delete all of them.

https://redd.it/1awh0sm
@r_bash
PS1 issues,

My prompt glitches sometimes when scrolling through history, it will do things like drop characters,

"$ git push" will become "$ it push" but still work.

Another one that appears sometimes is ✔️ will add another of themselves for each character that I delete from my command.

Any ideas what is causeings this?

\------ a the majority (but not all) of my prompt code ------

PS1="\\n${PS1_USER}\\u ${PS1_BG_TEXT}at${PS1_SYSTEM} \\h ${PS1_BG_TEXT}in${PS1_PWD} \\w ${PS1_GIT}\\${GIT_INFO}\\

\\n\\${EXIT_STAT}${PS1_WHITE}\\$ ${PS1_RESET}"

\# function to set PS1

function _bash_prompt(){

\# This check has to be the first thing in the function or the $? will check the last command

\# in the noscript not the command prompt command

\# sets a command exit statues

if [[ $? -eq 0 \]\]; then

EXIT_STAT="✔️" # Green "✔️" for success

else

EXIT_STAT="" # Red "" for failure

fi

\# git info

export GIT_INFO=$(git branch &>/dev/null && echo "$(__git_ps1 '%s')")

}


(Edit grammar and formatting)

https://redd.it/1awhjr5
@r_bash
`fg` does not work in noscripts for raw terminal mode processes

just so we are on the same page, here is small c program

void enableRawMode() {
struct termios raw ;
tcgetattr(STDIN_FILENO, &raw);
raw.c_lflag &= ~(ECHO | ICANON | ISIG);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
}
int main() {
enableRawMode();
sleep(3)
return 0;

}

to accurately get pid, we do this:

./main & MAIN_PID=$!
echo $MAIN_PID
fg

for some reason this works when copy-pasting this into terminal, but when written in noscript, running it gets "`tcgetattr: Inappropriate ioctl for device`"

same with when running other programs which use raw mode, like vim (although different error message)

plz help >:

https://redd.it/1awfhbd
@r_bash
Syntax of current branch in terminal is off, please help!

I reformatted my laptop with Linux Mint 21.3, it's coming from 21.2. I commented out this code:

if "$color_prompt" = yes ; then
PS1='${debianchroot:+($debianchroot)}[\03301;32m\\u@\h[\03300m\:[\03301;34m\\w[\03300m\\$ '
else
PS1='${debianchroot:+($debianchroot)}\u@\h:\w\$ '
fi
unset colorprompt forcecolorprompt

and added this code snipped immediately ahead of it:

git
branch() {
git branch 2> /dev/null | sed -e '/^^*/d' -e 's/ \(.\)/(\1)/'
}
if "$color_prompt" = yes ; then
PS1='${debianchroot:+($debianchroot)}[\03301;32m\\u@\h[\03300m\:[\03301;34m\\w[\03301;35m\$(gitbranch)\[\033[00m\]\$ '
else
PS1='${debian
chroot:+($debianchroot)}\u@\h:\w$(gitbranch)\$ '
fi

This resulted in the terminal prompt looking like this:

(bash) user@Grell:~/GitHub/noscripts main$

I changed it slightly to:

git_branch() {
git branch 2> /dev/null | sed -e '/^[^
]/d' -e 's/ \(._\)/(\1)/'
}
if "$color_prompt" = yes ; then
PS1='${debianchroot:+($debianchroot)}[\03301;32m\\u@\h[\03300m\:[\03301;34m\\w[\03301;35m\$(gitbranch)\[\033[00m\]\$ '
else
PS1='${debian
chroot:+($debianchroot)}\u@\h:\w$(gitbranch)\$ '
fi

And it looks like this:

(bash) user@Grell:~/GitHub/noscripts(m)ain$

Most of the resources I'm finding online provide one of these two code snippets, or something similar, so I haven't yet found a solution. The coloring of the prompt is as it was on my 21.2 installation, so that part's likely correct, I just need to figure out the parentheses.

How can I get it to look like this:

(bash) user@Grell:~/GitHub/noscripts(main)$

My entire .bashrc is in comments.

https://redd.it/1awrk6i
@r_bash
How do I keep pv printing on the same line of rsync progression instead of scrolling the entire progression? I can't get zenity or yad to show any progress at all.

Thats basically it, I have a noscript that I use for drive/directory syncing to select a host and then select one or more peripherals in the /media directory to sync to. It's all done and like I want with one exception, I am tying to figure out how to show the progression with a progress bar of some kind that actually show the progress. The pv option works well for the information I need, except it scrolls to the next line on every write instead of overwriting the same line and that's not going to work. I'm not married to pv so if anyone has any better ideas or suggestions...

I was thinking of piping the pv command to a function that forces it to read and rewrite it to the same line by sending it through a printf command, but is there a better way to make pv write to the same line?

Or, is there another way I can do a progress bar when using rsync that will allow me to show a more accurate representation of the syncing process? So far nothing I've tried works to show the progression of rsync. I think the problem is a reliable count progression and the progress bar like with yad and zenity isn't getting the count as it progresses to show the bar sliding across.

Any ideas?

Rsync on a dry run reports 20,000+ files but during the actual write, only those needing updated in the archive on the actual run will update even though both use the same flags and options, throwing off the progress count.

I'm not sure if any of these would make a difference on how rsync passes data to one of the progress options. The "--info=name0" option, I found out, only displays the output line of rsync which would give the status line only of rsync which can work if I can't get an accurate display of a progress bar to work. Should I add a "-v" option as well? Or any other?

The options info sent to both the dry run and actual is:
>OPTIONS="-Puham"

>FLAGS="--no-i-r --info=progress2 --mkpath --preallocate --no-motd"

https://redd.it/1awqsa3
@r_bash
am stuck in a gameshell (part 3) btw i cant use if while ... and cant use && ; .... and thank u guys sm for the help

,------------------------------------------------------------------------.

(_\\ \\

| Objective |

| ========= |

| |

| You are on a road trip and stopped at a gas station to buy a |

| map of Canada. On the back of this map, there is a set of |

| tables that give the city located at each highway exit as well as |

| some of its attractions. We have reproduced these tables in the |

| files in the "tableaux" directory. The file names correspond to the |

| names of highways. They are classified by province in subdirectories |

| of "tableau". Each file presents its data in the following format: |

| |

| - The first line describes the first exit, the second line the |

| second exit, and so on. |

| - The city and its attractions are separated by a semicolon ";" |

| - Attractions are separated by spaces. |

| |

| For example, the Ontario highway 416 is described by the file |

| "tableaux/Ontario/416" which has the content |

| |

| Johnstown;bridge |

| Edwardsburgh;mill gallery |

| Spencerville;sailboat |

| ... |

| |

| indicating that Edwardsburgh is located at the second exit and its |

| attractions are a mill and a gallery. |

| |

| There is exactly one city in Canada that has an "orchestra" and is |

| adjacent to a city with a "mill" on the same highway. Find this |

| city, its highway, and exit number. |

| |

| Constraints |

| =========== |

| |

| - You are allowed only one command. |

| |

| Hints |

| ======= |

| |

| - Try to minimize the number of different commands used. |

_| |

(_/__________________________________________________________________(*)___/

\\\\

))

\^

​

https://redd.it/1awxoaq
@r_bash
bash noscript development

what would be the overall noscript of a role that mostly consisted of bash noscript development. would that be a software developer? or something else?

https://redd.it/1ax6z7w
@r_bash
How to sort arrays natively in Bash

https://vorakl.com/articles/bash-sort/

Bash supports sorting arrays natively through the asort built-in command. However, this command is not always loaded by default. The article shows how to build Bash from source to access all loadable modules, including asort.

https://redd.it/1axonee
@r_bash
division of numbers

I am trying to make a notification for low battery for my arch laptop. I decided to use bash because it blends nicely with everything else

#!/bin/bash
chargeNow=$(cat /sys/class/powersupply/BAT0/chargenow)
chargeFull=$(cat /sys/class/powersupply/BAT0/chargefull)

echo $chargeNow
echo $chargeFull

perBat=$((chargeNow/chargeFull))

echo $perBat

as to my knowledge this should output a proper percentage but it outputs 0.

The outputs for chargeNow and chargeFull are correct

https://redd.it/1axx58m
@r_bash
Tracing where a function was called from

Take for example the following noscript:

#!/bin/bash

function somefunctionname {
some
code
goes
here
}

function anotherfunctionname {
some
other
code
goes
here
}

main
code
goes
here

What I want to do is have the first function identify if I called the first function from inside the second function or from inside the main part of the code. Is there a way to do this automatically without using global variables or adding data to the end of the function call?

​

Edit: Basically I need to know if it was called from inside another function, and if so, what was that function called. If I don't get a function name I can assume it's the main program.

https://redd.it/1ay443h
@r_bash
I had some questions about setting up bash auto-completions (when you hit <TAB> twice) for a complicated shell function

Im trying to figure out how to set up auto-completions (where it will auto-complete on `<TAB>` if it can or bring up a list of possible completions on a 2nd `<TAB>`) for my [forkrun](https://github.com/jkool702/forkrun) utility, which runs code in parallel with syntax much like `xargs -P`.

Ive never worked with autocompletion nor readline, and while I think I could get something working for a fairly simple function I suspect that getting `forkrun'`'s auto-completion how Id like it is going to take some advanced bash auto-complete magic. There are 2 aspects that make setting up auto-completion for forkrun tricky:

***

TRICKY BIT #1: it requires options to be in the same general format as `xargs` where you have:


... | forkrun [forkrun_options] [--] command [command_options]

# NOTE: everything in `[...]` is optional

**Ideally, I would like it to:**

1. initially auto-complete forkrun options, then
2. for the first option that doesnt start with a `-` or `+` OR the option immediately after a '--' (whichever comes first) have it auto-complete commands, and then
3. for all remaining options do auto-completions for that command (should they be available)

***

TRICKY BIT #2: `forkrun` uses a limited degree or "fuzzy" option matching. Options are identified using a `while-->case` loop with extglob-based case conditions. In practice, this basically means that each hoption has several aliases. Currently, options passed to forkrun trigger 1 of 39 different possible (unique) code paths, but there are ~400 possible different inputs that can trigger them (i.e., on average each unique option codepath has ~10 aliases).

See [forkrun.bash - lines 40-210](https://github.com/jkool702/forkrun/blob/main/forkrun.bash#L40) for the specific extglob matching criteria, but *most* of the possible matches are shown in the below `echo` command. Each line corresponds to all the possible aliases for a single option.

**Ideally, I would want the auto-completion to only offer up 1 possible auto-completion from each option (whatever is the shortest completoin based on what is already typed)**.

For example, if someone types `forkrun -pip` and hits tab I want it to auto-complete to `-pipe`, not to show `-pipe` `-piperead` and `-pipe-read` as possible completions, since all those completions are aliases and they all trigger the exact same codepath

***

# options with arguments are accepted with either 1 or 2 leading dash ('-') characters. arguments can be passed as '-opt <arg>' or '-opt=arg'
# options without arguments (excluding the ones for displaying help) are accepted with either 1 or 2 leading dash ('-') and/or plus ('+') characters
# this applies to both the short (single-letter) and long option types. i.e., { '-o' '--opt' '--o' '-opt' } all work

# option takes an argument that can be passed via either:
# '-opt <arg>'' (2 inputs) --OR-- '--opt=<arg>' (1 input)
# the <arg> doesnt need to be auto-completed, but the option flag before it does.
echo -{,-}{j,P,nprocs}{,=} \
-{,-}{t,tmp,tmpdir}{,=} \
-{,-}l{,=} -{,-}{,n}line{,s}{,=} \
-{,-}L{,=} -{,-}{,N}LINE{,S}{,=} \
-{,-}{b,byte,bytes}{,=} \
-{,-}{B,BYTE,BYTES}{,=} \
-{,-}{d,delim,delimiter}{,=}


# option does NOT take an argument, and can be passed via either:
# '-opt' (enable option/flag) --OR-- '+opt' (disable option/flag)
echo {-,+}{,-,+}{i,insert} \
{-,+}{,-,+}{I,INSERT,INSERT-ID,INSERTID} \
{-,+}{,-,+}{k,keep,keeporder,keep-order} \
{-,+}{,-,+}{n,number,numberlines,number-lines} \
{-,+}{,-,+}{z,0,zero,null} \
{-,+}{,-,+}{s,subshell,sub-shell,sub-shell-run,subshell-run} \
{-,+}{,-,+}S {-,+}{,-,+}{S,s}tdin{,run,-run} \
{-,+}{,-,+}{p,pipe,piperead,pipe-read} \
{-,+}{,-,+}{D,Delete,delete} \
{-,+}{,-,+}{N,NO} {-,+}{,-,+}{N,n}{O,o}{,-}func \
{-,+}{,-,+}{u,unescape} \
{-,+}{,-,+}{v,,vv,vvv,vvvv,verbose}

# option displays help text on
stderr and then returns.
# There are 5 different "levels" of help text that can be displayed.
echo -{,-}usage \
-{,-}{\?,h,help} \
-{,-}help={s,short} \
-{,-}help={f,flags} \
-{,-}help={a,all}

***

Any tips on how to go about implementing this? Can anyone confirm whether or not it is even possible to do this in the way id like for it to work?

Thanks in advance.

https://redd.it/1ayr2up
@r_bash
Multiple bash versions

I am working with a code. My Visual Studio Code has bash version 5 but when I run it, it runs with version 3. Even when I check from direct terminal, it says version 3. How to make it run with version 5 always?

https://redd.it/1ayug8u
@r_bash
How to enable 'live' history expansion on the current line?

When I migrated from my old computer to new I lost the ability to perform 'live' history expansion while I type - at least, this is how I recollect it would work - for example, consider these two commands...

ls -l /etc/hosts
cat !$

.. if I recall correctly, as soon as I press SPACE after typing the dollar sign in the second command, the "!$" would be 'live' expanded to "/etc/hosts". It was *very* useful because you can see what the expression would expand to prior to submitting the command.

&#x200B;

https://redd.it/1ayx5d4
@r_bash
bash automatic completion question: is there a way to programatically determine (from inside a noscript/function) what the completions would have been for some commandline?

Title mostly sums it up - id like to be able to figure out what completions would have been suggested for some (partial) command line had you typed it and hit tab twice, but from inside a (non-interactive) noscript/function.

I know you can get the completion that was used with a given command via `complete -p ${command}`, but I cant seem to figure out how to feed that a command line programatically and trigger having it give completions.

***

My use case is I am adding completions to my [forkrun](https://github.com/jkool702/forkrun/blob/main/forkrun/bash) utility. `forkrun` is fundamentally a function that runs other commands for you (in parallel), and so its commandline is structured

forkrun [<forkrun_options>] [--] <command> [<command_options>]

I have [autocompletion working for the `<forkrun options>` and for the `<command>` itself](https://github.com/jkool702/forkrun/blob/forkrun_autocompletion/forkrun.bash#L928), but for any remaining `<command_options>` I would like to generate the same completions as what would have been generated if someone had typed

<command> [<command_options>]

with a partially typed last option directly into the terminal and then hit tab twice.

Thanks in advance.

https://redd.it/1az5jsd
@r_bash
Anyone else?

I'm writing a noscript that does all my install and config from a base xorg install of Arch. My noscript offers WM choices and choices for a simple or extended install. Nothing hard at all...but sometimes I just stare at it running options through my head looking for ways to make it more functional..etc. I see all these options but just can't move forward because as soon as I do write something I will come up with a better way. I have been staring at the skeleton of my noscript for hours.
At least I have a good playlist playing.
What do you do to break out of this mode?

https://redd.it/1az8xmn
@r_bash
Command working diffent in the shell than inside noscript.

Hello.

This command give to me my current public IP:

curl checkip.amazonaws.com

MyPublicIp

But if I try to use the same command inside a noscript or with a extra tool like awk in the command line, I get this extra output:

curl checkip.amazonaws.com | awk -F . '{print $1}'

% Total % Received % Xferd Average Speed Time Time Time Current

Dload Upload Total Spent Left Speed

100 15 100 15 0 0 110 0 --:--:-- --:--:-- --:--:-- 111

200

But I don't know how to get rid of that extra output, any ideas I will appreciated people, thanks!!!

&#x200B;

https://redd.it/1azjfxj
@r_bash
Calling all Bashers who work with JSON files...

Hi, I work extensively with JSON files in my automation noscripts, so much that I got sick of writing out long lines for JQ.

So I have been building a Bash library with all the JSON functionality I need, as simple to use functions that then do all the underlying work for you.

I need such a library for four other projects I am working on for work, however, we believe in OpenSource and want to give it to you all to use. Before then, I need testers, and I need people to provide recommendations for additional features.

So far we have these functions:

* jsonadd - add a key as an array/value/object to a location
* jsondelete - delete a key from a location
* jsonecho - echo out a location as a string - either to display or into a variable
* jsonedit - edit a key at a location
* jsonembed - strange one, but I have a use case, basically convert JSON where all " is escaped to be \\"
* jsonextract - as above, but the other way round
* jsonlist - list all key names at a location, either to display or into an array
* jsonmerge - merge two json files or datasets into a single file or data sets. Convert matching locations into arrays. Option to merge dups into single entries.
* jsonnew - create a new blank jsonfile or dataset.
* jsonpretty - convert a json file into a pretty format
* jsonsearch - find all locations of a keyname and list them either on screen or into an array
* jsonseek - find all index values in array where key=value - output to screen or an array
* jsonskeleton - writes an array of json keys to a location with each key=null
* jsonsize - if it's a string it returns number of characters, if its a number / boolean / null returns 0, if it's an object returns number of keys, it's an array returns number of indexes.
* jsonsort - writes json file or data into alphabetical order - conserves order of array indexes
* jsonstring - convert a json file into a condensed single line file
* jsontest - tests a key location - returns void if not exist, else returns string, number, null, boolean, object or array
* jsonvalid - validates json file, returns an array of errors or returns nothing if it is valid
* jsonwrite - writes json from a variable to a new file

https://redd.it/1azjs67
@r_bash