r_bash – Telegram
I want real world examples of what do you actually use Bash for.

Hi, it seems like everyone is recommending me to learn Bash but no one really explain me why.

When I asked them what do you use it for, they said "everything" and that's it.

​

Could you guys give me 1-2 examples of what do you use it for, in your daily life.

How does it make you life easier?

​

P.S. Sorry for my English.

https://redd.it/wrb25x
@r_bash
Entering an interactive CLI loop

I have an application with an interactive CLI. Fairly simple c++ using stdIO with an infinite loop and command parsing. Works really well in a terminal.

I can call this program fine from a noscript like this:

printf "cmd1 cmd2 cmd3 printstatus cmd4 cmd5" | ./myprog

I want to be able to call this program and then take actions from it in a noscript, like:

./myprog
-args
#magic missing step
printf "cmd1"
printf "cmd2"
result= printf "print
status"
if( $result == "active")
printf exit
fi

Etc.

Is there an easy way to create this?

https://redd.it/wtdejn
@r_bash
Filling an associative Array inside a function using a nameref variable

Hello guys,

I have a question for you. I'm writing a noscript that's supposed to check certain PCs over ssh. To achieve this, I have an associative array `declare -A test_results` outside the function. Inside the function, I try to fill it with strings that are supposed to be printed to stdout in the end of the noscript. Like this:

function check_pc{
# $1 = Room name, $2 = pc number, $3 = Array test_results

local -n result=$3

if ! ssh $SSH_OPTIONS $SSH_USER@$1-pc$2.$DOMAIN echo test >/dev/null; then
result[$1-pc$2]="$1-pc$2 is unreachable\n"
# V_ECHO contains "echo" if run with -v option
$V_ECHO "[Debug] In function check_pc - Content of result varibale for $1-pc$2: >>> ${result[$1-pc$2]} <<< [SSH]"
return 1
fi
}

Imagine my room name is n040 and pc number is 10. Inside the function it'll output `${result[n040-pc10]}` just fine: "n040-pc10 is unreachable\\n". Outside of the function though, `$test_results[n040-pc10]` is empty.

This function is being called in a loop with many machines simultaneously like this:

...

declare -A test_results

...

for (( pc_count=0; $pc_count<=${PC[$lab_count]}; pc_count=pc_count+1 )); do
printf -v PC_COUNT "%02d" $pc_count
check_pc ${LAB[$lab_count]} $PC_COUNT test_results &
done

...

Why is `$test_results` empty? Can anyone help me out here pls? Maybe there are smarter ways of doing this?

pls no roasting, constructive criticism is welcome. I'm not experienced with bash noscripts.

Thank you :)

https://redd.it/wvq8fo
@r_bash
How do I copy data from a USB port into a file ? $cat <port> , but for binary ?

I need to send a command to an oscilloscope via a USB port. I need to put the binary reply into a file.

Right now I am using this:

echo ":SYST:UTIL:READ? 1,33554432" > /dev/usbtmc0; cat /dev/usbtmc0 > reply.bin

It works well for text replies but seems to mess up binary replies. How do I put the binary reply that comes from /dev/usbtmc0 into a file ?

Thanks

Solution

$cat actually works in this situation. There was a problem with the downstream file processing that led me to say that $cat wasn't working. I was wrong.

&#x200B;

&#x200B;

https://redd.it/wvyaue
@r_bash
Can you add features such as Syntax highlighting and Auto-suggestions to Bash?

Recently I've started to experiment with Bash and I have one question. Is their a way to add Syntax highlighting and Autosuggestions to Bash? The one thing I LOVE about the Fish shell is it's out-of-the-box autosuggestion feature that not only tries to auto-complete commands, but also suggests from your command history, this is the one thing I think Fish dose better than any other shell and I'm hoping that I can replicate it on Bash.

I know it's challenging to implement autosuggestions in Bash because it's a limitation of GNU readline - Bash uses readline for entering and editing text, but this means you're limited to using readline features for dynamic line editing. E.g you cannot dynamically change the color of text a user inputs using readline (limiting the implementation of Fish-like syntax highlighting).

Do any workarounds exist to make syntax highlighting and autosuggestions work in Bash? Any help would be much appreciated.

https://redd.it/wylaoj
@r_bash
How to interpret ANSI escape characters in a file?

Is there an easy way to read a text file (presumably a log of a previously executed command) and interpret any escape sequences so that cat'ing the new log file is equivalent to viewing it in a text editor? For example, if the output of the command sends the letter A, a backspace, and then the letter E, the log file (after being interpreted) should only contain the character E and nothing else.

EDIT: Figured it out

https://redd.it/wzk2ly
@r_bash
Authentication Bearer Token

Is it possible to obtain the auth bearer token of a login session through noscript? I want to POST something on my website via curl POST but can't as it required bearer token to be passed. Can I use my creds to GET token in command line or through bash noscript?

https://redd.it/x05q6v
@r_bash
Brash Cli Trash Manager in Pure Bash

Why Brash

Well, why not. As you see its similar to Trash\_cli. Unlike Trash_cli, Brash don't Depends on any Python libs just pure bash.

So why not ?

https://redd.it/x0m7y4
@r_bash
Is there a Bash equivalent to Zsh Named Directories feature?

Hi, I read that Zsh has the Named Directories feature, where you can create an 'alias' to a path.

The neat part is that you can use this alias as part of a command.

So, instead of using something like:

cp .bashrc /very/long/path/name

I could use:

cp .bashrc vlpn

Does Bash has something like that?

https://redd.it/x1nik6
@r_bash
Is it possible to stop a bash a bash noscript during execution and then return back to where you left off the next time you run the noscript

Hopefully the noscript makes sense, for context let's say this is the situation:

- I'm running a bash noscript that runs random commands one by one and in order to proceed to each next command the user has to press the spacebar. there are about 80 items

- Let's say the user presses CTRL+C to stop the noscript from executing halfway through those 80 items

Is there a way to return back to where they were in noscript execution when they cancelled the noscript? Or do they have to re-run the noscript and then start at the very beginning again?

https://redd.it/x225ew
@r_bash
Re-directing outputs from a noscript that uses FFmpeg to recursively transcode video files

Hi all. I have very little experience so far with bash noscripting, so please forgive my rudimentary question... but I've been given a noscript that uses FFmpeg to recursively transcode mkv video files to mp4 derivatives:

#!/bin/bash
VIDEOS=/Users/ExampleUser/Desktop/1
cd /Users/ExampleUser/Desktop/1
find "$VIDEOS" -name '*.mkv' -exec sh -c 'ffmpeg -analyzeduration 15M -guess_layout_max 0 -i "$0" -y -pix_fmt yuv420p -codec:v libx264 -fps_mode cfr -r 29.97 -filter:v "yadif,scale=640:480" -aspect 4:3 -preset medium -g 60 -sc_threshold 0 -profile:v main -b:v 1000k -minrate 900k -maxrate 1200k -bufsize 2000k -tune film -pass 1 -an -f mp4 /dev/null ; ffmpeg -i "$0" -y -pass 2 -pix_fmt yuv420p -codec:v libx264 -fps_mode cfr -r 29.97 -filter:v "yadif,scale=640:480" -preset medium -g 60 -sc_threshold 0 -profile:v main -b:v 1000k -minrate 900k -maxrate 1200k -bufsize 2000k -tune film -map 0:0 -map 0:1 -codec:a aac_at -ac 2 -ar 48000 -b:a 128k -filter:a "aresample=async=1:min_hard_comp=0.100000:first_pts=0" -f mp4 -movflags faststart "${0%%.mkv}_sl.mp4"' {} \;
rm *.log.mbtree *.log
exit;

Right now, it outputs the derivative mp4s into the same directory as the source mkv files (specified by the variable VIDEOS). How can I change the output destination for the mp4 files? Ideally, I'd like to re-direct the mp4 outputs to a different disk attached to our workstation. Many thanks for any suggestions!

https://redd.it/x2knt0
@r_bash
How can I write this if condition more efficiently?

if $a -eq 0 && $b -eq 0 && $c -eq 0 ; then

I want to do something like:

if $a && $b && $c -eq 0

i just don't know how to format it correctly

https://redd.it/x37adx
@r_bash
Any tip on optimizing this?

Hi!

I have a waybar module to track Spotify that runs every two seconds.
Since it runs so frequently I want it to be as performant as possible.

This is what I came so far:

#!/bin/sh

player="playerctl -p 'spotify'"
metadata="$player metadata"

playerstatus=$(eval $player status 2> /dev/null)

([ "$player
status" = "Playing" ] || "$player_status" = "Paused" ) && \
printf "$(eval $metadata artist) - $(eval $metadata noscript)"

It works, but I figured this is a nice opportunity to learn something new about shell-noscripts.
Does anybody have any tip or idea on how to improve this for runtime footprint?

Thanks in advance :D

EDIT: result thanks to @rustyflavor and @oh5nxo:

player=$(playerctl -p 'spotify' metadata -f "{{ artist }} - {{ noscript }}")

"$player" != "No players found" && printf "$player"

https://redd.it/x3ez5w
@r_bash
Are parentheses wrapped around the primary case statement variable required?

Parentheses:

case "$1" in
esac

Without parentheses:

case $1 in
esac

Would I have to worry about whitespace, and or weird ass symbols in the $1 variable? Or does the case statement simply not care? If parentheses are not required in any stretch of the imagination, then I will write all my dash noscript case statements without parentheses.

https://redd.it/x3vnes
@r_bash
How can I replace this grep command? I'm getting the Argument list too long error.

Hello, I'm very new to bash so this can probably be easily solved.

I'm writing a bash noscript that stores a list of files in a variable, and then I need to grep those files from a much larger list that contains the files from the first list. Don't know if that makes sense. Here's how I did it:

finalList=$(cat <(echo "$completeList") | grep "$partialList")

It works fine most of the time, however, in some cases the "$partialList" has a lot of files, and the "grep: Argument list too long" error pops up. Any workaround I can use? I read I could use the find command but I'm not really sure how to apply it here.

Thanks in advance!

https://redd.it/x42cnc
@r_bash
I've been trying to make a noscript to simplify my very common find command usage, but it's not working in three ways

First, I can't figure out how to use . in a variable. I want to use . so that output from find is like ./dir1/dir2/file, instead of /home/user/project/date/dir1/dir2/file. In line 7 below at the point SEARCH_DIR="$PWD" is what I need help with for using . please, as I've resorted to $PWD.

Second, the find command when executed from my bash noscript is not doing wildcard expansion on the *. I echo the command I'm running and copy and paste it into bash and it works as intended, but when run from my noscript file it says No such file or directory.

Third, it can't actually find the directory I pass to it. So if I do ff *test* -s /, it says No such file or directory.

Here is the noscript:

#!/bin/bash

# File Find

FILENAME="$1"
shift
SEARCHDIR="$PWD"
EXCLUDED
DIRS=

-z "$FILENAME" && echo "No filename pattern supplied."

while "$#" -gt 0 ; do
echo "$#"
case "$1" in
-x | --exclude ) EXCLUDEDDIRS="${EXCLUDEDDIRS} ! -path '${2}'"; shift 2 ;;
-s | --search-dir ) SEARCHDIR="$2"; shift 2 ;;
* ) shift ;;
esac
done

case "$SEARCH
DIR" in
"WebModules") EXCLUDEDDIRS="${EXCLUDEDDIRS} ! -path '${PWD}/obj/'" ;;
) ;;
esac

COMMAND="find ${SEARCHDIR} ${EXCLUDEDDIRS} -name ${FILENAME} -print"
echo "$COMMAND"
"$COMMAND"

https://redd.it/x45d70
@r_bash
can someone what did I overlook

what is the purpose of the noscript: unlocking the dataset using the curl command

the code that works:

curl "`https://$host/api/v2.0/pool/dataset/unlock`" -k -X POST -H "accept: */*" -H "Content-Type: application/json" -H "Authorization: Bearer 1-$API_TOKEN" -d '{"id": "the_dataset_hardcoded","unlock_options": {"key_file": false,"recursive": false,"toggle_attachments": true,"datasets": [{"name" : "the_dataset_hardcoded" , "passphrase" : "the_password_hardcoded"}]}}'

now this one works flawlessly, but the moment i try to replace the "the_dataset_hardcoded" and/or the "the_password_hardcoded" as an environmental variable the noscript stops working

my next try is to create the part as a string that i can echo out for debugging so i create:

curl_builder3="'{\"id\": \"$pool\",\"unlock_options\": {\"key_file\": false,\"recursive\": false,\"toggle_attachments\": true,\"datasets\": [{\"name\" : \"$pool\" , \"passphrase\" : \"$pass\"}]}}'"

and run it like this:

curl "`https://$host/api/v2.0/pool/dataset/unlock`" -k -X POST -H "accept: */*" -H "Content-Type: application/json" -H "Authorization: Bearer 1-$API_TOKEN" -d $curl_builder3

but what i get for this is:

curl: (3) unmatched brace in URL position 1:

{"key_file":

^

bash: line 3: Server: command not found

&#x200B;

but when I echo the created env variable i get the correct string that if i copy and run in terminal it does what is supposed to do

&#x200B;

now what did I miss

&#x200B;

&#x200B;

edit:

the curl command is now fixed and it looks like this:

curl "`https://$host/api/v2.0/pool/dataset/unlock`" -k -X POST -H "accept: */*" -H "Content-Type: application/json" -H "Authorization: Bearer 1-$API_TOKEN" -d "{\"id\": \"$pool\",\"unlock_options\": {\"key_file\": false,\"recursive\": false,\"toggle_attachments\": true,\"datasets\": [{\"name\" : \"$pool\" , \"passphrase\" : \"$pass\"}]}}"

&#x200B;

https://redd.it/x5v910
@r_bash
I am once again asking for your noscripting support

How are you doing bash ninjas?

I learned a lot about noscripting in my last post here, and I want to see if there is some other hidden improvement that can be done on a little noscript I created, and hopefully learn something new on the way.

I use wireplumber to control volume, the command I use to increase volume is

wpctl set-volume @DEFAULTAUDIOSINK@ 1%+

but as a downside, this command allows to increase volume well over 100%, which I don't like.
I figured I could check the volume with this command

sicro@sicro ~ $ wpctl get-volume @DEFAULTAUDIOSINK@
Volume: 1.00

so if I were to pipe the output to awk I could: remove the Volume: part, compare the numbers, and pass the corresponding argument to the original command like this

wpctl set-volume @DEFAULTAUDIOSINK@ $(wpctl get-volume @DEFAULTAUDIOSINK@ | awk '{ print ($2 >= 1) ? "100%" : "1%+"}')

Now, this needs two calls to wpctl and awk to do the math.
Does anybody can come up with a better version that can reduce the processes spawned?

Thank you for your time :D

https://redd.it/x7ab4y
@r_bash