You are not logged in.

#851 2010-02-09 08:16:09

mikesd
Member
From: Australia
Registered: 2008-02-01
Posts: 788
Website

Re: Post your handy self made command line utilities

man wrapper that allows you to view rfcs if you have the rfc package installed. The sed removes form feeds from the text files.

usage: man rfc822

Note: rfc is a space hog.

man() {
    local RFC=/usr/share/doc/rfc/txt/$1.txt
    if [ -r $RFC ]
    then
        cat $RFC | sed 's/\f//' | less
    else
        /usr/bin/man $@
    fi
}

Offline

#852 2010-02-09 20:06:57

brisbin33
Member
From: boston, ma
Registered: 2008-07-24
Posts: 1,796
Website

Re: Post your handy self made command line utilities

scrapes the mirror status webpage for your uncommented mirrors and pretty-prints results:

script:

#!/bin/bash
#
# pbrisbin 2009
#
###

tmp='/tmp/mirrors'
URL='https://users.archlinux.de/~gerbra/mirrorcheck.html'

get_active_mirrors() { awk '/^Server = .*/ {print $3}' /etc/pacman.d/mirrorlist | cut -d '/' -f 3; }

# download mirror status page
lynx -dump "$URL" | grep -A 1000 'CAPTION: All mirrors' > "$tmp"

# no data
if [ ! -s "$tmp" ]; then
  echo 'error getting mirrors status'

  [ -e "$tmp" ] && rm "$tmp"
  exit 1
fi

# header row
echo 'Mirror                    Last sync data'

# lines scraped from page
for mirror in $(get_active_mirrors); do
  (echo -n $mirror; grep -A 1 "^\ \ \ \[[0-9]*\]$mirror" "$tmp"  | tail -1) |\
  awk '{ if ($3) printf "%-25s %3s %3s %2s %8s %3s %4s %3s %7s %5s\n",
                           $1, $3, $4, $5, $6, $7, $8, $9, $10, $11 }'

done

# cleanup
rm "$tmp"

output:

//blue/0/~/ mirrorcheck
Mirror                    Last sync data
locke.suu.edu             Tue Feb 09 15:01:14 UTC 2010   0 day(s), 05:58
mirrors.xmission.com      Tue Feb 09 07:01:06 UTC 2010   0 day(s), 13:58
mirrors.xmission.com      Tue Feb 09 07:01:06 UTC 2010   0 day(s), 13:58
mirror.rit.edu            Tue Feb 09 05:01:06 UTC 2010   0 day(s), 15:58
mirror.rit.edu            Tue Feb 09 05:01:06 UTC 2010   0 day(s), 15:58
schlunix.org              Tue Feb 09 07:01:06 UTC 2010   0 day(s), 13:58
archlinux.umflint.edu     Thu Jan 07 00:01:08 UTC 2010  33 day(s), 20:58
mirror.umoss.org          Tue Feb 09 05:01:06 UTC 2010   0 day(s), 15:58

EDIT: first improvement, thanks!

Last edited by brisbin33 (2010-02-09 21:13:06)

Offline

#853 2010-02-09 20:49:23

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

Looks good but:

get_active_mirrors() { grep -v '^$\|^#' /etc/pacman.d/mirrorlist | awk '{print $3}' | awk -F '/' '{print $3}'; }

could be

get_active_mirrors() { awk -F '/' '/^Server = .*/ {print $3}' /etc/pacman.d/mirrorlist; }

smile

The scraping code looks interesting...but I haven't time to go through it in detail, yet. Looks like it could be applied to other pages, though.

(edited - forgot the file)

Last edited by skanky (2010-02-09 20:52:06)


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#854 2010-02-10 05:36:12

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: Post your handy self made command line utilities

brisbin33 wrote:

scrapes the mirror status webpage for your uncommented mirrors and pretty-prints results:
... ...

There's this short secret ...

curl -s 'https://www.archlinux.de/?page=MirrorStatusReflector'

mad

Edit: I think this is about as quick as yours ...

re=$(sed '/^ *Server *= *\([^\$]*\)\$repo.*$/!d;s//\1/' /etc/pacman.d/mirrorlist | tr '\n' '|' | sed 's/|$//')
grep -E "$re" <(curl -s 'https://www.archlinux.de/?page=MirrorStatusReflector')

There apparently is much, much duplicated work in the filtering (grep), but no big deal for such a small input tongue

Last edited by lolilolicon (2010-02-10 06:11:21)


This silver ladybug at line 28...

Offline

#855 2010-02-10 15:57:58

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

Okay, I make no claims that this is the best way to do this in awk, but I wanted to do it as an exercise. This is the mirror status scrape written just using awk & lynx:

#!/bin/bash
ARC="i686"
URL="https://users.archlinux.de/~gerbra/mirrorcheck.html"

lynx -dump $URL | gawk '# Mirror Status lookup

BEGIN   {
            FS = "/"
            while ((getline < "/etc/pacman.d/mirrorlist") > 0) {
                if ($0 ~ /^ *Server.*/) {
                    mirror[$3]=1
                }
            }
            FS = " "
            getDetails = 0
        }

/CAPTION: All/,/^ *Contact/ {
            if ($0 ~ /\[[[:digit:]]+\]/) {
                sub("\\[[[:digit:]]+\\]", "", $0)
                server = $1
                if (server in mirror) {
                    printf("%-25s--- \n", server)
                    getDetails = 1
                }
                else
                {
                    getDetails = 0
                }
            }
            else {
                if (getDetails) {
                    if ($1 ~ /.*'"$ARC"'.*/) {
                        printf ( "%-25s %3s %2s %8s %3s %4s %3s %7s\n",
                                    $1, $3, $4, $5, $6, $7, $8, $10)
                    }
                }
            }
        }'  -

It prints a line for each repository for i686. To use x86_64 just change the value of ARC to that.


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#856 2010-02-10 18:47:27

brisbin33
Member
From: boston, ma
Registered: 2008-07-24
Posts: 1,796
Website

Re: Post your handy self made command line utilities

/me steals lolilolicon's method big_smile.

Offline

#857 2010-02-10 21:24:47

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

Just for the hell of it, here's that method in (g)awk. smile
Again, there might be a better way of doing it in awk alone.

#!/bin/bash

URL="https://www.archlinux.de/?page=MirrorStatusReflector"

curl -s $URL | gawk '# Mirror Status lookup
BEGIN { while ((getline < "/etc/pacman.d/mirrorlist") > 0) {
          if ($0 ~ /^[^#]/) {
             sub("\\$repo.*", "", $3)
             mirror[$3] = 1
          }
        }
      }
      { if ($3 in mirror) print }' -

"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#858 2010-02-11 03:33:09

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

lfm2m3u: Scan a Last.FM playlist and generate an m3u file from it. I made this to help my friend and I share things a little easier.

It needs bash 4 and the URI::Escape perl module.

Source on GitHub

daenyth@Muspelheimr Music $ lfm2m3u.bash 
Please enter the URL of a Last.FM playlist to scan

daenyth@Muspelheimr Music $ lfm2m3u.bash http://www.last.fm/user/Cemetary_walk/library/playlists/3jl8j_dayjam | head
# Umphrey's McGee//Divisions
# Spin Doctors//Spanish Castle Magic
State Radio/Wicker Plane/01 Wicker Plane.mp3
State Radio/Year of the Crow/11 Wicker Plane.mp3
Railroad Earth/The Good Life/02 Bread and Water.mp3
# State Radio//Held Up By The Wires
Gov't Mule/By A Thread/09 Inside Outside Woman Blues #3.mp3
Pete Francis/Good to Finally Know/05 Air.mp3
# The Derek Trucks Band//Sahib Teri Bandi/Maki Madni
Tea Leaf Green/Rock 'n' Roll Band/07 Incandescent Devil.mp3

Last edited by Daenyth (2010-02-11 03:36:46)

Offline

#859 2010-02-13 10:55:03

TaylanUB
Member
Registered: 2009-09-16
Posts: 150

Re: Post your handy self made command line utilities

Don't want to litter up the page with lots of 'code' boxes, so i'm deviding the files with a big line saying 'EOF'.
All scripts have a comment section like "script_name: Short description here." after the shebang line.

#!/bin/sh
#
# google: Uses w3m and SSL-Scroogle.
#

spattern=$(echo "$*" | sed '{s/ /%20/g}')

[ "$spattern" ] &&
w3m https://ssl.scroogle.org/cgi-bin/nbbwssl.cgi?Gw="$spattern" ||
w3m https://ssl.scroogle.org/

########## EOF ##########

#!/bin/sh
#
# wiki: Uses w3m and English Wikipedia.
#

wikiterm=$(echo "$*" | sed '{s/ /_/g}')

[ "$wikiterm" ] &&
w3m "http://en.wikipedia.org/w/index.php?title=Special:Search&search=$wikiterm&go=Go" ||
w3m http://en.wikipedia.org/

########## EOF ##########

#!/bin/sh
#
# sys-backup.sh: Take system backups to tub-files.
#                Also refreshes /root/.paclists/* first.
#
# Var $f used for "**/tub-files".
#

set -e

echo

mkdir -p /root/.paclists
pacman -Q > /root/.paclists/all
pacman -Qg > /root/.paclists/groups
pacman -Qe > /root/.paclists/explicit
pacman -Qd > /root/.paclists/deps
pacman -Qet > /root/.paclists/top

if ! [ "$f" ]; then
    echo "ERROR: var \$f is unset"
    echo
    exit 1
fi

rm -f "$f"/system/backups-??????????.tar.bz2

tar -c --bzip2 2>/dev/null \
-f "$f"/system/backups-`date +%y%m%d%H%M`.tar.bz2 \
$(echo -n "\
    /boot/grub/menu.lst
    /etc/asound.state
    /etc/dhcpcd.conf
    /etc/fstab
    /etc/hosts
    /etc/inittab
    /etc/issue
    /etc/locale.gen
    /etc/mkinitcpio.conf
    /etc/mkinitcpio.d/kernel26.preset
    /etc/pacman.conf
    /etc/profile
    /etc/rc.conf
    /etc/rc.local
    /etc/rc.local.shutdown
    /etc/rc.multi
    /etc/rc.shutdown
    /etc/rc.single
    /etc/rc.sysinit
    /etc/resolv.conf
    /home/irc/
    /root/.Xdefaults
    /root/.bash_profile
    /root/.bashrc
    /root/.centerim/
    /root/.config/uzbl/config
    /root/.fehrc
    /root/.hwid/
    /root/.less
    /root/.local/share/uzbl/bookmarks
    /root/.mplayer/config
    /root/.paclists/
    /root/.profile
    /root/.ratpoisonrc
    /root/.scripts/
    /root/.shellrc
    /root/.vimrc
    /root/.w3m/config
    /root/.w3m/keymap
    /root/.xinitrc
    /root/.xorg.conf.d/
")

echo "DONE"
echo

########## EOF ##########

#!/bin/sh
#
# file-backup.sh: Backup tub-files to tub-home.
#
# Var $f used for "**/tub-files".
# Var $h used for "**/tub-home".
#

set -e

echo

if ! [ "$f" ]; then
    echo "ERROR: var \$f is unset"
    echo
    exit 1
fi
if ! [ "$h" ]; then
    echo "ERROR: var \$h is unset"
    echo
    exit 1
fi
if ! [ -e "$h" ]; then
    echo "ERROR: var \$h points to nonexistant file"
    echo
    exit 1
fi

rm -f "$h"/tub-files-??????????.tar.bz2
tar -c --bzip2 -f "$h"/tub-files-`date +%y%m%d%H%M`.tar.bz2 "$f" 2>/dev/null
echo "Last backup has been taken on:" > "$f"/.last_backup_date
date >> "$f"/.last_backup_date

echo "DONE"
echo

########## EOF ##########

#!/bin/sh
#
# lshwid.sh: Output specific parts from lshw.
#

lshw 2>/dev/null \
-disable ide \
-disable scsi \
-disable usb \
|\
grep \
-e " description:" \
-e " product:" \
-e " vendor:" \
|\
sed '{s/ *//g}'

########## EOF ##########

#!/bin/sh
#
# identpc.sh: Identify the current PC via hwid.
#
# Designed to run without PATH.
#

echo

echo "identifying PC ..."
echo

hwiddir="/root/.hwid"

if [ -z "`ls "$hwiddir" 2>/dev/null`" ]; then
    echo "ERROR: '$hwiddir' empty or nonexistant"
    echo "press enter to continue"
    read
    exit 1
fi

/root/.scripts/lshwid.sh > /tmp/hwid

for PC in `ls "$hwiddir"`; do
    if ! [ "`diff /tmp/hwid "$hwiddir"/"$PC"`" ]; then

        echo "MATCH; identified as: '$PC'"
        echo "running '/root/.scripts/setup/$PC' ..."
        echo

        if ! [ -e /root/.scripts/setup/"$PC" ]; then
            echo "ERROR: file is nonexistant"
            echo "press enter to continue"
            read
            exit 1
        fi
        if ! [ -x /root/.scripts/setup/"$PC" ]; then
            echo "ERROR: execute permission not granted"
            echo "press enter to continue"
            read
            exit 1
        fi

        /root/.scripts/setup/"$PC"
        exit

    fi
done

echo "FAILURE; no matching hwid entry in '$hwiddir'"
echo "press enter to continue"
read
exit 1

COMMENTARY:

My OS is on a flash stick to be used on any PC.
lshwid.sh carves out parts from lshw that will be the same each time you run it on a PC, not prone to small differences like plugging in a webcam, etc., and the resulting files are stored in a specific place.
identpc.sh matches all stored hwid files against a new lshwid.sh output and runs the appropriate setup script (which mounts local drives and changes xorg.conf, most importantly) if there's a match. It's called from /etc/rc.local so this happens automatically on boot.

'tub-files' is the directory holding all my important files that i carry with me, on the flash stick also holding my OS.
'tub-home' is my real home directory, holding backups, and more useless stuff like media files (music, films...). I wouldn't make it $HOME though as lots of software carelessly dumps files there, while any config files i care about go into **/tub-files/system/config/.

Dunno how good you find these, all are pretty straight forward i guess, but i'm proud of the PC identification, and using an `echo -n "<multiple_lines>"` inside a $() to get rid of excessive newline-backslashing FTW. big_smile


``Common sense is nothing more than a deposit of prejudices laid down by the mind before you reach eighteen.''
~ Albert Einstein

Offline

#860 2010-02-15 17:26:47

kick52
Member
Registered: 2009-10-19
Posts: 18

Re: Post your handy self made command line utilities

cstrikesounds(){ find /media/windows/Program\ Files/Steam/steamapps/kick52/counter-strike/ \( -iname \*.mp3 -o -iname \*.wav \) | shuf > /tmp/cstrikeplaylist
mplayer -playlist /tmp/cstrikeplaylist ; }

Play random sounds from Counter-Strike servers...

Hilarity ensues.

Offline

#861 2010-02-15 23:07:57

Yannick_LM
Member
Registered: 2008-12-22
Posts: 142

Re: Post your handy self made command line utilities

#!/usr/bin/env python

"""
Quick script to replace stuff in files

"""

import sys
import os
import re
import random
import logging
import fnmatch

from optparse import OptionParser

COLORS = {
    "bold"    :  "\033[1m"  ,
    "clear"   :  "\033[0m"  ,
    "red"     :  "\033[31m" ,
    "green"   :  "\033[32m" ,
    "blue"    :  "\033[34m" ,
}

FILTER_OUT = (
    ".git"    ,
    ".svn"    ,
    "*.py[co]",
    "*.[oa]"  ,
    "*~"
)

__usage__ = """
pyreplacer [options]  PATTERN REPL [files]

eg:
  pyreplacer 'toto' 'titi'
  pyreplacer '(.*)toto([0-9]{0,3})' '\\1titi\\2'

Files matching %s are discarded.
""" % (str(FILTER_OUT))

LOGGER = logging.getLogger("pyreplacer")

def recurse_file(opts, directory, action):
    """
    Recusively go do the subdirectories of the directory,
    calling the action on each file

    """
    for f in os.listdir(directory):
        if opts.get("no_hidden") and f.startswith("."):
            LOGGER.info("filter hidden  : %s/%s", directory, f)
            continue
        filter_out = False
        if not opts.get("no_filter"):
            for fo in FILTER_OUT:
                if fnmatch.fnmatch(f, fo):
                    LOGGER.info("filter %s: %s/%s", fo, directory, f)
                    filter_out = True
                    break
        if filter_out:
            continue
        f = os.path.join(directory, f)
        if os.path.isdir(f):
            recurse_file(opts, f, action)
        if os.path.isfile(f):
            action(f)


def replace_in_file(opts, in_file, regexp, repl):
    """
    Perfoms re.sub(regexp, repl, line) for each line in
    in_file
    """
    in_fd = open(in_file, "r")
    in_lines = in_fd.readlines()
    in_fd.close()

    out_lines = in_lines[:]
    out_lines = [re.sub(regexp, repl, l) for l in in_lines]

    diff = False

    # See if there's a diff first:
    for (in_line, out_line) in zip(in_lines, out_lines):
        if in_line != out_line:
            diff = True

    if not diff:
        return

    if not opts.get("quiet"):
        print COLORS["bold"] + COLORS["blue"] + "patching: " + in_file + COLORS["clear"]
    if opts.get("go"):
        if opts.get("backup"):
            rand_int = random.randint(100,999)
            back_file = "%s-%i.back" % (in_file, rand_int)
            back_file_fd = open(back_file, "w")
            back_file_fd.writelines(in_lines)
            back_file_fd.close()
        out_fd = open(in_file, "w")
        out_fd.writelines(out_lines)
        out_fd.close()

    if opts.get("quiet"):
        return

    for (in_line, out_line) in zip(in_lines, out_lines):
        if in_line != out_line:
            in_line  = in_line.strip()
            out_line = out_line.strip()
            print COLORS["bold"] + COLORS["red"]   + "--" + in_line  + COLORS["clear"]
            print COLORS["bold"] + COLORS["green"] + "++" + out_line + COLORS["clear"]
            print


def main():
    """
    manages options when called from command line

    """
    option_parser = OptionParser(usage = __usage__)
    option_parser.add_option("--no-skip-hidden",
        action = "store_false", dest = "no_hidden",
        help = "Do not skip hidden files. Use this if you know what you are doing...")
    option_parser.add_option("--no-filter", action = "store_true", dest = "no_filter",
                             help = "Do not skip files that match the filter")
    option_parser.add_option("-d", "--debug",
        action = "store_true", dest = "debug",
        help = "Enable debug output")
    option_parser.add_option("--backup",
        action = "store_true", dest = "backup",
        help = "Create a backup for each file. This is the default")
    option_parser.add_option("--no-backup",
        action = "store_false", dest = "backup",
        help = "Do not create backups")
    option_parser.add_option("--go",
        action = "store_true", dest = "go",
        help = "Perform changes rather than just printing then")
    option_parser.add_option("--dry-run", "-n",
        action = "store_false", dest = "go",
        help = "Do not change anything. This is the default")
    option_parser.add_option("--color",
        action = "store_false", dest = "color",
        help = "Colorize output. This is the default")
    option_parser.add_option("--no-color",
        action = "store_false", dest = "color",
        help = "Do not colorize output")
    option_parser.add_option("--quiet", "-q",
        action = "store_true", dest = "quiet",
        help = "Do not produce any output")

    option_parser.set_defaults(
        no_hidden = True,
        backup    = True,
        go        = False,
        color     = True,
        debug     = False,
        quiet     = False)

    (opts_obj, args) = option_parser.parse_args()

    opts = vars(opts_obj)

    if not opts.get("color"):
        for k in COLORS.iterkeys():
            COLORS[k] = ""

    if opts.get("debug"):
        logging.basicConfig(level=logging.DEBUG)

    if len(args) < 2:
        print "Wrong number of arguments"
        print __usage__
        sys.exit(2)

    pattern = args[0]
    repl    = args[1]

    regexp = re.compile(pattern)

    def repl_action(f):
        return replace_in_file(opts, f, regexp, repl)

    if len(args) > 3:
        files = args[2:]
        for f in files:
            repl_action(f)
    else:
        recurse_file(opts, os.getcwd(), repl_action)



if __name__ == "__main__":
    main()

using logging may be a bit overkill here...

Offline

#862 2010-02-16 21:29:15

hamelg
Member
From: France
Registered: 2008-06-19
Posts: 129

Re: Post your handy self made command line utilities

pick a random argument

#!/bin/bash

[ $# -eq 0 ] && exit 1
[ $# -eq 1 ] && { echo $1 ; exit 1 ;}

n=0
RANDOM=$$

# Choose a random args
while [ $n -eq 0 ] ; do
    n=$[$RANDOM % $[$# + 1] ]
done

eval echo "\${$n}"

Using it to play a random short jingle when opening my kde session, like this :
timidity `randargs.sh ~/SOUNDS/MIDI/SHRT*`

Offline

#863 2010-02-16 21:53:03

brisbin33
Member
From: boston, ma
Registered: 2008-07-24
Posts: 1,796
Website

Re: Post your handy self made command line utilities

hamelg wrote:

pick a random argument

best way to phrase that ever.

also, could so something like this

#!/bin/bash

args=( "$@" )

echo "${args[$(($RANDOM % ${#args[@]}))]}"

Offline

#864 2010-02-18 13:31:26

Enk
Member
Registered: 2010-02-17
Posts: 7

Re: Post your handy self made command line utilities

I am used to using Guake terminal, and wanted the same hide/show feature using the default terminal in xfce4 so I wrote a little program that checks if the terminal is open (then it focuses it), or open a new terminal if none is open.

I haven't done any Linux-programming before, so if anyone see any improvements to this; yell out! big_smile

If anyone wonders I got this program ("oof Terminal") bound to CTRL+SHIFT+ENTER smile

Requires wmctrl.

oof.c (open-or-focus tongue ):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]) {
    if(argc != 2) {
        printf("%s: one operand please.\n", argv[0]);
        return 1;
    }
    
    char command[256];
    command[0] = '\0';
    strcat(command, "pgrep \0");
    strcat(command, argv[1]);
    
    FILE *fpipe = (FILE*)popen(command, "r");
    char line[256];
    
    int c = 0;
    while(fgets(line, sizeof(line), fpipe)) {
        // printf("%s", line);
        c++;
    }
    
    if(c < 1) {
        system(argv[1]);
    }
    else {
        char cmd[256];
        cmd[0] = '\0';
        strcat(cmd, "wmctrl -a \0");
        strcat(cmd, argv[1]);
        system(cmd);
    }

    pclose(fpipe);
    return 0;
}

Offline

#865 2010-02-18 15:08:26

raf_kig
Member
Registered: 2008-11-28
Posts: 143

Re: Post your handy self made command line utilities

Enk: Not really an improvement, but this just screams for using a bash script

#!/bin/bash
wmctrl -a ${1} || ${*}

Offline

#866 2010-02-18 16:36:32

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Post your handy self made command line utilities

The most highly convoluted random directory function ever:

rand(){ x=(${1:-$PWD}/*);x=$(file ${x[$(($RANDOM%${#x[@]}))]});[ ! "${x##*: dir*}" ]&&x=${x%%:*}&&echo ${x//\/\//\/}||rand; }

Dun dun dun...

Last edited by GraveyardPC (2010-02-18 16:36:52)

Offline

#867 2010-02-20 10:44:33

The_Baron
Member
Registered: 2009-01-10
Posts: 23

Re: Post your handy self made command line utilities

Determines if someone is an oldgit:

oldgitAge = 50 #start of oldgitness
age = input("Enter age: ")
while age >= oldgitAge:
    print "oldgitness" #infinite loop of oldgitness
else:
    print "He is an oldgit! there must be an error."

Last edited by The_Baron (2010-02-23 12:48:38)

Offline

#868 2010-02-21 00:13:32

xenofungus
Member
From: Spain
Registered: 2009-10-17
Posts: 63

Re: Post your handy self made command line utilities

a quick script to add feeds to newsbeuter from firefox

#!/bin/bash
url=$(echo $@ | sed -e 's|^feed|http|')
echo "$url"  >> "$HOME/.newsbeuter/urls"

Offline

#869 2010-02-21 13:48:53

supulton
Member
Registered: 2008-12-31
Posts: 58

Re: Post your handy self made command line utilities

for people who use when, the simple calendar program, and would like to have pop-ups with gxmessage, i created a script to do just that.

#!/bin/bash
 
# set date, create file
current="$(date -d '15 minutes' +%-l:%M%p)"
today=~/.when/today
when --past=0 --future=0 > $today
 
# display task only
reminders=`grep "$current"$ $today | awk '{print substr($0, index($0,$5)) }'`
espeak -v english-us "$reminders" &
 
# call gxmessage
when_remind() {
gxmessage -center -nofocus -borderless -geometry 400x200 -timeout 1800 "$reminders"
}
 
#[ "$reminders" ] && when_remind || gxmessage -center -timeout 5 -name Empty "No reminders."
[ "$reminders" ] && when_remind

format your appointments like so:

2010 feb 21, visit google, 2PM
2010 march 10, discover the meaning of life, 3PM

and add a line like this to your cron file:

*/ * * * * export DISPLAY=:0.0 && sh /path/to/when_remind.sh

now every five minutes it should check if you have upcoming appointments, and if you do, it will pop up with formatted output:

visit google, 2PM
discover the meaning of life, 3PM

link: http://github.com/supulton/gitstuff/blo … _remind.sh
updated; no longer in hour-only increments.

here's a helper script for when_reminder to add appointments without going into an editor
link: http://github.com/supulton/gitstuff/blo … ipts/whena

i also wrote an mpc pipemenu for openbox.
link: http://github.com/supulton/gitstuff/blo … s/mpcob.sh

Last edited by supulton (2010-03-02 04:44:08)

Offline

#870 2010-02-23 10:16:13

jhvid
Member
From: /dev/denmark
Registered: 2009-08-19
Posts: 52

Re: Post your handy self made command line utilities

Just a simple ruby script, that put files into trash.
(I've aliased rm to trash.rb in my .zshrc)

#!/usr/bin/ruby -w
# trash.rb
# a script for trashing files
#

require "fileutils"

randnumber  = rand(100)
file_names     = []
ARGV.each do |file|
  file_names << file
end

file_names.each do |fn|
  new_fn = "/home/jonas/.trash/#{File.basename(fn)}-#{randnumber}.trash"
  FileUtils.mv(fn, new_fn)
end

Last edited by jhvid (2010-03-24 11:11:21)


GCS d- s-:+ a12 C++++ U++++ L+++ P--- E--- W+++ N+ o K- w--- O? M-- V? PS PE
Y- PGP? t? 5? X? R tv b+++ DI+ D- G++ e++ h! !r !y

Please ignore me... I'm pretty weird...

Offline

#871 2010-02-23 10:45:06

dmz
Member
From: Sweden
Registered: 2008-08-27
Posts: 881
Website

Re: Post your handy self made command line utilities

This utility prints art like this:

[♥]▇▇▇▇▇▇▇▇[♥]
▇[♥]▇▇▇▇▇▇[♥]▇
▇▇[♥]▇▇▇▇[♥]▇▇
▇▇▇[♥]▇▇[♥]▇▇▇
▇▇▇▇[♥][♥]▇▇▇▇
▇▇▇[♥]▇▇[♥]▇▇▇
▇▇[♥]▇▇▇▇[♥]▇▇
▇[♥]▇▇▇▇▇▇[♥]▇

#!/usr/bin/perl 
# crossmake

use strict;
use warnings;
use encoding 'utf8';
use Getopt::Long;
use List::Util qw(shuffle);

our($color,$char,$space,$size);
GetOptions('color!'   =>  \$color,
           'char=s'   =>  \$char,
           'space=s'  =>  \$space,
           'size=i'   =>  \$size,
           'help'     =>  \&help,
          );

my $c   = "\033[0m";
my $c1  = "\033[32m";
my $c2  = "\033[31m";
my $c3  = "\033[34;1m";
my $c4  = "\033[31;1m";

my @chars = qw([♥] ♥ o O x X);
my @space = qw(▇ ▕ #);
@chars = shuffle(@chars);
@space = shuffle(@space);

my $token = $char  // $chars[0];
my $ws    = $space // $space[0];
my $count = $size  // 8;

for(my $i=0; $i<$count; ++$i) {
  if($i%2==0) {
    $c = $c1 unless(!$color);
  }
  else {
    $c = $c2 unless(!$color);
  }
  my $j = 2 * $count - $i * 2;
  print $c, $ws x $i, $token, $ws x $j, $token, $ws x $i, "\n";
}
for(my $i=$count; $i>0; --$i) {
  if($i%2==0) {
    $c = $c3 unless(!$color);
  }
  else {
    $c = $c4 unless(!$color);
  }
  my $j = 2 * $count - $i * 2;
  print $c, $ws x $i, $token, $ws x $j, $token, $ws x $i, "\n";
}

sub help {
  print << "HLEP";
  USAGE
    $0 [OPTIONS]
  OPTIONS
    --(no)color
    --char      char
    --space     " "
    --size      size of painting
HLEP
exit 0;
}

Offline

#872 2010-03-01 02:49:06

aeosynth
Member
From: California
Registered: 2010-02-06
Posts: 115
Website

Re: Post your handy self made command line utilities

I spent some time writing a ruby bookmarking app, but then today I realized that I could accomplish the core in one line of bash:

#!/bin/bash

ln -Ts "$PWD" ~/s/"`basename "$PWD"`"

Of course you need the ~/s (s for symlink) directory. Tab completion, bookmark "management", come for free!

Edit:
After some more time tinkering, this is what I've come up with:

#!/bin/bash

if [ $1 ]
  then name=$1
else
  name=`basename "$PWD"`
fi

ln -Ts "$PWD" ~/s/"$name" && echo bookmarked $PWD: $name

For even faster access, in my .bash_aliases file I've got the following:

v() { vim ~/s/"$1"; }

So I can type `v ba` and immediately start editing my .bash_aliases. Of course, adding `alias ba="vim ~/.bash_aliases"` would be even faster, but then you start getting cluttered with these really specific aliases.

Last edited by aeosynth (2010-03-01 05:26:24)

Offline

#873 2010-03-01 04:50:28

dmz
Member
From: Sweden
Registered: 2008-08-27
Posts: 881
Website

Re: Post your handy self made command line utilities

Crosscheck update. Preview:
cross.png

#!/usr/bin/perl 
# crossmake

use strict;
use warnings;
use encoding 'utf8';
use Getopt::Long;
use List::Util qw(shuffle);

our($color,$char,$space,$size);
GetOptions('color!'   =>  \$color,
           'char=s'   =>  \$char,
           'space=s'  =>  \$space,
           'size=i'   =>  \$size,
           'help'     =>  \&help,
          );

my @colors = ("\033[31m", "\033[31;1m", "\033[32m", "\033[32;1m", "\033[33m",
              "\033[33;1m", "\033[34m", "\033[34;1m", "\033[36m",
              );
my @chars = qw([♥] ♥ o O x X);
my @space = ('▇', '▕', '#');
@chars = shuffle(@chars);
@space = shuffle(@space);

my $token = $char  // $chars[0];
my $ws    = $space // $space[0];
my $count = $size  // 8;
my $c = "\033[0m";
for(my $i=0; $i<$count; ++$i) {
  if($i%2==0) {
    @colors = shuffle(@colors);
    $c = $colors[0] unless(!$color);
  }
  else {
    @colors = shuffle(@colors);
    $c = $colors[0] unless(!$color);
  }
  my $j = 2 * $count - $i * 2;
  print $c, $ws x $i, $token, $ws x $j, $token, $ws x $i, "\n";
}
for(my $i=$count; $i>0; --$i) {
  if($i%2==0) {
    @colors = shuffle(@colors);
    $c = $colors[0] unless(!$color);
  }
  else {
    @colors = shuffle(@colors);
    $c = $colors[0] unless(!$color);
  }
  my $j = 2 * $count - $i * 2;
  print $c, $ws x $i, $token, $ws x $j, $token, $ws x $i, "\n";
}

sub help {
  print << "HLEP";
  USAGE
    $0 [OPTIONS]
  OPTIONS
    --(no)color
    --char      char
    --space     " "
    --size      size of painting
HLEP
exit 0;
}

Offline

#874 2010-03-01 14:01:49

aeosynth
Member
From: California
Registered: 2010-02-06
Posts: 115
Website

Re: Post your handy self made command line utilities

Updated to allow bookmarking arbitrary filepaths:

#!/bin/sh

path=$PWD/$2
if [ $1 ]; then
  bm=$1
else
  bm=`basename "$PWD"`
fi

ln -Ts "$path" ~/j/"$bm" && echo bookmarked $path: $bm

Using `v() { vim ~/j/"$1"; }` turns off tab completion, so instead I'm using `alias j='cd ~/j'` to quickly 'jump' to my symlink folder. I also aliased v to vim, since that just seems obvious, so now if I want to edit my bash aliases, I type:
j<Enter>v ba

The core of this little program is pretty much done, although the accessory functions could be improved with programmable completion, to shave off the j<Enter> keystrokes.

Offline

#875 2010-03-01 22:08:03

jlcordeiro
Member
From: Portugal
Registered: 2009-05-23
Posts: 76

Re: Post your handy self made command line utilities

A very simple one, but this one saves me a lot of time every now and then. I use it to extract tvshows downloaded as multiple rar parts.

It just recursively searches for *.rar files and extracts them to the current folder.


#!/bin/bash

for i in test `find . -name '*.rar'`
do
    unrar e $i
done

Theres one problem with it that I know of, but I didnt feel the need to fix this so far. Im not sure how this will behave with tvshows packed as part01.rar, part02.rar ... partXY.rar instead of file.r00 file.r01 file.rar.

Last edited by jlcordeiro (2010-03-01 22:09:47)

Offline

Board footer

Powered by FluxBB