You are not logged in.

#3076 2017-11-04 21:28:23

Mladia
Member
Registered: 2016-04-30
Posts: 59

Re: Post your handy self made command line utilities

Reading the current marked word and google-ing it. I've assigned the script to a keyboard shortcut and can easly search something.


googwo

#!/bin/bash

word=$(xclip -out -selection primary)

echo $word | xclip -in -selection clipboard

url="https://www.google.de/search?q=$word"

xdg-open "$url" &

The variables are a little bit redundant and can be done in a one-liner, but it's easier for to read and copy stuff from it.

Offline

#3077 2017-11-04 22:20:07

dimich
Member
From: Kharkiv, Ukraine
Registered: 2009-11-03
Posts: 237

Re: Post your handy self made command line utilities

Mladia wrote:
xdg-open "$url" &

It's possible to replace shell process instead of creating new one:

exec xdg-open "$url"

Not so important but little bit more optimal.

Offline

#3078 2017-11-05 14:40:10

YesItsMe
Member
Registered: 2017-07-12
Posts: 37

Re: Post your handy self made command line utilities

I made a simple client for the twtxt micro-blogging system:
https://hub.darcs.net/dertuxmalwieder/twtxtc

Offline

#3079 2017-11-12 15:39:17

quequotion
Member
From: Oita, Japan
Registered: 2013-07-29
Posts: 813
Website

Re: Post your handy self made command line utilities

Execute a command after a desktop notification countdown:

#!/bin/bash
#usage: countdown "command -argument -argument" "number"
TIMER="${2}"
while [ "${TIMER}" -gt 0 ]; do
  [[ "${TIMER}" -eq "${2}" ]] && replace="$(notify-send -u critical -t 900 -i media-playback-pause -p -- ${TIMER})"
  [[ "${TIMER}" -lt "${2}" ]] && replace="$(notify-send -u critical -t 900 -i media-playback-pause -r ${replace} -p -- ${TIMER})"
  TIMER="$(($TIMER-1))"
  sleep 1
done
#echo "GO!"
command ${1}

You'll need a notification daemon that respects the timeout parameter as well as {print,replaces} id parameters. I use notify-osd-customizable; it's timeout support is partial and notifications tend to linger on or vanish early by some milliseconds. The resulting countdown has an almost human inaccuracy.

Another daemon might yield more precise countdowns.

Edit: "-u critical" might be necessary for notify-osd(-customizable).

Last edited by quequotion (2017-11-23 02:40:13)

Offline

#3080 2017-11-15 04:46:36

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

Updating Ambrevar's handy currency converter after Google changed their URLs.

#!/bin/sh
# from Ambrevar https://bbs.archlinux.org/viewtopic.php?pid=1568235#p1568235

if [ $# -ne 3 ] || [ "$1" = "-h" ]; then
	cat <<EOF
Usage: ${0##*/} VALUE IN-CURRENCY OUT-CURRENCY

Convert VALUE from IN-CURRENCY to OUT-CURRENCY.
CURRENCY is a 3-letters code like EUR, SEK, USD, etc.

EOF
	exit
fi
curl -sA "Mozilla/5.0" "https://finance.google.com/finance/converter?a=$1&from=$2&to=$3" | \
    awk -F '<|>' '/result/ {print substr($5,1,length($5)-6)}'

Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#3081 2017-11-18 21:04:55

Ambrevar
Member
Registered: 2011-08-14
Posts: 212
Website

Re: Post your handy self made command line utilities

Not using GNU units?

Offline

#3082 2017-11-18 21:17:33

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

Units is awesome for static conversions (pounds to kilos), but for currencies I found this approach much more accurate.


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#3083 2017-11-20 18:14:30

dimich
Member
From: Kharkiv, Ukraine
Registered: 2009-11-03
Posts: 237

Re: Post your handy self made command line utilities

Script for switching secondary monitor on/off. It's binded to a key in window manager.

#!/bin/sh

OUTPUT=VGA-0

STATE=$(xrandr | grep "^${OUTPUT}" | sed -n 's/.*\(connected\|disconnected\)[[:space:]]\+\(primary\)\?\([^(]\+\)(.*/\3/p')

if [ -n "${STATE}" ]; then
    MODE="--off"
else
    MODE="--mode 1280x1024 --pos 1920x176 --rotate normal"
fi

xrandr --output "${OUTPUT}" ${MODE}

Offline

#3084 2017-11-20 19:16:30

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,441
Website

Re: Post your handy self made command line utilities

No need to pipe through grep to sed, sed can use a line regex.  But in this case it looks like you are just checking whether or not there is a number before the parentheses, so there is no need for sed at all:

OUTPUT=VGA-0
MODE="--mode 1280x1024 --pos 1920x176"

xrandr | grep -q "^${OUTPUT}[ a-z]*[0-9]" && MODE="--off"
xrandr --output $OUTPUT $MODE

Last edited by Trilby (2017-11-21 02:23:04)


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3085 2017-11-21 02:18:56

dimich
Member
From: Kharkiv, Ukraine
Registered: 2009-11-03
Posts: 237

Re: Post your handy self made command line utilities

Trilby wrote:

No need to pipe through grep to sed, sed can use a line regex.

Thank you for reply.
Of course it can be optimized. It was just a quick&dirty solution.

Trilby wrote:

But in this case it looks like you are just checking whether or not there is a number before the parentheses, so there is no need for sed at all:

xrandr | grep "^${OUTPUT}[ a-z]*[0-9]"

Yes, that's better. Xrandr output is for humans and isn't strict. I don't know can it be different in other versions, localizations etc.

Offline

#3086 2017-11-26 03:28:08

Barkester
Member
Registered: 2017-07-01
Posts: 19

Re: Post your handy self made command line utilities

Here's some more NOOB stuff for NOOBs.

Enhanced and better organized my notes. Made a new Ruby branch. Tried GIT, but its just way more than I need. Nice stack of aliases that tie in with my scripts nicely and make it all easy.
https://hastebin.com/hokuwadupu

Some are pretty self-explanatory like bashc for bash shortcuts regex for a cheatsheet, and clit for CLI text which just bundles all my notes for grepping when I'm groping. rit is it's Ruby counterpart with the same function. Clitud hoovers up the both of them along with study materials and system backup and reinstall info. Any changed "rc" files will be there too for the pasting. uunrar is used quite often.

I'll also thow up a copy of the recursive renamer thats from way back. Wish i could remember who posted it. Its in the first couple years of this post somewhere. I like it better than the later ones. Call it A2a this time.
https://hastebin.com/abakonigar

Another handy one is from my Ruby studies. Just handy. After making a stack of links as I often do, it verifies them all. No more one by one. I call it badlink here as thats all it prints. Its actually 'ruby where/badlink.rb', but when given an alias is nice.
https://hastebin.com/uhaloyabun

Find it helps my studies quite a bit. Don't Google much. Hope some of you find some use here.

Offline

#3087 2017-11-26 13:37:02

Rasi
Member
From: Germany
Registered: 2007-08-14
Posts: 1,914
Website

Re: Post your handy self made command line utilities

Made myself a script that lists all fonts containing a certain character. Script works with Hex codes and actual glyphs.

#!/usr/bin/env perl

use utf8;
use autodie;
use strict;
use warnings;
use autodie;
use Data::Printer;
use Encode qw/decode encode/;
use Font::FreeType;
use Getopt::Long;
use charnames ();
use Pod::Usage qw(pod2usage);

my @font_list = map { (split /:/, $_)[0] } `fc-list`;
@font_list = grep(/\.(ttf|odf)$/i, @font_list);

my ($opt_hex, $opt_help, $opt_char);

GetOptions ("x|hex=s"  => \$opt_hex,
            "c|char=s" => \$opt_char,
            "h|help"   => \$opt_help)
or die("Invalid option. Try --help\n");

sub print_fonts {
    my ($char, $hex, $char_name) = @_;
    $char                        = encode('UTF-8', $char);

    print STDERR "Glyph:   $char\n";
    print STDERR "Name:    $char_name\n";
    print STDERR "Hex:     $hex\n\n";

    foreach my $font (@font_list) {
        my $face = Font::FreeType->new->face($font);
        next unless $face->is_scalable;
        $face->set_char_size(0,0,0,0);

        my $glyph = $face->glyph_from_char_code(ord decode('UTF-8', $char));
        print "$font\n" if $glyph && $glyph->has_outline;
    }
}

sub get_vars_from_hex {
    my ($hex)     = @_;
    my $glyph     = chr(hex($hex));
    my $char_name = charnames::viacode($hex);

    return($glyph, $hex, $char_name);
}

sub get_vars_from_glyph {
    my ($glyph)   = @_;
    my $hex       = sprintf "%04x", ord decode('UTF-8', $glyph);
    my $char_name = charnames::viacode(hex($hex));

    return($glyph, $hex, $char_name);
}
    
sub main {
    my ($glyph, $hex, $char_name);

    if   (defined $opt_hex)  { ($glyph, $hex, $char_name) = get_vars_from_hex($opt_hex); }
    elsif(defined $opt_char) { ($glyph, $hex, $char_name) = get_vars_from_glyph($opt_char); $glyph = decode('UTF-8', $glyph); }
    else                     { pod2usage(1); die unless(defined $opt_help)}

    print_fonts($glyph, $hex, $char_name);
}

main();

__END__
=head1 NAME

findfonts.pl - find fonts providing certain characters

=head1 SYNOPSIS

findfonts.pl [command] [hex,glyph]

  Commands:
    -x, --hex         Search fonts by hex code.
    -c, --char        Search fonts by glyph.
    -h, --help        Show this help.

  Examples:
    findfonts.pl --hex 1f49f
    findfonts.pl --char ?

findfonts.pl version 0.1

=cut

=head1 LICENSE
Copyright (C) 2017  Rasmus Steinke <rasi@xinu.at>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
See LICENSE for the full license text.
=cut

In action:
https://fb.53280.de/F2U9P/

Last edited by Rasi (2017-11-26 13:39:26)


He hoped and prayed that there wasn't an afterlife. Then he realized there was a contradiction involved here and merely hoped that there wasn't an afterlife.

Douglas Adams

Offline

#3088 2017-11-30 06:29:31

Docbroke
Member
From: India
Registered: 2015-06-13
Posts: 1,433

Re: Post your handy self made command line utilities

Capture screenshot (mouse selected area) using import command from imagemagick

#!/bin/bash

FILE=/tmp/image.jpg
COUNT=0
while [ -f $FILE ]; do
    FILE=/tmp/image$COUNT.jpg
    COUNT=$(( $COUNT + 1 ))
done

import $FILE
notify-send -u normal "Image copied to $FILE"

similarly capture full-screen


#!/bin/bash

FILE=/tmp/image-full.jpg
COUNT=0

while [ -f $FILE ]; do
    FILE=/tmp/image-full$COUNT.jpg
    COUNT=$(( $COUNT + 1 ))
done

import -window root $FILE
notify-send -u normal "Image copied to $FILE"

Offline

#3089 2017-11-30 15:52:06

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,390

Re: Post your handy self made command line utilities

Not only a portion of screen, if you single click, you'll get the focused window.


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#3090 2017-11-30 19:15:26

dmerej
Member
From: Paris
Registered: 2016-04-09
Posts: 101
Website

Re: Post your handy self made command line utilities

I prefer using scrot tongue

Last edited by dmerej (2017-11-30 19:15:48)


Responsible Coder, Python Fan, Rust enthusiast

Offline

#3091 2017-12-01 18:13:53

browncoatjd
Member
From: Michigan
Registered: 2010-10-31
Posts: 2

Re: Post your handy self made command line utilities

A backup script. I was looking for an automated way to backup the documents on my windows laptop that would give me incremental backups, reduce storage overhead, and store them in a way where files would be easily recoverable. I ended up using a headless linux server 1.5L in size for the task. This Rsync script allows it to act like a 'time machine', creating a full backup on it's first run; then copying only the files that changed and using hard-links to fill the rest of the most recent backup directory to give me an easily retrievable full backup.

#!/bin/bash

# Windows Computer
HOST=Windows-Computer-Name
WRKGRP=WORKGROUP
SHARE="windows-share-name"
USRNM="windows-username"
PASSWD="windows-password"

# Config
EXCLUDE="/home/username/.rsync/exclude_backup-windows-computer"
LOGFILE="/home/username/.logs/backup-$HOST.log" 
LOCKFILE="/home/username/.scripts/backup-$HOST.lock"
MAXAGE="512" #number of old backups to keep

DATE=`date "+%Y-%m-%d-%H%M%S"`
SOURCE="/mnt/$HOST/" #don't forget the trailing slash!
DEST="/srv/bak/hourly/$HOST/$USRNM" #Folder the backups go in

# Create a lockfile for the script
if [ ! -e $LOCKFILE ]; then
	trap "rm -f $LOCKFILE; exit" INT TERM EXIT
	touch $LOCKFILE

# Check if $HOST is available
ping -c 3 $HOST &>/dev/null
if [ ! $? -ne 0 ] ; then

	echo "Found $HOST, mounting file systems..." > $LOGFILE

	# Check if mountpoint exists and if not then create it
	if [ ! -d "$SOURCE" ]; then
		# Can't Find Directory So Create It
		mkdir "$SOURCE"
	fi

	if [ -d "$SOURCE" ]; then
		mount -t cifs //$HOST/$SHARE $SOURCE -o user=$USRNM,password=$PASSWD,workgroup=$WRKGRP &&

		# Desktop notifier on laptop (creates blank file in Desktop folder)
		touch "$SOURCE"Desktop/backupinprogress
		sleep 2

		# Count number of backups and delete the oldest
		COUNT=`find $DEST-* -type d -prune | wc -l`
		OLDEST=`find $DEST-* -type d -prune | head -n 1` #this only works if directories have YYYYMMDD format
		if [[ $COUNT -gt $MAXAGE ]] ; then
		rm -rf $OLDEST
		fi

		# The backup process
		if [ -d  $DEST-recent ]; then
			rsync -avhi --delete --stats --exclude-from $EXCLUDE --link-dest=$DEST-recent $SOURCE $DEST-$DATE > $LOGFILE
			if [ "$(ls -A $DEST-$DATE)" ]; then
				rm -f $DEST-recent
				ln -s $DEST-$DATE $DEST-recent
			else
				echo "ERROR...$DEST-$DATE is Empty" >> $LOGFILE
			fi
		else
			rsync -avhi --delete --stats --exclude-from $EXCLUDE $SOURCE $DEST-$DATE > $LOGFILE
			ln -s $DEST-$DATE $DEST-recent
		fi
		touch $DEST-$DATE
		cp $LOGFILE $DEST-$DATE/rsync.log

		#Remove the notifier after the backup completes
		rm "$SOURCE"Desktop/backupinprogress

		#Unmount the share
		if [ -d "$SOURCE" ]; then
			umount $SOURCE
		fi

		#Remove the mountpoint
		if [ ! -d "$SOURCE" ]; then
			echo "No unused mount point for $SHARE" >> $LOGFILE
		else
			echo "Found Empty Mount Point: $SOURCE" >> $LOGFILE
			echo "Removing..." >> $LOGFILE
			rmdir "$SOURCE"
		fi
	fi
else
	echo "$DATE Could not find $HOST" >> $LOGFILE
fi

# Remove lockfile
	rm $LOCKFILE
	trap - INT TERM EXIT
else
	echo "script is already running" >> $LOGFILE
fi

If it helps, here are the contents of my exclude file to avoid some of the hidden windows system directories

/AppData/Local/
/Application Data/
/AppData/LocalLow/
/AppData/Roaming/
/Cookies/
/Desktop/backupinprogress
/Documents/My Music/
/Documents/My Pictures/
/Documents/My Videos/
/IntelGraphicsProfiles/
/Local Settings/
/My Documents/
/NetHood/
/PrintHood/
/Recent/
/SendTo/
/Start Menu/
/Templates/
NTUSER*
ntuser*

Offline

#3092 2017-12-16 07:43:07

Roken
Member
From: South Wales, UK
Registered: 2012-01-16
Posts: 1,251

Re: Post your handy self made command line utilities

Inspired by a support thread, I put this together to monitor temps of all drives connected. Requires hddtemp to be installed.

It also picks up my printer, which has an SD Card reader, though I get no info since it's not SMART enabled.

#!/bin/bash

clear
while true; do 
	for DRIVE in $( ls /dev | grep sd ); do 
		LEN=$(printf "%s" "$DRIVE" | wc -m)
		if [ $LEN = 3 ]; then 
			sudo hddtemp /dev/"$DRIVE"
		fi
	done
	sleep 1
	tput cup 0,0
done

Ryzen 5900X 12 core/24 thread - RTX 3090 FE 24 Gb, Asus Prime B450 Plus, 32Gb Corsair DDR4, Cooler Master N300 chassis, 5 HD (1 NvME PCI, 4SSD) + 1 x optical.
Linux user #545703

Offline

#3093 2017-12-16 07:56:21

V1del
Forum Moderator
Registered: 2012-10-16
Posts: 21,410

Re: Post your handy self made command line utilities

Don't parse ls! /dev/sd* will give you the same result (with 200% less processes no less!)

Oh and if you want to skip the partition devices and only rely on the three letter extensions, using /dev/sd? will do that as well.

Last edited by V1del (2017-12-16 08:08:53)

Offline

#3094 2017-12-16 11:43:10

dimich
Member
From: Kharkiv, Ukraine
Registered: 2009-11-03
Posts: 237

Re: Post your handy self made command line utilities

Roken wrote:

It also picks up my printer, which has an SD Card reader, though I get no info since it's not SMART enabled.

$ smartctl --scan

can show SMART-enabled devices.

Offline

#3095 2017-12-16 12:08:39

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,441
Website

Re: Post your handy self made command line utilities

Videl covered two points, but presented them as if they were one.  Using ls to generate a loop is bad practice, and passing ls to grep is just silly as ls could do that itself anyways.  So 1) ditch the grep, 2) ditch the ls, now 3) ditch all that printf | wc nonsense as ${#DRIVE} will give you the same result.  Now if you wanted to get just the basename of the paths that would be returned, there are two solutons: 1) basename! or if you don't want to run that each time through the loop, 2:

for drive in $(find /dev/ -name 'sd*' -printf "%f\n"); do
   [ ${#drive} -eq 3 ] && sudo hddtemp /dev/$drive
done

But really there is no reason to work to trim /dev/ only to add it back, and no reason to even check the number of characters if you don't do anything with the longer device names anyways!:

for drive in /dev/sd?; do sudo hddtemp $drive; done

"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3096 2017-12-16 15:11:09

whatshisname
Member
Registered: 2010-04-24
Posts: 162

Re: Post your handy self made command line utilities

This is why I love this category in the forums.

Even when someone posts a useful script there's still something to be learned.

Nice sig, as well, Trilby. :-)

Offline

#3097 2017-12-16 16:02:30

V1del
Forum Moderator
Registered: 2012-10-16
Posts: 21,410

Re: Post your handy self made command line utilities

Well I didn't want to give too many hints tongue But yeah that's what I was going for.

Offline

#3098 2017-12-16 17:08:31

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,441
Website

Re: Post your handy self made command line utilities

Actually I just commit yet another well documented shell error.  Most commands (just confirmed that hddtemp fits this) can accept multiple targets, so even the for loop I posted is foolish:

hddtemp /dev/sd?

As for the signature, thanks.  While I do appreciate the great contributions the GNU has made to the open source world, I am genuinely concerned with both their dominance over the linux ecosystem, and an all-to-common assumption that their tools are the only tools, and another all-to-common requirement to use their tools with the potential to render linux as much of a walled garden as macOS currently is.

I've been tinkering with gnu-free systems: kernel + busybox + musl + llvm/clang.  I might call it WING/Linux: WING Is Not GNU smile

Or maybe DINGO/Linux: Dingo Is Not GNU, Obviously (and it might eat your baby).

Last edited by Trilby (2017-12-16 17:17:08)


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3099 2017-12-16 22:59:16

whatshisname
Member
Registered: 2010-04-24
Posts: 162

Re: Post your handy self made command line utilities

WING is good!  I like it!

I became a big fan of BusyBox while messing around with Tiny Core.

I'm also in favor of minimalist desktop environments.  I'd love to see someone build a DE along the lines of of XFCE which was underpinned by BusyBox.

Way beyond my expertise, though.

Last edited by whatshisname (2017-12-16 23:08:33)

Offline

#3100 2017-12-16 23:05:44

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,441
Website

Re: Post your handy self made command line utilities

I don't think there could be such a thing as a minimal DE.  That phrase is a bit of an oxymoron.  But in anycase, WMs/DEs really don't need to know anything about whether they are the same machine as coreutils or busybox, they don't really use either one in any way.  Most existing DEs would run fine on a busybox system (many of them do on busybox distros).


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

Board footer

Powered by FluxBB