r_bash | Unsorted

Telegram-канал r_bash - r_bash

36

Credits: @r_channels & @reddit2telegram

Subscribe to a channel

r_bash

;;&
[A-Za-z=])
cs+=";$(c2n "$c")";
(((bb+=10)>20)) && return 1
;;
-)
cs+=";22;24"
;;
+)
cs+=";1"
;;
_)
cs+=";4"
;;
.)
((bb+=10))
;;
*)
return 1
;;
esac;
done;
printf "\e[%sm" "${cs#;}" )
}

Again, all feedback is welcome! I'm not trying to encourage adoption of this thing, it's more of a puzzle of brevity and optimization. I learned a lot from /u/o11c the first time I showed it. (If you think you can use it, have at it.)

I especially don't like using `;22;24` to clear underline and bold formatting, but `\e[0m` clears the colors as well as the formatting, and I don't want to have to preserve any state to know which one needs clearing.

https://redd.it/11sjtcu
@r_bash

Читать полностью…

r_bash

Sshto update

Hi, another sshto update is here. I've played a bit with Selected\_hosts and I though that it could be handy to be able to save this list as permanent config file. Just run EditConf command for Selected_hosts group. Have fun)

https://preview.redd.it/ptifeme3uyna1.png?width=824&format=png&auto=webp&v=enabled&s=e56187548fbb3608618ccd82b277b4844ff6d14d

https://redd.it/11s8vp1
@r_bash

Читать полностью…

r_bash

How to run ffmpeg async to bash

I'm running into an issue where inotifywait stops running after its event fires and runs ffmpeg.

Here's my code:

#!/bin/bash
# This bash script uses inotifywait to watch a directory for new mp4 or mkv files and convert them using ffmpeg.


# Set the directory to watch

DIR="/home/stingwraith/Downloads"

# Wait for a new mp4 or mkv file to be created

inotifywait -m $DIR -e create -e movedto |

while read path action file; do
echo "The file '$file' appeared in directory '$path' via '$action'"

# Check if the file is an mp4 or mkv
if [[ $file == *.mp4 || $file == *.mkv || $file == *.ogv ]]; then
# resolution=$(ffprobe -v error -select
streams v:0 -showentries stream=width,height -of csv=s=x:p=0 $DIR/$file)
# if [ ${resolution#*x} -lt 720 ]; then
# Convert the file using ffmpeg
echo "Starting conversion..."
ffmpeg -hwaccel vaapi -hwaccel
device /dev/dri/ renderD128 -i $DIR/$file -c:v libx264 -vf "scale=1024:576" -crf 25 -preset veryslow -r 22 -c:a aac -b:a 192k -ac 2 $DIR/$file.converted.mp4
echo "Conversion completed! Original file deleted!"
# Remove the original file
rm $DIR/$file
# else
#do something
# fi
fi
done




The problem is that while ffmpeg is running an encoding job, if any new files show up, it won't run ffmpeg on them.

Any help is much appreciated!

https://redd.it/11s2ga6
@r_bash

Читать полностью…

r_bash

My VOIP phone service provides an API to send SMS .. is this how its done using curl

API is

https://www.thevoipcompany.com/send-sms?username=username&password=password&to=destination&subscriptionId=subscription ID&text=message

My understanding curl could do this with something like this ... correct?

>curl -X POST -d 'username=username&password=password&to=destination&subscriptionId=subscription id&text=message' https://www.mynetfone.com.au/send-sms

If correct it would be simple to put it into a bash wrapper.

https://redd.it/11rved7
@r_bash

Читать полностью…

r_bash

Emulate "Copy Link To Clipboard" By Copying Text Wrapper - How To?

Is it possible to do the copying in bash by emulating "copy link to clipboard" when the text wrapper is highlighted? Projecting this onto Markdown format of URL it would look like highlighting the [reddit!] segment of [reddit](https://reddit.com) with (https://reddit.com) going to the clipboard. Refer to the linked image for the visual example.

https://i.imgur.com/AvTIOaM.png

https://redd.it/11rjkpg
@r_bash

Читать полностью…

r_bash

Read contents of file and run a command

My scenario:

cat filesystems.txt
#path;major;minor;average
/var;10;10;10
/opt;10;10;10

Then, my bash must read this file (filesystems.txt) and for each line of this file (except first line), do "df -h" for each item.

My goal is to have this:

df -h /var
df -h /opt

​

https://redd.it/11rl8b0
@r_bash

Читать полностью…

r_bash

Code golf: highly minified function for injecting ANSI color in bash scripts

I've been putting together a function for inserting ANSI color sequences in bash scripts and trying to keep the character count down.

Here's a picture to give you an idea what I'm going for: https://i.imgur.com/6CnnGtN.png

The idea is to replace all those ubiquitous color definition blocks in the scripts I inherit that leave the first page looking like this (clipped from a recent submission here):

#Regular Color Variables
coff='\033[0m' #No Color
black='\033[0;30m'
#Black
red='\033[1;91m' #Red
green='\033[1;92m' #Green
yellow='\033[0;93m' #Yellow
blue='\033[0;94m' #Blue
purple='\033[0;95m' #Purple
cyan='\033[0;96m' #Cyan
white='\033[0;97m' #White
#BackGround Colors Variables
b
black='\03340m'
b_red='\033[41m'
b_green='\033[42m'
b_yellow='\033[43m'
b_blue='\033[44m'
b_purple='\033[95m'
b_cyan='\033[46m'
b_white='\033[47m'

I've got something that supports all 16 colors on all 16 background colors in the standard 4-bit ANSI palette, as well as bold, underline, and "terminal default" codes (`\e[39m`, `\e[49m`).

clr() {
local in="$*" fgb=30 bgb=40 colors="krgybmcw =" fg bg cs
[[ "$in" ] || { printf "%b" "\e0m"; return; } # reset
[[ "$in" == *-* ] && cs=";22;24"; # normal
[ "$in" == *+* ] && cs=";1"; # bold
[ "$in" == *_* ] && cs+=";4"; # underline
in=${in//-_+ /}
[ "${in,,}" =~ ^[.=rgbcmykw{0,2}$ ]] || return 1
fg=${in:0:1}; [ "$fg" ] || fg=.; bg=${in:1:1}; bg=${bg#.}
[ "$fg" =~ [A-Z ]] && fgb=90
[ "$bg" =~ [A-Z ]] && bgb=100
[ "$fg" == "." ] || { i=${colors%%"${fg,,}"}; cs+=";$((${#i}+fgb))"; }
[[ "$bg" ]] && { i=${colors%%"${bg,,}"
}; cs+=";$((${#i}+bgb))"; }
printf "%b" "\e${cs#;}m"
}

I'm trying to keep it mostly minified so it's a tricky read. The less obvious abbreviations are `in`: input arguments, `cs`: control sequence, `fgb`/`bgb`: foreground/background brightness.

`shellcheck --shell=bash clr.sh` surprisingly had no complaints when I fed it this snippet, I was expecting to be flooded with complaints (so many unquoted expansions and assignments!) so I'm not even sure I'm using it right.

The parameters it accepts:

Parameter | Result
---|---
no arguments | Reset to default formatting
r,g,b,c,m,y,k,w | Red, green, blue, cyan, magenta, yellow, black, white
R,G,B,C,M,Y,K,W | Bright versions of same colors
+ | bold
_ | underline
- | strip formatting (bold/underline)
= | terminal default background/foreground
. | placeholder to separate foreground from background when changing background only

It doesn't care about the order of parameters or the spacing, except that the background color must be preceded by a foreground color (hence the no-op `.` placeholder for leaving foreground alone).

I'm trying to make it so that it outputs the minimal escape sequence for the desired formatting: e.g. no `0;` or `1;` when changing only the color. What I most dissatisfied with so far is having to use `22;24` to strip the bold/underline formatting, but `0;` strips the colors along with the formatting (breaking the "Blue bold not bold" example in the screenshot) and I don't want to make the function have to track any state to know whether it's underlining or bold that needs to be cancelled out.

Any tips? Especially ones that reduce the character count!

[
https://redd.it/11ri7f3
@r_bash

Читать полностью…

r_bash

I made a bash script to fetch all Android System Info in the termux app, Any Suggestions can be helpful to improve the script.

https://redd.it/11r1x2y
@r_bash

Читать полностью…

r_bash

Set /P errorMsg=<%TMP%\senseTmp.txt
set "errorOutput=[Error Id: %errorCode%, Error Level: %lastError%] %errorDescription% Error message: %errorMsg%"
%powershellPath% -ExecutionPolicy Bypass -NoProfile -Command "Add-Type 'using System; using System.Diagnostics; using System.Diagnostics.Tracing; namespace Sense { [EventData(Name = \"Onboarding\")]public struct Onboarding{public string Message { get; set; }} public class Trace {public static EventSourceOptions TelemetryCriticalOption = new EventSourceOptions(){Level = EventLevel.Error, Keywords = (EventKeywords)0x0000200000000000, Tags = (EventTags)0x0200000}; public void WriteOnboardingMessage(string message){es.Write(\"OnboardingScript\", TelemetryCriticalOption, new Onboarding {Message = message});} private static readonly string[] telemetryTraits = { \"ETW_GROUP\", \"{5ECB0BAC-B930-47F5-A8A4-E8253529EDB7}\" }; private EventSource es = new EventSource(\"Microsoft.Windows.Sense.Client.Management\",EventSourceSettings.EtwSelfDescribingEventFormat,telemetryTraits);}}'; $logger = New-Object -TypeName Sense.Trace; $logger.WriteOnboardingMessage('%errorOutput%')" >NUL 2>&1
echo %errorOutput%
echo %troubleshootInfo%
echo.
eventcreate /l Application /so WDATPOnboarding /t Error /id %errorCode% /d "%errorOutput%" >NUL 2>&1
GOTO CLEANUP

:SUCCEEDED
echo Finished performing onboarding operations
echo.
GOTO WAIT_FOR_THE_SERVICE_TO_START

:WAIT_FOR_THE_SERVICE_TO_START
echo Waiting for the service to start
echo.

set /a counter=0

:SENSE_RUNNING_WAIT
sc query "SENSE" | find /i "RUNNING" >NUL 2>&1
if %ERRORLEVEL% NEQ 0 (
IF %counter% EQU 4 (
set "errorDescription=Unable to start Microsoft Defender for Endpoint Service."
set errorCode=15
set lastError=%ERRORLEVEL%
GOTO ERROR
)

set /a counter=%counter%+1

timeout 5 >NUL 2>&1
GOTO :SENSE_RUNNING_WAIT
)

set /a counter=0

:SENSE_ONBOARDED_STATUS_WAIT
REG query "HKLM\SOFTWARE\Microsoft\Windows Advanced Threat Protection\Status" /v OnboardingState /reg:64 >NUL 2>&1
if %ERRORLEVEL% NEQ 0 (
IF %counter% EQU 4 (
@echo Microsoft Defender for Endpoint Service is not running as expected> %TMP%\senseTmp.txt
set errorCode=35
set lastError=%ERRORLEVEL%
GOTO ERROR
)

set /a counter=%counter%+1

timeout 5 >NUL 2>&1
GOTO :SENSE_ONBOARDED_STATUS_WAIT
)

set /a counter=0

:SENSE_ONBOARDED_WAIT
REG query "HKLM\SOFTWARE\Microsoft\Windows Advanced Threat Protection\Status" /v OnboardingState /reg:64 | find /i "0x1" >NUL 2>&1
if %ERRORLEVEL% NEQ 0 (
IF %counter% EQU 4 (
@echo Microsoft Defender for Endpoint Service is not running as expected> %TMP%\senseTmp.txt
set errorCode=40
set lastError=%ERRORLEVEL%
GOTO ERROR
)

set /a counter=%counter%+1

timeout 5 >NUL 2>&1
GOTO :SENSE_ONBOARDED_WAIT
)

set "successOutput=Successfully onboarded machine to Microsoft Defender for Endpoint"
echo %successOutput%
echo.
eventcreate /l Application /so WDATPOnboarding /t Information /id 20 /d "%successOutput%" >NUL 2>&1
%powershellPath% -ExecutionPolicy Bypass -NoProfile -Command "Add-Type 'using System; using System.Diagnostics; using System.Diagnostics.Tracing; namespace Sense { [EventData(Name = \"Onboarding\")]public struct Onboarding{public string Message { get; set; }} public class Trace {public static EventSourceOptions TelemetryCriticalOption = new EventSourceOptions(){Level = EventLevel.Informational, Keywords = (EventKeywords)0x0000200000000000, Tags = (EventTags)0x0200000}; public void WriteOnboardingMessage(string message){es.Write(\"OnboardingScript\", TelemetryCriticalOption, new Onboarding {Message = message});} private static readonly string[] telemetryTraits = { \"ETW_GROUP\", \"{5ECB0BAC-B930-47F5-A8A4-E8253529EDB7}\" }; private EventSource es = new

Читать полностью…

r_bash

"{\"body\":\"{\\\"previousOrgIds\\\":[],\\\"orgId\\\":\\\"6ad0aaaa-89b1-418b-934b-399c0ce86225\\\",\\\"geoLocationUrl\\\":\\\"https://winatp-gw-weu.microsoft.com/\\\",\\\"datacenter\\\":\\\"WestEurope\\\",\\\"vortexGeoLocation\\\":\\\"EU\\\",\\\"version\\\":\\\"1.45\\\"}\",\"sig\":\"dyzVy2wM1U9qjupC9HOqogWazgUr+8tdm+M8EcoOKDdfj9TItpL2o2rzZz1mpSD9a2X8FoA1w1HYV3zKE/xzxtx0xxSGPQdFz7la/slpttWqELKGIruE3GYYtWe0tgruqb73rX8nscPj3GCnnzVmLeIRqsWtWOMowMT/R8II7RuFGt51D+dHax4sKJ3VkkSumBVnL61p6nJboDy6htdidTCpkN83e7de9rBXBHMtI2SO5KvLahDqIHoHxulax43v0gM4BcGYZWMCHlBbwZrgPTdcs6H5G18SD7Wyctd6BEDx0t25xrYLHAs4nGlyHhDIhVh0Uyy+uclFjcrxjeajBA==\",\"sha256sig\":\"tjaopRgKg4efsSflwoy8wxymkYOxS2vvHStRwTLFTlLRqzeHq4OVWMV4YqYNhK1ofBkQky77LuVhdVsfwXuRTqPPrzimBgYBLKulCIe5p8s9vbYFbpCXxXxsLHui5LFBI4OORZ9p0Sxzth0AtDUdAjWcvaWWP5Y8b07fXnSRC/VjEOMBZrU+fAtJND/tYuZsBz4ZFJZ6xoPSO4nmoNtXbEh73V/bUkmezuLvxULXWRqiffOIGoPaZmdado/ext9Tu00rYRk1vmVeJXY8Q7D2eJypj4CHaw8OjcsyDMHnmrZf63mkHRi93CEt/XRmTuiPholB08NKtMmdQU9cEeyApg==\",\"cert\":\"MIIFgzCCA2ugAwIBAgITMwAAAgKh9Eww96dTK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jYxMDE4MjMwNTE5WjB+MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSgwJgYDVQQDEx9NaWNyb3NvZnQgU2VjdXJlIFNlcnZlciBDQSAyMDExMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0AvApKgZgeI25eKq5fOyFVh1vrTlSfHghPm7DWTvhcGBVbjz5/FtQFU9zotq0YST9XV8W6TUdBDKMvMj067uz54EWMLZR8vRfABBSHEbAWcXGK/G/nMDfuTvQ5zvAXEqH4EmQ3eYVFdznVUr8J6OfQYOrBtU8yb3+CMIIoueBh03OP1y0srlY8GaWn2ybbNSqW7prrX8izb5nvr2HFgbl1alEeW3Utu76fBUv7T/LGy4XSbOoArX35Ptf92s8SxzGtkZN1W63SJ4jqHUmwn4ByIxcbCUruCw5yZEV5CBlxXOYexl4kvxhVIWMvi1eKp+zU3sgyGkqJu+mmoE4KMczVYYbP1rL0I+4jfycqvQeHNye97sAFjlITCjCDqZ75/D93oWlmW1w4Gv9DlwSa/2qfZqADj5tAgZ4Bo1pVZ2Il9q8mmuPq1YRk24VPaJQUQecrG8EidT0sH/ss1QmB619Lu2woI52awb8jsnhGqwxiYL1zoQ57PbfNNWrFNMC/o7MTd02Fkr+QB5GQZ7/RwdQtRBDS8FDtVrSSP/z834eoLP2jwt3+jYEgQYuh6Id7iYHxAHu8gFfgsJv2vd405bsPnHhKY7ykyfW2Ip98eiqJWIcCzlwT88UiNPQJrDMYWDL78p8R1QjyGWB87v8oDCRH2bYu8vw3eJq0VNUz4CedMCAwEAAaO

Читать полностью…

r_bash

My manager told me to execute this without any explenation on what it does. Anyone here has a clue?

Edit: Sorry, i know it's long, but I'm kinda worried on the nature of this script.

Also, title has typos, sorry.

@echo off

echo This script is for onboarding machines to the Microsoft Defender for Endpoint services, including security and compliance products.
echo Once completed, the machine should light up in the portal within 5-30 minutes, depending on this machine's Internet connectivity availability and machine power state (plugged in vs. battery powered).
echo IMPORTANT: This script is optimized for onboarding a single machine and should not be used for large scale deployment.
echo For more information on large scale deployment, please consult the MDE documentation (links available in the MDE portal under the endpoint onboarding section).
echo.
:USER_CONSENT
set /p shouldContinue= "Press (Y) to confirm and continue or (N) to cancel and exit: "
IF /I "%shouldContinue%"=="N" (
GOTO CLEANUP
)
IF /I "%shouldContinue%"=="Y" (
GOTO SCRIPT_START
)
echo.
echo Wrong input. Please try again.
GOTO USER_CONSENT
echo.
:SCRIPT_START
REG add "HKLM\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection" /v latency /t REG_SZ /f /d "Demo" >NUL 2>&1

@echo off

echo.
echo Starting Microsoft Defender for Endpoint onboarding process...
echo.

set errorCode=0
set lastError=0
set "troubleshootInfo=For more information, visit: https://go.microsoft.com/fwlink/p/?linkid=822807"
set "errorDescription="

echo Testing administrator privileges

net session >NUL 2>&1
if %ERRORLEVEL% NEQ 0 (
@echo Script is running with insufficient privileges. Please run with administrator privileges> %TMP%\senseTmp.txt
set errorCode=65
set lastError=%ERRORLEVEL%
GOTO ERROR
)

echo Script is running with sufficient privileges
echo.
echo Performing onboarding operations
echo.

IF [%PROCESSOR_ARCHITEW6432%] EQU [] (
set powershellPath=%windir%\System32\WindowsPowerShell\v1.0\powershell.exe
) ELSE (
set powershellPath=%windir%\SysNative\WindowsPowerShell\v1.0\powershell.exe
)

set sdbin=0100048044000000540000000000000014000000020030000200000000001400FF0F120001010000000000051200000000001400E104120001010000000000050B0000000102000000000005200000002002000001020000000000052000000020020000 >NUL 2>&1
reg add HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security /v 14f8138e-3b61-580b-544b-2609378ae460 /t REG_BINARY /d %sdbin% /f >NUL 2>&1
reg add HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security /v cb2ff72d-d4e4-585d-33f9-f3a395c40be7 /t REG_BINARY /d %sdbin% /f >NUL 2>&1

REG add "HKLM\SOFTWARE\Policies\Microsoft\Windows\DataCollection" /v DisableEnterpriseAuthProxy /t REG_DWORD /f /d 1 >NUL 2>&1

%powershellPath% -ExecutionPolicy Bypass -NoProfile -Command "Add-Type ' using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; using System.ComponentModel; public static class Elam{ [DllImport(\"Kernel32\", CharSet=CharSet.Auto, SetLastError=true)] public static extern bool InstallELAMCertificateInfo(SafeFileHandle handle); public static void InstallWdBoot(string path) { Console.Out.WriteLine(\"About to call create file on {0}\", path); var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read); var handle = stream.SafeFileHandle; Console.Out.WriteLine(\"About to call InstallELAMCertificateInfo on handle {0}\", handle.DangerousGetHandle()); if (!InstallELAMCertificateInfo(handle)) { Console.Out.WriteLine(\"Call failed.\"); throw new Win32Exception(Marshal.GetLastWin32Error()); } Console.Out.WriteLine(\"Call successful.\"); } } '; $driverPath = $env:SystemRoot + '\System32\Drivers\WdBoot.sys'; [Elam]::InstallWdBoot($driverPath) " >NUL 2>&1

REG query "HKLM\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection" /v

Читать полностью…

r_bash

Cannot match character limit with regex

I have a bit of regex I'm struggling with and cannot seem to get it to only allow up to 20 characters.

I want it to match either with max of 20 characters in length:

test
test-123


I do not want it to match:

test-
-test
test-123-


This is what I have:

^([A-Za-z0-9]+)([-A-Za-z0-9]*)([A-Za-z0-9]+).{1,20}$'

What's wrong with this?

https://redd.it/11qihgm
@r_bash

Читать полностью…

r_bash

[help] Given the output of "df -h"... how to...

Given the output of the "df -h", how to find out the corresponding disk device with single command ? All I am trying to list out the corresponding block device that "/dev/mapper/vg\_name-lvol0" is mounted on. Cheers !

[root@my-host]# df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 7.7G 0 7.7G 0% /dev
tmpfs 7.7G 0 7.7G 0% /dev/shm
tmpfs 7.7G 25M 7.7G 1% /run
tmpfs 7.7G 0 7.7G 0% /sys/fs/cgroup
/dev/nvme0n1p2 20G 4.5G 16G 23% /
tmpfs 1.6G 0 1.6G 0% /run/user/1000
/dev/mapper/vg_name-lvol0 1016M 740M 277M 73% /hellworld

https://redd.it/11qfai7
@r_bash

Читать полностью…

r_bash

How to compare 2 strings and store output to variable without if statement?

Basically I want to achieve something like this

compare="str1" == "str2"

where $compare would either TRUE of FALSE

https://redd.it/11pxlzf
@r_bash

Читать полностью…

r_bash

Trying to Grep urls

I am trying to find a way to find urls (specifically jpgs) with grep, but I just cant seem to find the secret sauce to get the command to work.

what I have right now is

grep -o http.*.jpg jpgfiles.txt

https://redd.it/11pvnjk
@r_bash

Читать полностью…

r_bash

ANSI coloring function for bash scripts, absurdly minified

I've been dabbling with this ANSI coloring function for injecting color into bash scripts. All feedback is welcome!

Essentially, it works like this: https://i.imgur.com/BXEPxva.png

It supports the entire standard 4-bit ANSI palette with all foreground/background combinations, as well as bold and underline. This is a full table of its formatting and color codes: https://i.imgur.com/EKi9KIm.png


(Kudos to /u/o11c for critiquing the first draft and starting me on the path to shaving 200 bytes off my earlier attempt, even if maybe he's an exalted greybeard raised on monochrome monitors who wouldn't touch this function with a ten foot pole on his machines. I'm only guessing.)

-----

I often inherit scripts from colleagues and folks on the web with coloring variables similar to these recent submissions:

-----

https://github.com/vaniacer/sshto/blob/master/sshto#L87



| Input | Output
---|---|----
This script | `printf "${BLD}${RED}${BBLU}"Hello!${DEF}"` | `\e[1m\e[31m\e[44mHello!\e[0m`
clr function | `printf "$(clr +rb)Hello!$(clr)"` | `\e[1;31;44mHello!\e[0m`

-----

https://github.com/Aj-Seven/Android-Sysinfo/blob/master/sysinfo.sh#L2

| Input | Output
---|---|----
This script | `echo "${yellow}${b_blue}foo` | `\e[0;93m\e[44mfoo`
clr function | `echo "$(clr Yb)foo"` | `\e[93;44mfoo`

-----

The function is highly minified, the secret sauce is using `colors="krgybmcw ="` with `i=${colors%%"${1,}"*}` and `${#i}` to find the offset of the color the character represents in the ANSI definitions.

| Black | Red | Green | Yellow | Blue | Magenta | Cyan | White | --- | Term Default
---|---|----|----|----|----|----|----|----|----|----|
My abbreviation | k | r | g | y | b | m | c | w | | =
ANSI fg | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | | 39
ANSI bg | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | | 49
ANSI bright fg | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | |
ANSI bright bg | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | |

I took liberal advantage of the fact that `bg=fg+10` and `bright=normal+60`.

I also wasted seven bytes on unnecessary capitulations toward `shellcheck`, but it passes now.

The ugly shortened variable names represent:

* in: input arguments
* b: basis for color numbering, 30 is the minimum, +60 for bright, +10 for background, +0 through +7 for hue
* bb: background bump, after setting a foreground color add 10 to the next color code to make it a background color instead of a foreground color
* c: single character read from `$in` on the while loop
* cs: control sequence, what goes between the `\e[` and the `m` in the ANSI formatting string

Note the function is defined as `clr() ( ... )` with parentheses instead of the standard `clr() { ... }` braces, this is to run it in a subshell so I can have a function (c2n, color to number) inside my function.

----

clr() (
local in="$*" colors="krgybmcw =" b bb c cs
[ "$in" ] || { printf "\e[0m"; return; }
c2n() { local i=${colors%%"${1,}"*}; printf "%d" "$((${#i}+b+bb))"; }
while c=${in::1}; [ "$c" ]; do in=${in:1}; b=30;
case $c in [A-Z]) ((b+=60));;&
[A-Za-z=]) cs+=";$(c2n "$c")"; (((bb+=10)>20)) && return 1 ;;
-) cs+=";22;24";; +) cs+=";1";; _) cs+=";4";; .) ((bb+=10));;
*) return 1;;
esac
done
printf "\e[%sm" "${cs#;}"
)

Did you know bash's `type` builtin will automatically reformat your functions with its standards for indentation and line breaks? Here's the same function as `type` outputs it for easier reading:

bash-5.1$ type clr
clr is a function
clr ()
{
( local in="$*" colors="krgybmcw =" b bb c cs;
[ "$in" ] || {
printf "\e[0m";
return
};
function c2n ()
{
local i=${colors%%"${1,}"*};
printf "%d" "$((${#i}+b+bb))"
};
while c=${in::1};
[ "$c" ]; do
in=${in:1};
b=30;
case $c in
[A-Z])
((b+=60))

Читать полностью…

r_bash

cp: cannot create regular file '/usr/local/bin/arduino-cli': Permission denied

Hello!

I have what is likely a really dumb question. I'm trying to automate the installation of the arduino-cli. I tried using the following line:

sudo curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR=/usr/local/bin sh

When i try and run that, I get prompted for a password (which makes sense), and then I see this:

Installing in /usr/local/bin
ARCH=64bit
OS=Linux
Using curl as download tool
Downloading https://downloads.arduino.cc/arduino-cli/arduino-cli_0.31.0_Linux_64bit.tar.gz
cp: cannot create regular file '/usr/local/bin/arduino-cli': Permission denied
Failed to install arduino-cli

It appears to not want me to write to this directory, even with sudo access, so I'm a bit confused as to what the issue is, or how to resolve it. I ran :

ll /usr/local/bin

and received back:

drwxr-xr-x 2 root root 4096 Aug 12 2021 ./
drwxr-xr-x 10 root root 4096 Feb 9 2021 ../

If I use sudo, I assume this means I have write access to this folder but maybe I'm misunderstanding permissions. I assume it's somewhere along these lines but wanted to check before I poked around with it too much and broke something.

Any suggestions you can give me would be greatly appreciated. Thanks!

https://redd.it/11s4oay
@r_bash

Читать полностью…

r_bash

Bash continuous parallelization

I work with academic research, specifically with simulations. The important feature of these simulations in the context of the problem is that some of them take longer than others.

I want to run let's say 1000 simulations, each in a single thread of the processador. If my machine has 6 threads i can do several batches of 6 + one batch of the remaining.

Using something like:

./run.out 1 & ./run.out 2 & ./run.out 3 & ./run.out 4 & ./run.out 5 & ./run.out 6 & wait
./run.out 7 & ./run.out 8 & ./run.out 9 & ./run.out 9 & ./run.out 10 & ./run.out 11 & wait

And that's definetly runs faster than doing one by one, sequentially. But if i have at least process that takes a lot longer than the others, i'm losing precious time.

The final question is: Is there a simple way that can i set a fixed number of processes to be running at the same time, and as soon as one is finishes another one takes it place, that way i'm not bottlenecked by a single slower program.

I will greatly apreciate the help, since solving this would greatly improve my reseach.

https://redd.it/11rxgwt
@r_bash

Читать полностью…

r_bash

smenu is so cool! :)

A demo of what kind of menus you can make with smenu, and a small tour of the command line history too, which I have installed on Ctrl-n, since I have FZF on Ctrl-r.

smenu demo

https://redd.it/11rrfcs
@r_bash

Читать полностью…

r_bash

having trouble checking if a drive is mounted!

Greetings everyone,

&#x200B;

I'm making a little wrapper for pmount to automate the mounting/dismounting of hotplugged LUKS USB devices. I'll post the script below.

https://pastebin.com/Tr9ZUEJe

I'm having trouble in particular with the "scan" function. I'm trying to get it to display eligable devices ONLY if they are not already currently mounted. I'm not sure how to do this. Currently, it displays (correctly) all devices which 1.) have a UUID and 2.) have an associated .key file in the $SECRETSDIR/luks folder. I'd like this output to exclude whatever is included in the "currentlymounted" array.

&#x200B;

I'd really value any input about how to accomplish this, thanks in advance!

https://redd.it/11rk4b0
@r_bash

Читать полностью…

r_bash

aliases to save current dir in one terminal and move to it in a different terminal

I often open a new terminal windows to work in the same directory as my current terminal window and I find it annoying to have to manually cd to it, specially if current directory path is long. There is probably a better way but here is what I came up with:

alias sf='pwd > ~/.folder'

alias lf='cd "$(cat ~/.folder)"'

sf is for save folder, lf for load folder.

I literally just came up with that so I haven't really used it for real beyond testing.

https://redd.it/11rjw8q
@r_bash

Читать полностью…

r_bash

While (loop) with if-statement and timeout after 300 seconds

Hi,


I want to create a while (loop) with an if-statement which timesout after 300 seconds, when the neccessary value isnt provided from the service.


My attempt:

# API Request (GET) - Status
API_STATUS=`curl .....`

# Set timeout value
TIMEOUT=0

while [[ "$API_STATUS" != "1.0" ]];
do
# Increase timeout value by 1
TIMEOUT=$((TIMEOUT+1))

if [[ TIMEOUT != "60" ]]
then
# Wait 5 seconds
sleep 5
API_STATUS=`curl .....`

elif [[ TIMEOUT == "60" ]]
then
echo "$TIMESTAMP Not reachable." >> $LOG
exit
fi
done


Note:
Im executing a curl command to get a value from the backend service. If "1.0" then stop while-loop, if the service isnt reachable for example "120 seconds" wait and then proceed.

https://redd.it/11r91rv
@r_bash

Читать полностью…

r_bash

EventSource(\"Microsoft.Windows.Sense.Client.Management\",EventSourceSettings.EtwSelfDescribingEventFormat,telemetryTraits);}}'; $logger = New-Object -TypeName Sense.Trace; $logger.WriteOnboardingMessage('%successOutput%')" >NUL 2>&1
"%PROGRAMFILES%\Windows Defender\MpCmdRun.exe" -ReloadEngine >NUL 2>&1

GOTO CLEANUP

:CLEANUP
if exist %TMP%\senseTmp.txt del %TMP%\senseTmp.txt
pause
EXIT /B %errorCode%

https://redd.it/11qxe60
@r_bash

Читать полностью…

r_bash

CAUswggFHMBAGCSsGAQQBgjcVAQQDAgEAMB0GA1UdDgQWBBQ2VollSctbmy88rEIWUE2RuTPXkTAZBgkrBgEEAYI3FAIEDB4KAFMAdQBiAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAfBgNVHSMEGDAWgBRyLToCMZBDuRQFTuHqp8cx0SOJNDBaBgNVHR8EUzBRME+gTaBLhklodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWNSb29DZXJBdXQyMDExXzIwMTFfMDNfMjIuY3JsMF4GCCsGAQUFBwEBBFIwUDBOBggrBgEFBQcwAoZCaHR0cDovL3d3dy5taWNyb3NvZnQuY29tL3BraS9jZXJ0cy9NaWNSb29DZXJBdXQyMDExXzIwMTFfMDNfMjIuY3J0MA0GCSqGSIb3DQEBCwUAA4ICAQBByGHB9VuePpEx8bDGvwkBtJ22kHTXCdumLg2fyOd2NEavB2CJTIGzPNX0EjV1wnOl9U2EjMukXa+/kvYXCFdClXJlBXZ5re7RurguVKNRB6xo6yEM4yWBws0q8sP/z8K9SRiax/CExfkUvGuV5Zbvs0LSU9VKoBLErhJ2UwlWDp3306ZJiFDyiiyXIKK+TnjvBWW3S6EWiN4xxwhCJHyke56dvGAAXmKX45P8p/5beyXf5FN/S77mPvDbAXlCHG6FbH22RDD7pTeSk7Kl7iCtP1PVyfQoa1fB+B1qt1YqtieBHKYtn+f00DGDl6gqtqy+G0H15IlfVvvaWt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Zysjik0dySTclY6ysSXNQ7roxrsIPlAT/4CTL2kzU0Iq/dNw13CYArzUgA8YyZGUcFAenRv9FO0OYoQzeZpApKCNmacXPSqs0xE2N2oTdvkjgefRI8ZjLny23h/FKJ3crWZgWalmG+oijHHKOnNlA8OqTfSm7mhzvO6/DggTedEzxSjr25HTTGHdUKaj2YKXCMiSrRq4IQSB/c9O+lxbtVGjhjhE63bK2VVOxlIhBJF7jAHscPrFRH\"]}" > %TMP%\senseTmp.txt 2>&1
if %ERRORLEVEL% NEQ 0 (
set "errorDescription=Unable to write onboarding information to registry."
set errorCode=10
set lastError=%ERRORLEVEL%
GOTO ERROR
)

echo Starting the service, if not already running
echo.
sc query "SENSE" | find /i "RUNNING" >NUL 2>&1
if %ERRORLEVEL% EQU 0 GOTO RUNNING

net start sense > %TMP%\senseTmp.txt 2>&1
if %ERRORLEVEL% NEQ 0 (
echo Microsoft Defender for Endpoint Service has not started yet
GOTO WAIT_FOR_THE_SERVICE_TO_START
)
goto SUCCEEDED

:RUNNING
set "runningOutput=The Microsoft Defender for Endpoint Service is already running!"
echo %runningOutput%
echo.
eventcreate /l Application /so WDATPOnboarding /t Information /id 10 /d "%runningOutput%" >NUL 2>&1
GOTO WAIT_FOR_THE_SERVICE_TO_START

:ERROR

Читать полностью…

r_bash

696C1FA1-4030-4FA4-8713-FAF9B2EA7C0A /reg:64 > %TMP%\senseTmp.txt 2>&1
if %ERRORLEVEL% EQU 0 (
REG delete "HKLM\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection" /v 696C1FA1-4030-4FA4-8713-FAF9B2EA7C0A /f > %TMP%\senseTmp.txt 2>&1
if %ERRORLEVEL% NEQ 0 (
set "errorDescription=Unable to delete previous offboarding information from registry."
set errorCode=5
set lastError=%ERRORLEVEL%
GOTO ERROR
)
)

REG add "HKLM\SOFTWARE\Policies\Microsoft\Windows Advanced Threat Protection" /v OnboardingInfo /t REG_SZ /f /d

Читать полностью…

r_bash

bash script to send disk usage telegram alert

Hello, I have found this interesting script googling but it gives me error on line 12 ans 18 percent not found and let not found. Can someone help me fixing it ?

#!/bin/bash

USERID="XXX" #Chat to u/getidbot
KEY="XXX" #Telegram Secret Code
URL="https://api.telegram.org/bot$KEY/sendMessage"
TIMEOUT="10"
threshold="90" #Set Custom Threshold
i=2
result=df -kh /dev/sda1 |grep -v "Filesystem" | awk '{ print $5 }' | sed 's/%//g'

for percent in $result; do
if ((percent > threshold))
then
partition=df -kh | head -$i | tail -1| awk '{print $1}'
TEXT="$partition at $(hostname -f) is ${percent}% full"
curl -s --max-time $TIMEOUT -d "chatid=$USERID&disablewebpagepreview=1&text=$TEXT" $URL > /dev/null
fi
let i=$i+1
done

https://redd.it/11qirwo
@r_bash

Читать полностью…

r_bash

Copy files based on txt file

I must be doing something wrong here while I’m trying bash to copy (with overwrite option) all the files based on txt files, which contains source and destination paths, multiple, different paths.
I tried with cat, with xargs, with no avail…
Any suggestions will be much appreciated.
TiA

https://redd.it/11qg9kd
@r_bash

Читать полностью…

r_bash

Is this the correct way of setting environmental variables in bash ?

I have these environmental variables in csh

setenv CDS_ENABLE_EXP_PCELL true

setenv CDS_EXP_PCELL_DIR ./.expressPcells

If I were to set the same variables in Bash will this be the correct format:

export CDS_ENABLE_EXP_PCELL=true

export CDS_EXP_PCELL_DIR=$CDS_EXP_PCELL_DIR: ./.expressPcells

https://redd.it/11qcsvk
@r_bash

Читать полностью…

r_bash

I made a repo for useful bash scripts

https://github.com/wolandark/BASH\_Scripts\_For\_Everyone

These are my personal bash scripts that I thought other people might also find useful. I'm hoping that other people cleverer than I will contribute to the repo and make it a large bank of shell scripts in one place. I will continue to push more scripts if I come up with anything new and handy. I'll gladly accept PRs and ideas and suggestions.
cheers!

https://redd.it/11pyc2l
@r_bash

Читать полностью…

r_bash

Is there a better way to remove all files of certain extension except most recent?

~/Documents/Blah/Foo Bar~D45EAG74.foo/ contains a bunch of files and folders.
Multiple backups are created within and named something like; Backup_2023-03-12T18-13-02_A_028E165A-42CB-E084-F0C8-04C8EE231D82.backup

I'm needing a way to delete *.backup files while leaving the most recent one alone.

The below works only if there aren't any spaces in the filenames. Sadly, sometimes there are indeed spaces in the filename.

#!/bin/bash
# ~/.scripts/myscript.sh
# Gets run daily via systemd service and timer

myDir="$HOME/Documents/Blah/Foo Bar~D45EAG74.foo/"
myCount=$(find ~/Documents/Blah/Foo Bar~D45EAG74.foo"/ -type f -name '.backup' | wc -l)

if [ "$myCount" -ge 2 ]; then
cd "$myDir"
ls
.backup | head -n -1 | xargs rm --
cd --
fi


I'm hoping there's a cleaner/more efficient way to do this while fixing it so spaces aren't an problem anymore. You can also see that one line has $HOME and another has a ~ in their paths. This triggers my OCD but I'm not sure how to fix it.
Can anyone help me find some solutions?

https://redd.it/11ptomy
@r_bash

Читать полностью…
Subscribe to a channel