Handy scripts you'd like to share

Remove certain text at the beginning of many file names

Sample, if you have multiple files like

20221227 2210 - Random TV Chanel HD - Make Arch Great Again.ts

but you need only 'Make Arch Great Again.ts', use

for file in *.ts; do
    echo mv "$file" "${file#*-*- }"
done

in '#!/bin/bash' script.

Remove 'echo' if the output looks ok.


More on https://stackoverflow.com/ :wink:


3 Likes

Start and stop your conkys with a simple command

This script will start a conky if it's not running; if it is running, it will kill it.

Useful for keybindings; as the same keybinding will either start or stop the conky.

It takes the name of the conky config file as an argument.

Please note to use it, you must call your script "toggleconky.sh"; this is due to the grep declaring the PID variable: we only want the line output of ps that has the actual running conky.

PID=`ps -ef | grep -v -P 'grep|toggleconky' | grep -o -P $REGEX  | awk '{print $2}'`

You can name your script anything, but change that line accordingly.

#!/bin/sh

# USAGE: toggleconky.sh <name of conky config> 

CONFIG=""
if [ -z "$1" ]; then
	exit 0
else
	CONFIG=$1	
fi
#echo $CONFIG
REGEX='.+conky.+'$CONFIG
#echo $REGEX

PID=`ps -ef | grep -v -P 'grep|toggleconky' | grep -o -P $REGEX  | awk '{print $2}'`
#check if PID, if not, we start, otherwise, kill
#echo $PID
if [ -z "$PID" ]; then
	#echo 'not found...start'
	conky -c ~/.config/conky/$CONFIG
else
	#echo 'found, kill'	
	kill -9 $PID
fi
4 Likes

Many user use more than one conky files :wink:

I use

killall conky

done :wink:
And as sample

 conky -c ~/.config/conky/conky-shct

or use an alias for that.
But basically I have conky because I want to see it :wink:

But basically your script is a nice thing. :slight_smile:

4 Likes

Agree, Conky is made to be seen. But this is Linux, and you do it because you can :slight_smile:

Actually wrote the script for when I was developing lua conkys....I'd create the occaisional bug (not often, most of my code is bug free :slight_smile: ) and lua would start dumping reams of stdout....it was easy to just use my toggleconky.sh to stop it and start it again...."!!" became my friend.

I have a section of my monitor now for "wildcard" conkys. I can choose which one I want there and use my keybindings to display it (or kill it).

The script actually morphed from a similar use case where I needed to start/stop a process from a keybinding (because its a headless computer governed by a flirc remote). The tricky part is getting all the grep/regex to extract the PID so you can execute kill.

Like the "killall" suggestion...when I was a wee lad, all I had was "kill".

2 Likes

A couple simple fish shell abbreviations for the lazy ones like me:

.dots
abbr -a .dots -r '\.{3,}.*' --position anywhere -f _abbr_dots
function _abbr_dots
    string match -qr '\.\.(?<dots>\.+)(?<rest>.*)' -- $argv
    echo ..(string replace -a '.' '/..' -- $dots)$rest
end

Allows to shorten repeated leading ../ with multiple dots also when entering a filename, e.g.
micro .../file.txt expands to micro ../../file.txt.

.conf
abbr -a .conf -r '~~.*' --position anywhere -f _abbr_conf
function _abbr_conf
    test -n "$XDG_CONFIG"
    and set -l cfg $XDG_CONFIG
    or  set -l cfg ~/.config
    set -q _abbr_conf_tab   # skip expanding the shortcuts on tab completion
    or switch $argv         # shortcuts for frequently used files and dirs
        case '~~f'      ; set argv '~~fish'
        case '~~fc'     ; set argv '~~fish/config.fish'
        case '~~fcd'    ; set argv '~~fish/conf.d'
        case '~~ffn'    ; set argv '~~fish/functions'
        case '~~fa'     ; set argv (status -f) # this file
        case '~~s'      ; set argv '~~sway'
        case '~~ss'     ; set argv '~~sway/scripts'
        case '~~scd'    ; set argv '~~sway/config.d'
        case '~~w'      ; set argv '~~waybar'
        case '~~wc'     ; set argv '~~waybar/config'
        case '~~ws'     ; set argv '~~waybar/scripts'
        case '~~wss'    ; set argv '~~waybar/style.css'
        case '~~grub'   ; set argv '/etc/default/grub' # shortcuts do not need to be in .config
    end
    set -e _abbr_conf_tab
    string replace -r '^~~' $cfg/ -- $argv |string replace -r ^$HOME/ '~/'; or true
    # reset status in case the path wasn't in $HOME and the second replace failed
end~~~

Allows to shorten ~/.config[/name] with ~~[name], where 'name' can also be one of the configured shortcuts (the case statement and _abbr_conf_tab can be removed if no shortcuts are desired).


Note that Ctrl-Space can be used to avoid expanding, and Ctrl-Z to undo the expansion after the fact.

File completion won't work until after expansion, which is somewhat annoying.
I see no downside in binding / and tab to also first expand abbreviations though:

bind /  expand-abbr self-insert
bind \t expand-abbr complete # or (to skip shortcuts on tab completion):
bind \t 'set _abbr_conf_tab; commandline -f expand-abbr; commandline -f complete'
# NOTE: 'set _abbr_conf_tab' expand-abbr complete  does not work

and, why not (unrelated):

bind \e 'commandline -P; and commandline -f cancel; or commandline -f kill-whole-line'

Note: bindings (especially \t) may be ignored depending where they are issued, e.g. in conf.d.

4 Likes

Hangman is a must for every terminal user. (debatable)

https://chonkyrabbit.eu/git/random_games.git/tree/hangman.lua

if you have a word list, you could use cat worldlist | shuf -n 1 | xargs lua hangman.lua

https://chonkyrabbit.eu/git/raspi_power_button.git/about/

Power button for your Raspi, in case you ever lose control...

3 Likes

Copy command output or file(s) contents from command line, wrapped in forum markup ([details] and ~~~) with relevant details text. Most common escape codes are stripped by default.

./forum.fish
#!/bin/fish

function _forum_wrap
    argparse -is 'a/ansi' 'l/lang=' 'd/details=' -- $argv
    set -q _flag_a; or set esc_filter 's,\x1B\[[0-9;?]*[a-zA-Z],,g'
    printf %s\n "[details=\""(echo $_flag_d |string replace -r '^'$HOME '~' |string replace -r '^'$PWD '.' )"\"]" "~~~$_flag_l"
    sed -E "$esc_filter"
    printf %s\n "~~~" "[/details]" ""
end
function _forum_copy
    # this is to work around wl-copy detecting some text as binary data (embedded control chars?)
    if set -q WAYLAND_DISPLAY; and type -q wl-copy
        wl-copy -t 'text/plain;charset=utf-8'
    else
        fish_clipboard_copy
    end
end
function .cc
    set -l _flag_l 'text'
    set -l _flag_d "$argv"
    argparse -is 'a/ansi' 'l/lang=' 'd/details=' -- $argv
    $argv |_forum_wrap -d "$_flag_d" -l "$_flag_l" $_flag_a |_forum_copy
end
function .cf
    argparse -is 'a/ansi' 'l/lang=' -- $argv
    for item in $argv; _forum_wrap -d "$item" -l "$_flag_l" _flag_a <$item; end |_forum_copy
end
function .inxi
    .cc garuda-inxi
end

test "$_" = source; and exit

argparse -is 'a/ansi' -- $argv
if isatty stdin
    argparse -is 'i/inxi' -- $argv
    set -q _flag_i; and set argv --cmd garuda-inxi
    argparse -is 'c/cmd' -- $argv
    set -q _flag_c
    and .cc $argv
    or  .cf $argv
else
    set _flag_l ""
    set _flag_d (readlink /proc/self/fd/0)
    argparse -is 'l/lang=' 'd/details=' -- $argv
    _forum_wrap -d "$_flag_d" -l "$_flag_l" $_flag_a |_forum_copy
end

Use directly from command line, with redirection:
COMMAND | forum.fish
forum.fish <FILE

Use directly from command line, with arguments:
forum.fish FILE...
forum.fish -c COMMAND
forum.fish -i == -c garuda-inxi

Use the functions after sourcing it:
.cf FILE... copy the FILE(s) contents
.cc COMMAND LINE copy the output of COMMAND LINE
.inxi copy the output of garuda-inxi

Options:
-a --ansi allow ANSI escapes (default no)
-l --lang set syntax language (printed after ~~~, default "text" for command output)
-d --details set details text (default filename or command, can't be set for files given as arguments)

Limitations/problems:
When piping into the script, details text will be "pipe:[XXXX]" by default.
Cannot pipe/redirect into .cc and .cf functions, only the main script.
Some combination of arguments may be nonsensical.
Not all ANSI escape sequences are stripped.
(I'll probably fix these issues some day).

Other notes:
Does not depend on wl-copy anymore and should work on all environments (thanks to the fish_clipboard_copy function).
@sgs

4 Likes

To be able to run fish scripts from your terminal, you have to do two things.

  1. Add the following shebang line to the top of your script file: #!/usr/bin/env fish.
  2. Mark the file as executable using the following command: chmod +x <YOUR_FISH_SCRIPT_FILENAME>.
1 Like

Ah, I forgot to say, forum.fish is supposed to be sourced somewhere in the in the fish config.
It does not run as forum.fish from the command line.
Now that you mentioned it though... hold my beer.

1 Like

And

.inxi
find-the-command: "wl-copy" is not found locally, searching in repositories...
find-the-command: "wl-copy" may be found in the following packages:
	community/wl-clipboard
	chaotic-aur/wl-clipboard-rs
Abhängigkeiten werden aufgelöst …
Nach in Konflikt stehenden Paketen wird gesucht …

Paket (1)               Neue Version  Netto-Veränderung  Größe des Downloads

community/wl-clipboard  1:2.1.0-3              0,10 MiB             0,03 MiB

Gesamtgröße des Downloads:             0,03 MiB
Gesamtgröße der installierten Pakete:  0,10 MiB

:: Installation fortsetzen? [J/n] 

and

.inxi
Failed to connect to a Wayland server

? :wink:

1 Like

I though wl-clipboard was installed by default, my bad.
I don't know why "failed to connect" though, it works here.
Whoogle time.

1 Like

didn’t you say you use X11? Dare I request an inxi from the master of inxis?

1 Like

Always depends on which computer I am using, better, which DE is running on it.
:joy:

2 Likes

Reworked screenshot.sh for Sway:

~/.config/sway/scripts/screenshot.sh
#!/bin/bash

padding=$'\u2001 '
entries=( "$padding"$'<big>⮻ </big>\t'{'Copy','Save'}' active'
          "$padding"$'<big>🗔 </big>\t'{'Copy','Save'}' window'
          "$padding"$'<big>⛶ </big>\t'{'Copy','Save'}' area'
          "$padding"$'<big>⎙ </big>\t'{'Copy','Save'}' screen'
          "$padding"$'<big>🖵 </big>\t'{'Copy','Save'}' output'
        ) # 🗔  ❑  ⬚  ⎙  ⛶  ⌗  ▢  🖵  ⧠  ⮻

declare -l selected=$(printf '%s\n' "${entries[@]}" | wofi -mq -iM fuzzy -k /dev/null --style=$HOME/.config/wofi/style.widgets.css --conf=$HOME/.config/wofi/config.screenshot)

: ${selected:+$(/usr/share/sway/scripts/grimshot --notify ${selected#*$'\t'})}

# -mq           allow pango and strip it away
# -iM fuzzy     case insensitive fuzzy matching
# -k /dev/null  disable caching, i suspect it causes the occasional "shuffled entries" bug.
~/.config/wofi/config.screenshot
hide_search=true
hide_scroll=true
show=dmenu
lines=6  # should be 5 but it needs one more for some reason
columns=2
# may have to adjust width and height, 25% looks nice for me
width=25%
~/.config/sway/config.d/default
bindsym print         exec /usr/share/sway/scripts/grimshot --notify save output
bindsym Shift+print   exec /usr/share/sway/scripts/grimshot --notify copy area
bindsym Control+print exec ~/.config/sway/scripts/screenshot.sh
Copy active Save active
🗔 Copy window 🗔 Save window
Copy area Save area
Copy screen Save screen
🖵 Copy output 🖵 Save output

Note: since the icons are not all the same width I had to put a tab in there to keep the labels aligned.
It would cause excessive spacing between the icon and the label though, hence the padding.
It may need adjustment. First padding character has to be some other invisible than a normal space.
The final line expects the tab to be there, to split the icon away and then pass the remaining lowercase label text to grimshot.
If the items appear scattered around, it's likely too much padding (depends on the font size).
If the items appear shuffled, it's likely a wofi bug (I think it's worked around with -k /dev/null though).

4 Likes

Tried to get up and running with Davinci Resolve yesterday, and lets just say it wasn't a smooth experience :laughing:. Turns out onetbb causes it to hang on launch, and one of the recommended fixes is to rename libOpenCL.so temporarily. Thus bringing about the birth of this script.

#!/bin/bash

# /usr/bin/start-resolve.sh
# hacky startup script for bugged davinci resolve on systems running onetbb
# renames libOpenCL.so to bypass davinci hang, then restores

user="kilo" # replace with the username you use resolve with
exec=/opt/resolve/bin/resolve "$@"
dir="/opt/intel/oneapi/compiler/2023.0.0/linux/lib"
file="libOpenCL.so"
delay=2

rename() {
    from="$dir/$file"
    to="$dir/_$file"

    if [ $1 == 1 ]; then
        if ! [ -f $from ]; then return 0; fi
        echo "renaming $from"
        mv $from $to
    else
        if ! [ -f $to ]; then return 0; fi
        echo "restoring $from"
        mv $to $from
    fi
    return 1
}

restore() {
    sleep $delay
    rename 0
}

launch() {
    echo "running $exec as user $user"
    sudo -u $user $exec ;
}

cleanup() { rename 0; }
trap cleanup EXIT

rename 1 
restore & launch

Unfortunately it requires root to run mv in this location, so chmod +x the file. That means you'll need to type a password to run Resolve. A bit annoying, but not the end of the world.

I tried to slap this into a desktop file, and run in the background, but was unsuccessful. That means I've been running it with the terminal open. So, in it's current state, that's another slight annoyance. Oh well, beats manually renaming the file manually every time, I guess.

[Desktop Entry]
Version=1.0
Type=Application
Name=DaVinci Resolve
GenericName=DaVinci Resolve
Comment=Revolutionary new tools for editing, visual effects, color correction and professional audio post production, all in a single application!
Path=/opt/resolve/
Exec=sudo -i sh -c "/usr/bin/start-resolve %u"
Terminal=true
MimeType=application/x-resolveproj;
Icon=/opt/resolve/graphics/DV_Resolve.png
StartupNotify=true
Name[en_US]=DaVinci Resolve
StartupWMClass=resolve

I'm new to bash, and always open to suggestions and criticisms. If anyone knows how to make this run in the background, I'd gladly update this post with the provided information. I tried Exec=sudo -i sh -c "/usr/bin/start-resolve %u &", and a couple other weird things, but it refuses to run.

Edit: Whoops, slight bug in the .sh causing the file not to be renamed back on delay, fixed.

Edit 2: One solution is to use Exec=sudo -i bash -c "nohup /usr/bin/start-resolve %u &" but I'm not sure if that's ideal since I read it'll persist through logout.

You can kick a terminal program to the background with Ctrl+Z to interrupt, then bg to resume in the background. I don't know how to incorporate that into the script, but at the very least you could type it in manually so you can close the terminal after the script is running.

1 Like

Neat tip, thanks. I'll have to look more into this as it didn't seem to work while resolve is running.

Oh bummer, it's not running once you start it in the background with bg you mean?

This article says with a single ampersand you can start a script in the background to begin with.

./my_cool_script.sh &

I better get out of this thread, my scripting skills are pretty flimsy! :laughing:

2 Likes

I’m not sure if it’s because I’m starting it up with sh -c or what. Trying to suspend works if I run from terminal directly, but just results in ^z being printed from the .desktop launch.

I tried with the &, but there must be something simple I’m missing as to why that doesn’t work. ¯\_(ツ)_/¯

LOL, yeah I’m in the same boat. Regardless, I appreciate the efforts.

Perhaps I should stick to web development :laughing:

1 Like