Post scripts you've written or use that you have found useful

# Usage: push 'title' 'body'
# Send pushbullet notification to device. Useful after long commands/jobs finish
curl --header 'Access-Token: {{access_token}}' \
--header 'Content-Type: application/json' \
api.pushbullet.com/v2/pushes \
-X POST -d '{"type": "note", "title": "'"$1"'", "body": "'"$2"'", "device_iden": "{{device_id}}"}'

#!/usr/bin/env bash
# Usage: convertcopy img.jpg
# Make copies of an image that bypass dupe image checks
convert "$1" -resize 101% ~/tmp/"$1"_COPY1
convert "$1" -resize 102% ~/tmp/"$1"_COPY2
convert "$1" -resize 103% ~/tmp/"$1"_COPY3
convert "$1" -resize 104% ~/tmp/"$1"_COPY4

#!/usr/bin/env bash
# Usage: manytomp4 dir/*.avi
for file in "$1"; do
if [ -e "$file" ]; then
ffmpeg -i "$file" -f mp4 -vcodec libx264 -preset fast -profile:v main -acodec aac "$file.mp4" -hide_banner
notify-send "$file done"
fi
done
notify-send "all done"

#!/usr/bin/env bash
#Usage : tomp4 vid.avi

ffmpeg -i "$1" -f mp4 -vcodec libx264 -preset fast -profile:v main -acodec aac "$2" -hide_banner

#!/usr/bin/env python3
# For figuring out how long until the workday is over
import sys
from datetime import datetime, timedelta
""" Usage: timeuntil 09:00pm """


def main():
now = datetime.now()
try:
input_time = datetime.strptime(sys.argv[1], '%I:%M%p')
except:
print('Expected argument timestamp string in the format 09:00am')
sys.exit()
input_time = datetime.combine(datetime.today(), datetime.time(input_time))
delta = input_time - now
duration = format_delta(delta)
print(duration)


def format_delta(delta):
s = delta.seconds
hours = s // 3600
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
return f'{hours}h {minutes}m {seconds}s'


if __name__ == '__main__':
main()
else:
print('Must be run as standalone script')
sys.exit()

Attached: sadfrog steve jobs.png (800x850, 175K)

Other urls found in this thread:

imagemagick.org
a.4cdn.org/g/thread/65461068.json
api.pushbullet.com/v2/devices
docs.pushbullet.com/
gitignore.io/api/$@
twitter.com/NSFWRedditVideo

Given a thread url return total size of all files posted in it:
function thread_files_size (){
lynx -dump "$@" | grep '^ File:' | egrep -o '\([^(]+\)$' | sed -E 's/^\(// ; s/,[^,]+\)// ; /KB/ s, KB, 1024 / +, ; /MB/ s, MB, +, ; 1 s/^/4k0\n/ ; $ s/$/\np/' | dc
}

bump

for KDE:

this one darkens the screen
qdbus org.kde.Solid.PowerManagement /org/kde/Solid/PowerManagement/Actions/BrightnessControl setBrightnessSilent 3
xgamma -ggamma .45 -rgamma .45 -bgamma .5


this one will make the brightness acceptable
qdbus org.kde.Solid.PowerManagement /org/kde/Solid/PowerManagement/Actions/BrightnessControl setBrightnessSilent 8
xgamma -gamma .85


and this one is for games/videos
qdbus org.kde.Solid.PowerManagement /org/kde/Solid/PowerManagement/Actions/BrightnessControl setBrightnessSilent 10
xgamma -gamma 1

># For figuring out how long until the workday is over
Wew I made one of these as well, never took it outside the workplace though.

Yeah, I've only ever used it while at work. I just copied it to my home computer for this thread.

This one takes youtube channel URLs from the clipboard (using xclip) or $1 if present, and gives you the RSS feed for that channel in the clipboard:
#!/bin/bash

if [[ $1 == '' ]]

then
start=$(xclip -selection clipboard -o)
channel=$(curl -s $start | head -n 2500 | egrep -o data-channel-external-id=\"........................\" | head -1)
channelid=$(echo $channel | sed s/data-channel-external-id=\"// | sed s/\"//)
prefix=$(echo "youtube.com/feeds/videos.xml?channel_id=")
echo $prefix$channelid | xclip -selection clipboard -i

else
channel=$(curl -s $1 | head -n 2500 | egrep -o data-channel-external-id=\"........................\" | head -1)
channelid=$(echo $channel | sed s/data-channel-external-id=\"// | sed s/\"//)
prefix=$(echo "youtube.com/feeds/videos.xml?channel_id=")
#echo $prefix$channelid
echo $prefix$channelid | xclip -selection clipboard -i

fi

I have a few other ones but they are of no use to anyone else.

sudo dd if=/dev/zero of=/dev/sda1

for converting 565 VGA framebuffers to usable PNGs, e.g. after doing
/dev/fb0 > screen.raw

use this (which I found, not mine):
#!/usr/bin/perl -w
$w = shift || 450;
$h = shift || 800;
$pixels = $w * $h;

open OUT, "|pnmtopng" or die "Can't pipe pnmtopng: $!\n";

printf OUT "P6%d %d\n255\n", $w, $h;

while ((read STDIN, $raw, 2) and $pixels--) {
$short = unpack('S', $raw);
print OUT pack("C3",
($short & 0xf800) >> 8,
($short & 0x7e0) >> 3,
($short & 0x1f)

Thanks, man. This is very useful

Awesome!

Some scripts for use with acme:
ind indents a selected block
#!/bin/rc

sed 's/^/ /' $*

unind unindents a selected block
#!/bin/rc

sed 's/^ //' $*

neat

what does this do wit your disks

Fills MBR and other shit with zeros

Why? ;_;

Also why not use /dev/null instead of /dev/zeron?

Not sure if bait or not, but do it and you're fucked for good. dd = disk destroyer.

>Why? ;_;
Because I need to fill the beginning of drive with zeros, to make sure that custom boot loader will work as intended.
>Also why not use /dev/null instead of /dev/zeron?
null is one symbol, with 1 byte size (I think), and zero - infinitive number of zeros.
dd is command to write files directly to drive.

Ok, so you're genuinely asking this.
It makes no sense to dd zeros onto /dev/sd1, because most of the time your os is installed to that particular partition, bombarding it with zeros or random data will fuck up your system for good.
I did migrate OSs a lot of times using dd and co, but I'd advise against it if you do not absolutely positively know what you're doing.

Thanks for this

Attached: buzzlightyearmrs.nesbitt.jpg (1600x921, 156K)

Fuck, I've meant /dev/sda...

Can you elaborate more why you're running this command?

Only a bunch of shitty excel macros to try and alleviate our lack of a proper database

>curl
>not using httpie

alias ls="rm -rf"

curl is usually already installed, httpie not so

tru dat

>not alias sudo='sudo rm -rf / --no-preserve-root ;'

nice cheers Op

very useful could have used this is a scrape recently

thanks! how do i view the RSS feed?

>thanks! how do i view the RSS feed?
Not him, but I think you just paste it somewhere after running the script

right but how do u run/view it. No experience with it.

try going to the site with your browser, firefox at least has a built in rss feed reader

You could merge the channel and channelid lines if you use a positive lookbehind.

Paste this into a new Automator Services Run Shell Script where Service receives image files in Finder and pass input as arguments.
Requires ImageMagick.
# Concatenate several selected images into one horizontal strip with normalized height
# This Automator script requires ImageMagick
# $ brew install imagemagick or install manually from imagemagick.org

# Force Automator's Bash session to export the interactive $PATH and thereby recognize commands outside /usr/bin:/bin:/usr/sbin:/sbin
if [ -f ~/.bashrc ]; then source ~/.bashrc; fi
if [ -f ~/.bash_profile ]; then source ~/.bash_profile; fi

# Get smallest height image
minheight=`identify -format "%[fx:h]\n" "$@" | sort -gr | tail -n1`

# Create output filename, JPEG format
outdir=`dirname "$1"`; fname="ImageStrip`date '+%Y%m%d%H%M%S'.jpg`";

# Create command chain for convert to set all images' height to minheight
unset imcommand; for f in "$@"; do imcommand+=("$f" -geometry "x${minheight}"); done;

# Append images at the correct height and normalize resolution
convert "${imcommand[@]}" +append -density 72x72 "$outdir/$fname"

Converts text files to Shift-JIS encoding. Paste this into a new Automator Services Run Shell Script where Service receives selected files or folders in Finder and pass as arguments:
for f in "$@"
do
xattr -w com.apple.TextEncoding 'Shift_JIS;2561' "$f"
done

Open selected URL in incognito mode in Chrome. Paste this into a new Run AppleScript where Services receives selected URLs in any application, input it entire selection:
on run {input, parameters}
tell application "Google Chrome"
make new window with properties {mode:"incognito"}
activate
set URL of active tab of front window to input
end tell
end run

Dang, that pushbullet one is nice.

Anymore like that that can be used in a lot situations?

Jow Forums has a json api, you know. Not only is it easier to parse, but it gives you actual file sizes in bytes as opposed to rounded KB/MB values.
This thread: a.4cdn.org/g/thread/65461068.json (grep for "fsize")

>sar (search and replace)
grep -lr '$1' | xargs sed -i 's/$1/$2/g'

>repeat (for repeating a command)
local i max
max=$1; shift;
for ((i=1; i C-like syntax
eval "$@";
done

thats fucking awesome! thanks!

>Dang, that pushbullet one is nice.
Can you explain how that's useful please? I have no idea how pushbullet works... thanks.

I'm gay

Attached: 2018-04-09-025138_528x431_scrot.png (528x431, 31K)

Pushbullet has a bunch of different features, most of them involving push notifications.

For instance, if you have the chrome extension installed, there a submenu of your devices in the right click menu that you can send the link to your device. Or from your device you can use the share feature of apps to send content or links from one devices to other devices or to your desktop browser.

The script just uses pushbullet's API to send a push notification to your device but it's pretty useful since you can tack it onto a command that takes a long time to finish so that if you're away from your computer and it finishes you will get a notification on your phone that the task was completed.

oh, neat! I have a Raspi that I'd like to send notices from. will give it a try.

Okay, I signed into Pushbullet and I have the access-token but I have no idea what "device_iden" is. How do I get that? Anyone know? Thanks!

If you have a device registered with the account (eg. chrome extension installed in desktop browser or mobile app installed on phone/tablet with that account) you can get the device identity by making a request on the device API resource. This command should work, I think
curl --header 'Access-Token: :auth_token:' api.pushbullet.com/v2/devices

ah, thanks! I actually omitted the device part and it also just werkz.

# Make directory and cd into it (for .bashrc)
mkcd() {
mkdir -p $1;
cd $1;
}
#Go up one or more directories (for .bashrc)
up() {
cd $(printf "%0.0s../" $(seq 1 $1));
}

Oh, yeah. If you do that it sends to all devices, I think.

More info here:
docs.pushbullet.com/

># Make directory and cd into it (for .bashrc)
mkcd() {
mkdir -p $1;
cd $1;
}
fuck that's shitty programming.

It works mate.
If you wanna improve it, please do.

no need to be mean

>It works
yeah, but not always and it's not safe either.

he didn't write that. and it's not mean. it's just blunt. are you new to Jow Forums? seems so.

ok, thats true
mkcd() {
mkdir -p $1 && cd $1;
}

that will work a little better, thanks

it's still crap. but you're slowly getting there.

move all images in a directory into subdirectories named by the image resolutions
#!/bin/sh

# check if required arguments are provided
if [[ "$#" < 2 ]]; then
echo "usage: $0 "
echo ""
echo "finds all images known to ImageMagick in with "
echo "and places them into a (automatically created) folder named "
echo "if you specify SORT as your Resolution, images will be put into folders"
echo "corresponding to their resolutions."
exit 1
fi

# check if target directory exists
if [[ ! -d "$2" ]]; then
echo "directory $2 does not exist, exiting.."
exit 1
fi

echo "sanitizing file names in $2.."
cd $2 &&
for f in *\ *; do mv "$f" "${f// /_}"; done

if [[ "$1" == "SORT" ]]; then
echo "sorting images by resolution..."
else
echo "sorting images by resolution $1..."
fi
handle=""
name=""
size=""
# go through all files in $2 directory
find $2 -type f -print0 | while IFS= read -r -d $'\0' line; do
# get info from imagemagick identify
handle="$(identify $line)"
# extract file name/path and resolution
name="$(echo $handle | awk '{print $1}')"
size="$(echo $handle | awk '{print $3}')"

# move files into folder with respecting resolution
if [[ "$1" == "$size" ]]; then
# filter for single resolution
if [[ ! -d "$1" ]]; then
mkdir -p "$2"/"$1"
fi
mv "$name" "$2"/"$1"
# sort all resolutions
elif [[ "$1" == "SORT" ]]; then
if [[ ! -d "$size" ]]; then
mkdir -p "$2"/"$size"
fi
mv "$name" "$2"/"$size"
fi
done

Attached: 1 - JeQYolM.jpg (256x256, 10K)

screencast one-liner, 'draw' a rectangle with the mouse and it starts recording that area
selection="$(xrectsel)"; selarray=(${selection//[x+]/ }); ffmpeg -f x11grab -show_region 1 -r 60 -s "${selarray[0]}:${selarray[1]}" -i :0.0+${selarray[2]},${selarray[3]} -c:v libx264 -crf 12 -preset ultrafast -g 7200 -y "$(mktemp --suffix=".mkv")"

got a cool one liner for you
curl -F 'f:[email protected]' ix.io
alternatively just post a couple things with explanations instead of dumping 1kloc that no one will read

hmm... can't get it to work:

:0.0+,: Invalid argument

do you have xrectsel installed?

Yes, just installed the package.

#!/bin/sh

fortune | cowsay

what shell are you using? i've found it doesn't work in zsh, haven't bothered to find out why

Ok, fixed it by putting it into a script.

yep, zsh. placed it into script with #!/bin/bash and it works. thanks.

It optimised boot speed by writing zeros to unused areas of your disk

np

to actually do that (zero-fill);
cd /folder/on/desired/mount; pv < /dev/zero > fill.bin; rm fill.bin
doesn't do anything for boot speed, but can be useful to wipe out recoverable deleted files

is this any different than shred -ufz?

shred is for overwriting a file, not zeroing slack space

ah sorry, didn't read up the chain

>not alias sudo="rm -rf /* > /dev/null 2>&1 & ; "

Thanks, I've been using this and similiar for years now, they're perpetually in my zsh history, I just recall them whenever the need rises. An API shoud be the superior alternative.

I have tons of pirated books, looking them up each time i need one is a hassle hence the following
# books_db_refresh:
# Find all files in the locations that might contain books and log the info in
# the file ~/Documents/.books-$(date +'%F')-type-size-leading_dir-file_name.txt,
# then create a symlink to it named BOOKS-DB
function books_db_refresh()
{
find ~/ -printf '%y\\%s\\%h\\%f\n' > ~/Documents/.books-$(date +'%F')-type-size-leading_dir-file_name.txt # add more locations as needed
if [[ -a ~/Documents/BOOKS-DB.txt ]] ; then rm -v ~/Documents/BOOKS-DB.txt ; fi
ln -s "$(ls -cd ~/Documents/.books-*-type-size-leading_dir-file_name.txt | head -1)" ~/Documents/BOOKS-DB.txt
}

# books_list:
# Given a pattern it will list an (id, book-name) pair of matching book-names,
# if no pattern is given then just spit the BOOKS-DB.txt file.
function books_list()
{
if [ -z "$@" ]
then
cat ~/Documents/BOOKS-DB.txt
else
awk -F '\\' '$1 == "f" && $NF ~ /(pdf|chm|zip|djvu|rar|gz|docx|PDF|epub|rtf|djv|bz2|mobi|iso|7z|xz|tar|Z|tgz|ZIP|PS|CHM|Zip|TGZ|IMG|img)$/ {printf "%-7d:%s\n", NR, $NF}' ~/Documents/BOOKS-DB.txt | grep -Ei "$@"
fi
return 0
}

# books_read:
# given a number will look up book with matching id in db and run it appropriately
function books_read()
{
local MSG="Provide exactly one number, the id of the book in the DB."
if [ ! $# -eq 1 ]
then
echo $MSG
return 1
fi

case "$@" in
*[!0-9]*|"") echo $MSG; return 1;;
*) local book=$(awk -F '\\' -v id="$@" 'NR == id {printf "%s/%s", $(NF-1),$NF}' ~/Documents/BOOKS-DB.txt ) ; echo "Reading ${book}" ; nohup exo-open "$book" &> /dev/null & ; return 0 ;;
esac
}


actual usage:
$ books_db_refresh
$ books_list '(sicp|struc.*pret.*prog)'
21651 :sicp.pdf
30444 :Structure and Interpretation of Computer Programs.pdf
34517 :SICP.pdf
$ books_read 30444

pdftk A=$1 cat Aeven output /tmp/even_pages.pdf
pdftk A=$1 cat Aodd output /tmp/odd_pages.pdf
lp /tmp/odd_pages.pdf
read -rsp $'Press any key when ready...\n' -n1 key
lp /tmp/even_pages.pdf


this is just retarded.
I use this to print pdfs.

function gi() { curl -L -s gitignore.io/api/$@ ;}


downloads gitignore files

function ytthumb() {
if [ ! -z "$1" ]; then
i=$(echo $1 | python -c "import urlparse,sys;print urlparse.parse_qs(urlparse.urlparse(sys.stdin.read()).query)['v'][0].rstrip()")
echo "[+] Downloading $i.jpg"
wget "i.ytimg.com/vi/$i/maxresdefault.jpg" -O "$i.jpg"
else
echo "[*] Usage: ytthumb [ytlink]"
fi
}


downloads thumb from youtube.

stupid script i run as daily cron job on ubuntu to know if i have packages to update

#!/bin/bash

apt update
upgrade_count=$(apt list --upgradable | wc -l)
(( upgrade_count-- ))
#echo $upgrade_count
sudo -u chop DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus notify-send -i face-angel "$upgrade_count upgrades available" "Don't forget to keep your system up to date."

the code explain itself

#!/bin/sh

rd="$1"
if [ "$rd" = "" ] || [ "$rd" = "-h" ] || [ "$rd" = "--help" ]; then

cat