You are not logged in.

#676 2009-11-23 09:03:53

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Post your handy self made command line utilities

I improved the mpd.db-to-playlist script a bit, it will now work as expected with missing tag fields, which was giving trouble if you had an album that was made up of songs from different directories without track fields (it would just use any field it last saw in that directory).

Offline

#677 2009-11-24 21:15:00

spookykid
Member
From: Portugal
Registered: 2006-07-23
Posts: 141

Re: Post your handy self made command line utilities

Hi all,
I use this little script to run games on Wine, replaces Compiz with metacity and then restores Compiz again. Can be easilly costumized to use other WM. Requires Fusion-Icon, WMs can be customized.

#!/bin/bash
#
# start.sh
# 15/07/2009
#
# Created by spookykid

#----------------------------------------------------------------------------------------------------------------------------------

# Applications locations

declare -rx compiz="/usr/bin/compiz"
declare -rx metacity="/usr/bin/metacity"
declare -rx fusionicon="/usr/bin/fusion-icon"

# Window manager string to look for

declare -rx compiz_name="active wm = compiz"
declare -rx metacity_name="active wm = metacity"

# Window manager command
declare -rx run_compiz="compiz --replace --sm-disable --ignore-desktop-hints ccp"
declare -rx run_metacity="metacity --replace"

# Application to run
declare -rx exec_to_run1="wine RegSetup.exe"
declare -rx exec_to_run2="wine AVP2.exe"

#----------------------------------------------------------------------------------------------------------------------------------

if test -z "$BASH" ; then
    echo
    echo "Please run this script with the BASH shell"
    echo
    exit 192
fi

if test ! -x "$compiz" ; then
    echo
    echo "The command $compiz is not available, please install Compiz Window Manager on your system - ABORTING!"
    echo
    exit 192
fi

if test ! -x "$metacity" ; then
    echo
    echo "The command $metacity is not available, please install Metacity Window Manager on your system - ABORTING!"
    echo
    exit 192
fi

if test ! -x "$fusionicon"; then
    echo
    echo "The command $fusionicon is not available, please install Fusion-Icon on your system - ABORTING!"
    echo
    exit 192
fi

application_start()
{
    echo "   Starting application: $exec_to_run1"
    $exec_to_run1
    echo "   The application $exec_to_run1 has ended."
    echo "   Starting application: $exec_to_run2"
    $exec_to_run2
    echo "   The application $exec_to_run2 has ended."
}

compiz_start()
{
    echo "   Starting Compiz Window Manager with the command: $run_compiz"
    $run_compiz &
}

metacity_start()
{
    echo "   Starting Metacity Window Manager with the command: $run_metacity"
    $run_metacity &
}

check_wm()
{
    running_wm=`cat ~/.config/compiz/fusion-icon | grep "active wm"`

    if test "$running_wm" = "$compiz_name"; then
        echo
        echo "Detected Compiz Window Manager running ..."
        echo
        metacity_start
        application_start
        compiz_start
        echo
    fi

    if test "$running_wm" = "$metacity_name"; then
        echo
        echo "Detected Metacity Window Manager running ..."
        echo
        application_start
        echo
    fi
}

check_wm

exit 0

There is no knowledge that is not power!

Offline

#678 2009-11-24 21:41:10

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

Re: Post your handy self made command line utilities

Why not launch them into another display with xinit?

Offline

#679 2009-11-26 23:44:50

tomd123
Developer
Registered: 2008-08-12
Posts: 565

Re: Post your handy self made command line utilities

#!/usr/bin/python

# pb&j.py
# author: Thomas Dziedzic
# description: downloads all recent text on pastebin.com

from HTMLParser import HTMLParser
import urllib

url = "http://www.pastebin.com/"
urldl = "http://pastebin.com/pastebin.php?dl="
path = "pb&j"

# retrieves html content
f = urllib.urlopen(url)
s = f.read()
f.close()

# parse html
links = []
class Parser(HTMLParser):
    encounteredRecentPosts = False
    linkcount = 0

    def handle_starttag(self, tag, attrs):
        if tag == "a" and self.encounteredRecentPosts and self.linkcount < 10:
            links.append(attrs[0][1][20:])
            self.linkcount += 1

    def handle_data(self, data):
        if data == "Recent Posts":
            self.encounteredRecentPosts = True

parser = Parser()
parser.feed(s)
parser.close()

# download pastebin files into folder
for link in links:
    f = urllib.urlopen("http://pastebin.com/pastebin.php?dl=" + link)
    s = f.read()
    f.close()
    f = open(path + '\\' + link, 'w')
    f.write(s)
    f.close()

Downloads all recent text on pastebin.com into separate files.
Enjoy! ^^

I was going to add threads, but didn't feel like spending more time on this.
Any enhancements are welcome! Don't forget to paste them here for everyone.

EDIT: make sure to change the path + '\\' + link if you're not using windows. Yes, I did write this on windows tongue.

Last edited by tomd123 (2009-11-26 23:46:25)

Offline

#680 2009-11-27 07:26:44

tomd123
Developer
Registered: 2008-08-12
Posts: 565

Re: Post your handy self made command line utilities

#!/usr/bin/python

# chandl.py
# author: Thomas Dziedzic
# description: downloads all pictures on a 4chan board

from HTMLParser import HTMLParser
import urllib
import sys
import os

url = 'http://www.4chan.org/'
board = 'wg'

if len(sys.argv) > 1:
    board = sys.argv[1]

path = os.path.join('4chan', board)
if not os.path.exists (path):
    os.makedirs(path)

# parse html for boards
boards = {}
f = urllib.urlopen(url)
s = f.read()
f.close()
class BoardParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        classTag = [pair for pair in attrs if pair[0] == 'class']
        if tag == 'a' and len(classTag) == 1 and classTag[0][1] == 'boardlink':
            hrefTag = [pair for pair in attrs if pair[0] == 'href']
            titleTag = [pair for pair in attrs if pair[0] == 'title']
            href = hrefTag[0][1]
            title = titleTag[0][1]
            if len(title) > 0:
                boards[href.split('/')[-2]] = (title, href)
try:
    parser = BoardParser()
    parser.feed(s)
    parser.close()
except:
    # stupid malformed tags
    pass

# retrieves html content
f = urllib.urlopen(boards[board][1])
s = f.read()
f.close()

# parse html for board numbers
count = 0
class Parser(HTMLParser):
    encouteredBurichan = False

    def handle_starttag(self, tag, attrs):
        global count
        if tag == "a" and self.encouteredBurichan == True:
            count += 1
        if tag == 'form':
            self.encouteredBurichan = False

    def handle_data(self, data):
        if data == "Burichan":
            self.encouteredBurichan = True

parser = Parser()
parser.feed(s)
parser.close()
print '%i pages' % count

# create a list with current pages in board
pages = ['imgboard.html']
for i in range(1, count + 1):
    pages.append(str(i) + '.html')

for page in pages:
    # retrieve html content
    link = boards[board][1].split('imgboard.html')[0] + page
    print link
    f = urllib.urlopen(link)
    s = f.read()
    f.close()
    class ImageParser(HTMLParser):
        skipNext = False #4chan includes 2 consecutive links to the same image.
        
        def handle_starttag(self, tag, attrs):
            if tag == "a" and not self.skipNext:
                link = attrs[0][1]
                filename = link.split('/')[-1]
                fileext = filename.split('.')[-1]
                if fileext == 'jpg' and not os.path.exists(os.path.join(path, filename)):
                    f = urllib.urlopen(link)
                    print link
                    s = f.read()
                    f.close()
                    f = open(os.path.join(path, filename), 'wb')
                    f.write(s)
                    f.close()
                self.skipNext = True
            else:
                self.skipNext = False

    parser = ImageParser()
    parser.feed(s)
    parser.close()

4chan image downloader. Downloads all the images in a channel. It only downloads what's needed. (no need to redownload it if you already have it).
Usage: ./chandl [channel]
default channel is wg. Channel could be anything, wg, w, etc. (yes, it should work on b and s).

This is mainly an advanced version of the pastebin downloader.  Still no threaded downloading. This was especially tricky because channels were under different servers.

As always, I'm always glad to accept improvements smile

Edit: Forgot to mention that if you don't know already, 4chan is nsfw. Therefore some pictures may be nsfw, depending on the channel you decide to download.

Last edited by tomd123 (2009-11-27 07:35:30)

Offline

#681 2009-11-27 15:58:15

Procyon
Member
Registered: 2008-05-07
Posts: 1,819

Re: Post your handy self made command line utilities

tomd123 wrote:

4chan image downloader.

Does that download all threads on a board?

I wrote something similar once for just 1 thread, it will keep going until the thread 404s while remembering where it left off each iteration. I also posted the rss reader before that opens all links in an rss looking for keywords (most boards have an rss page). You can edit that to open this script instead of just echo it and automatically download all threads of a kind with this script.

#! /bin/bash
#Futaba/4chan thread saver
#Usage ./2cts 'http://may.2chan.net/b/res/1234567890.html' ['17000000'] ['wait time']
#Optional arg two: what post number to start downloading images
#Optional arg three: seconds to wait between reloads (default is 300 seconds)
page="$1"
[ -z "$page" ] && exit 1
# ! [[ "$page" =~ ^http.*res.[0-9]*.html?$ ]] && echo malformed URL && exit 1
latestpost=${2:-0}
! [[ "$latestpost" =~ ^[0-9]*$ ]] && echo malformed latest post && exit 1
reloadtime=${3:-300}
! [[ "$reloadtime" =~ ^[0-9]*$ ]] && echo malformed reload time && exit 1

if [[ "$page" =~ 2chan ]]; then
    mode=futaba
else
    mode=4chan
fi
dirname="$HOME/.4chan/"$(basename "$page")
[ -d "$dirname" ] && echo -n "THREAD FOUND" && exit 0
echo -e "\n---Working directory: $dirname---\n"
mkdir -p "$dirname"
cd "$dirname"

while true; do
echo -n "$page : $$ : "
curtime=$(date '+%s')
! wget -q -O $curtime "$page" && echo "Error in getting page" && exit 0
if [ $mode = 4chan ]; then
#grep delform $curtime | grep POST | cut -d \" -f 8 > $curtime.img
#sed -n 's/.*href="#\([0-9]*\)".*href="\(http[^"]*\)".*/\1 \2/p' $curtime  >> $curtime.img
sed 's/ /\n/g' $curtime | grep -A1 -E '(No\.|href="http.*\/?\/src)' | grep -v $'^--$\nNo\.\n^target=' | uniq | sed -n '1{h;b};2{p;x;p;b};p' | sed '/javascript/s/^[^0-9]*\([0-9]*\)[^0-9]*$/No.\1/;s/href="//;s/"$//' | sed '/^No/h;/^http/{x;G;s/No\.//;s~\n~ ~;p}' | uniq | grep src | grep -v '^ ' >> $curtime.img
elif [ $mode = futaba ]; then
#does not get OP pic
#sed 's/ /\n/g' $curtime | grep -E '(No\.|href="http.*\/b\/src)' | uniq | sed 's/href="//;s/"$//' | sed '/^No/h;/^http/{x;G;s/No\.//;s~\n~ ~;p}' | uniq | grep src | grep -v '^ ' > $curtime.img
sed 's/ /\n/g' $curtime | grep -E '(No\.|href="http.*\/b\/src)' | uniq | sed -n '1{h;b};2{p;x;p;b};p' | sed 's/href="//;s/"$//' | sed '/^No/h;/^http/{x;G;s/No\.//;s~\n~ ~;p}' | uniq | grep src | grep -v '^ ' > $curtime.img
fi

while read post img; do
    ! [[ $post =~ ^[0-9]*$ ]] && echo malformed post number && exit 1
    [ $post -lt $latestpost ] && echo -n "." && continue
    [ $post -eq $latestpost ] && echo -n "-" && continue
#    img="$(wget -q -O - "$img" | sed 's/.*URL=\([^"]*\)".*/\1/')"
    ! [[ $img =~ ^http.*src.[0-9]*.*$ ]] && echo malformed image name && exit 1
    if [ $post -gt $latestpost ]; then
        sleep 4
        echo -n "X"
        wget -q "$img" &
        latestpost=$post
        continue
    fi
    echo Unknown error
done < $curtime.img

echo "D"
sleep $reloadtime

done

Offline

#682 2009-11-27 16:05:12

tomd123
Developer
Registered: 2008-08-12
Posts: 565

Re: Post your handy self made command line utilities

Procyon wrote:
tomd123 wrote:

4chan image downloader.

Does that download all threads on a board.

Downloads all images in a channel on all of its pages. You would get all images in /wg/ if you typed 'chandl wg'. That includes all images on the first, second, etc page. This script also checks if it already has the file it's about to download. If it does, it doesn't download it again.

Offline

#683 2009-11-27 17:02:36

jelly
Administrator
From: /dev/null
Registered: 2008-06-10
Posts: 714

Re: Post your handy self made command line utilities

Daenyth wrote:

Why not launch them into another display with xinit?

#!/bin/bash
args=$@
if [ $# == 1 ]; then
    game=$(whereis "$args" | awk '{ print $2 }')
    xauth add :1 . e35a4dd7ad107110869f6972fa832666
    xinit $game -- :1 -xf86config game.conf
else
    echo "give a valid argument"
fi

That's what i use the launch a game on one of my two monitors.
http://jelly.homelinux.com/blog/?p=22 for further information

Offline

#684 2009-11-27 17:07:09

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: Post your handy self made command line utilities

tomd123 wrote:

Downloads all recent text on pastebin.com into separate files.
Enjoy! ^^

I was going to add threads, but didn't feel like spending more time on this.
Any enhancements are welcome! Don't forget to paste them here for everyone.

EDIT: make sure to change the path + '\\' + link if you're not using windows. Yes, I did write this on windows tongue.

Gah, I hate you for this.

Scraping /wg = possible win.
Scraping /b = puts the b in FBI.

Also, works just fine on non-Windows without any changes. Nicely done.

Offline

#685 2009-11-27 17:30:07

tomd123
Developer
Registered: 2008-08-12
Posts: 565

Re: Post your handy self made command line utilities

falconindy wrote:
tomd123 wrote:

Downloads all recent text on pastebin.com into separate files.
Enjoy! ^^

I was going to add threads, but didn't feel like spending more time on this.
Any enhancements are welcome! Don't forget to paste them here for everyone.

EDIT: make sure to change the path + '\\' + link if you're not using windows. Yes, I did write this on windows tongue.

Gah, I hate you for this.

Scraping /wg = possible win.
Scraping /b = puts the b in FBI.

Also, works just fine on non-Windows without any changes. Nicely done.

epic misquote fail is epic ^^
Anyways, ty. Ya, I improved the 4chan scraper with an os independent way of managing folders, even though I wrote it on windows. The pastebin scraper is the one that has the windows specific locations.

Last edited by tomd123 (2009-11-27 17:32:09)

Offline

#686 2009-11-27 18:25:17

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

Re: Post your handy self made command line utilities

jelly wrote:
Daenyth wrote:

Why not launch them into another display with xinit?

#!/bin/bash
args=$@
if [ $# == 1 ]; then
    game=$(whereis "$args" | awk '{ print $2 }')
    xauth add :1 . e35a4dd7ad107110869f6972fa832666
    xinit $game -- :1 -xf86config game.conf
else
    echo "give a valid argument"
fi

That's what i use the launch a game on one of my two monitors.
http://jelly.homelinux.com/blog/?p=22 for further information

The xauth bit only needs to be done once. I know my launchers never need it. I also wouldn't restrict to one argument, as a game can have arguments you want to launch it with. game="$1"; shift; xinit $game "$@" -- :1

Offline

#687 2009-11-27 20:07:31

kljohann
Member
Registered: 2008-05-31
Posts: 19

Re: Post your handy self made command line utilities

The following locks my netbook after a certain amount of inactivity when I close the screen.
Uses sinac & xlockmore from the AUR.

crontab

*/1 * * * * ~/lock_on_inactivity.sh

~/lock_on_inactivity.sh

#!/bin/bash

export DISPLAY=:0
grep "closed" /proc/acpi/button/lid/LID/state 2>&1 >/dev/null
if [ $? -eq 0 ] && [ `sinac` -gt 50 ]; then
    instances=$(ps -A | grep xlock | wc -l)
    if [ $instances -eq 0 ]; then
            xlock
    fi
fi

(You will have to adjust the "/proc/acpi..."-part.)

Offline

#688 2009-11-27 20:34:48

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

Re: Post your handy self made command line utilities

Why put it in cron every minute? Wouldn't it make more sense to let ACPI trigger it?

Offline

#689 2009-11-27 21:50:18

steve___
Member
Registered: 2008-02-24
Posts: 452

Re: Post your handy self made command line utilities

How could one do this?

Offline

#690 2009-11-27 21:53:21

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

Re: Post your handy self made command line utilities

Offline

#691 2009-11-29 18:21:14

Hiato
Member
Registered: 2009-01-21
Posts: 76

Re: Post your handy self made command line utilities

I'm shocked that through my brief look at this thread (that is, page 1 and this one), something like this hasn't arisen:

#!/bin/sh
dt="$(date +%d)"
wrd=""

if [ "$(echo $dt | cut -c 1)" == "1" ]; then
    case $(echo $dt | cut -c 2) in
        0) wrd="tenth" ;;
        1) wrd="eleventh" ;;
                2) wrd="twelth" ;;
                3) wrd="thirteenth" ;;
                4) wrd="fourteenth" ;;
                5) wrd="fifteenth" ;;
                6) wrd="sixteenth" ;;
                7) wrd="seventeenth" ;;
                8) wrd="eighteenth" ;;
                9) wrd="nineteenth" ;;
    esac
else
    case $(echo $dt | cut -c 1) in
        2) wrd="twenty-" ;;
        3) wrd="thirty-" ;;
    esac

    case $dt in
        20) wrd="twentieth" ;;
        30) wrd="thirtieth" ;;
    esac

    case $(echo $dt | cut -c 2) in
        1) wrd=$wrd"first" ;;
        2) wrd=$wrd"second" ;;
        3) wrd=$wrd"third" ;;
        4) wrd=$wrd"fourth" ;;
        5) wrd=$wrd"fifth" ;;
           6) wrd=$wrd"sixth" ;;
            7) wrd=$wrd"seventh" ;;
               8) wrd=$wrd"eighth" ;;
            9) wrd=$wrd"ninth" ;;
    esac
fi;
echo $(fuzzyclock), $(fuzzyclock -f 3 | tr '[:upper:]' '[:lower:]'), $(date +%A | tr '[:upper:]' '[:lower:]') the $wrd of $(date +%B | tr '[:upper:]' '[:lower:]')

Unfortunately, the time bits depend on fuzzyclock, but hey. One of my first scripts, as an exercise in learning bash.  Now, the one I usually use, it manages arbitrarily many 'slots' for a copy buffer and can treat them as a filo stack, and integrates superbly with my ratpoison environment, though it can be used with anything if, for example, xte is available to simulate key-presses. Read the code to understand the usage:

#!/usr/bin/env python
import os
import sys

def flatten(n):
    t=''
    for q in n: t+=q
    return t

if sys.argv[1]=='i':
    t=open('/tmp/cpbuff','w')
    t.write('0\n\n'*(int(sys.argv[2])))
    t.close
else:
    t=open('/tmp/cpbuff','r')    
    f=t.readlines()
    t.close

    j,q,s,l=0,0,[],[]
    while q<len(f):
        j,q,t=int(f[q])+1,q+1,''
        l+=[max(j-1,0)]
        while j>0:
            j,q,t=j-1,q+1,t+f[q]
        s+=[t]

    if sys.argv[1]=='x':
                t=flatten(os.popen('xclip -o').readlines())
        if t[len(t)-1]!='\n':t+='\n'
        if sys.argv[2]=='x':
            for q in range(0,len(s)-1,+1):
                            s[q],l[q]=s[q+1],l[q+1]
            s[len(s)-1],l[len(s)-1]=t,t.count('\n')-1
        elif sys.argv[2] in map(lambda x: str(x), range(1,len(s)+1)):
            s[int(sys.argv[2])-1],l[int(sys.argv[2])-1]=t,t.count('\n')-1

    if sys.argv[1]=='z':
        if sys.argv[2]=='z':
            os.system('echo %s | xclip' %(s[len(s)-1]))
            for q in range(len(s)-1,0,-1): s[q],l[q]=s[q-1],l[q-1]
            s[0],l[0]='\n',0
        elif sys.argv[2] in map(lambda x: str(x), range(1,len(s)+1)):
            os.system('echo %s | xclip' %(s[int(sys.argv[2])-1]))
        #os.system('xte keydown Shift_L key Insert keyup Shift_L')
        os.system('ratpoison -c getsel')

    t=open('/tmp/cpbuff','w')
    for q in range(len(s)): t.write(str(l[q])+'\n'+s[q])
    t.close

Yep, my coding style aint optimal, but at least it's unique tongue

Last edited by Hiato (2009-11-29 18:35:53)

Offline

#692 2009-11-29 18:42:40

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

Re: Post your handy self made command line utilities

Pretty sure there's a perl module to do the first, or one that could easily be adapted.

Hmm, google gives these:
Lingua::EN::Numbers::Ordinate - Only prints out "3rd" "4th", so on, not words.
Lingua::ES::Numeros - Does this for Spanish, could be modified.
Lingua::EN::Inflect - Very featureful and does a lot more than just ordinal words.

Offline

#693 2009-11-29 23:32:54

Wintervenom
Member
Registered: 2008-08-20
Posts: 1,011

Re: Post your handy self made command line utilities

For those that use the MVPS host list for ad-blocking:

#!/bin/dash
wget -c -O /tmp/hosts.txt http://www.mvps.org/winhelp2002/hosts.txt
sed -i -e 's:127.0.0.1:0.0.0.0:g' -e "s:^.*localhost.$:127.0.0.1 localhost `hostname`:" /tmp/hosts.txt
cat /tmp/hosts.txt | tr -d "\r" > /etc/hosts
rm /tmp/hosts.txt

MPD actions, using dmenu:

#!/bin/bash
### MPD Actions ################
# Version 0.1 by Scott Garrett #
################################

# Path to music library.
mdir="$HOME/../Music/Library"

# Path to MPD playlists.  You must have write access to these.
playlists="$HOME/../Music/Playlists"

#Path to the XDG trash.
trash="$HOME/.local/share/Trash/files"

# Actions that will be displayed.
actions='[Add to Playlist]
[Move to Trash]
[Queue Playlist]
[Update Database]'

# Yes/No prompt actions.
yn='No
Yes'

# If MPC is not installed...
if ! mpc &> /dev/null; then
  # ...then complain to the user...
  echo OK | dmenu -p 'MPC must be installed.'
  # ...and exit with unsuccessful status.
  exit 1
fi

function isplaying() {
  # If MPD is not playing anything...
  if ! mpc | grep -qE 'playing|paused'; then
    # ...then complain to the user...
    echo OK | dmenu -p 'MPD is not playing anything.'
    # ...and exit with unsuccessful status.
    exit 1
  fi
}

# Grab the relative path of the playing song from MPC.
file=`mpc --format '%file%' | head -n1`

# The absolute path to the song.
fpath="$mdir/$file"

# Give user the action prompt.
action=`echo "$actions" | dmenu -p "$(mpc --format '%title%' | head -n1):"`

# Let's figure out what the user selected.
case "$action" in
  *'Add to'*)
    # Make sure the user has something playing, first.
    isplaying
    # Let the user choose one of the playlists in MPD's playlist directory.
    playlist=`ls "$playlists/"*.m3u | sed "s:$playlists/::g" | dmenu -p 'Add to playlist:'`
    # Did the user choose a playlist?
    if [[ "$playlist" ]]; then
      # If so, then let's append the song to that playlist.
      # I don't think we can sort and filter in-place with `sort`.
      # We'll do it the convoluted way, instead.

      # Append the relative path of the song to the playlist.
      echo "$file" >> "$playlists/$playlist"

      # Now, we'll `sort` everything into a temporary playlist.
      # The '-u' argument will remove duplicate entries.
      sort -u "$playlists/$playlist" > "/tmp/$playlist.new"

      # Dump this new playlist into the old one.
      # We could use `mv`, but the permissions would change.
      cat "/tmp/$playlist.new" > "$playlists/$playlist"

      # Finally, delete the temporary playlist.
      rm "/tmp/$playlist.new"

      # Yay, we're done.
      echo "Appended <<$file>> to <<$playlists/$playlist>>."
    fi
  ;;
  *'Trash'*)
    # Make sure the user has something playing, first.
    isplaying
    # Make sure the user really wants to do this.
    if [[ `echo "$yn" | dmenu -p 'Delete playing song?'` == 'Yes' ]]; then
      # They asked for it.
      # We'll be nice and move the song to the XDG trash instead of deleting it.
      # Then the user won't be screwed if he or she has a change of mind.

      # Remove the currently playing song from the master playlist.
      mpc del 0

      # Make an XDG trash directory, if it does not exist.
      mkdir -p "$trash"

      # Move the song to the trash.
      mv "$fpath" "$trash"

      # Done.
      echo "Moved <<$file>> to XDG trash."
    fi
  ;;
  *'Queue'*)
    # Let the user choose a playlist.
    playlist=`( echo '[Entire Library]'; ls "$playlists/"*.m3u ) | sed "s:$playlists/::g" | dmenu -p 'Queue playlist:'`

    # If the user chose something...
    if [ -n "$playlist" ]; then
      # ...then clear the current playlist...
      mpc clear
      # ...and load what the user selected.
      case "$playlist" in
        *'Entire Library'*)
          mpc ls | mpc add
        ;;
        *)
          mpc load "${playlist%%.*}"
        ;;
      esac
      mpc play
    fi
  ;;
  *'Update'*)
    mpc update
  ;;
esac

Offline

#694 2009-11-30 01:43:53

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

Re: Post your handy self made command line utilities

Not so much a "utility", but I add this to my crontab files to help me remember the order.

# +---------------- minute       (0 - 59)
# |  +------------- hour         (0 - 23)
# |  |  +---------- day of month (1 - 31)
# |  |  |  +------- month        (1 - 12)
# |  |  |  |  +---- day of week  (0 - 7)  (Sunday=0 or 7)
# |  |  |  |  |
# *  *  *  *  *  command

Offline

#695 2009-11-30 09:00:11

Gen2ly
Member
From: Sevierville, TN
Registered: 2009-03-06
Posts: 1,529
Website

Re: Post your handy self made command line utilities

Yeah, I do this too but I put mine at the bottom:

# |   |   |   |   |  user command
# |   |   |   |  weekday (0-6) (Sunday=0)
# |   |   |   month (1-12)
# |   |   day (0-31)
# |   hour (0-23)
# minute (0-59)

Setting Up a Scripting Environment | Proud donor to wikipedia - link

Offline

#696 2009-11-30 11:08:55

Gen2ly
Member
From: Sevierville, TN
Registered: 2009-03-06
Posts: 1,529
Website

Re: Post your handy self made command line utilities

Had to fix a bug in the aliases to 'cd' to a saved directory that I wrote about earlier:

alias cdo="pwd | sed 's/ /\\\ /g' > ~/.cdo"   # save current dir location
alias cdn="cd $(cat ~/.cdo)"                  # cd to saved dir location

Setting Up a Scripting Environment | Proud donor to wikipedia - link

Offline

#697 2009-11-30 14:24:49

presario
Member
From: Tashkent, Uzbekistan
Registered: 2008-12-07
Posts: 57
Website

Re: Post your handy self made command line utilities

Not really a utility but a trick that I often use when I'm too lazy to write a (bash) script:

a_very_very_long_and_complex_command #tag

After that I can retrieve the command by typing:

^R#tag

The point is about labeling commands for easy retrieval so that you don't have to recall parts of the command that uniquely identify it.

Last edited by presario (2009-11-30 16:13:41)


Running ArchLinux on Compaq Presario v2000

Offline

#698 2009-11-30 14:39:32

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

Re: Post your handy self made command line utilities

presario wrote:

Not really a utility but a trick that I often use when I'm too lazy to write a (bash) script:

That is neat. I would never of thought of that.

Offline

#699 2009-11-30 19:08:14

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

Re: Post your handy self made command line utilities

I'm not sure how many people will find this useful, but I wrote this to quickly execute common command sequences on my router. If you happen to console into a Cisco router using Minicom, give this a try:

router(){
    local op cmd line vo ret tmp="/tmp/rmc_"$(date +%s)".tmp"
    local bh=" key_enter, en, exit, key_enter, en, "
    local bf=" key_enter, en, exit "

    OPTIND=1
    while getopts CRWnv op; do
    case $op in
        C)    minicom; return $? ;;
        R)    cmd="reload, y, key_enter, " ;;
        W)    cmd=$cmd"config t, int d1, shut, sleep 10, no shut, sleep 10, exit, exit, " ;;
        n)    cmd=$cmd"clear ip nat trans *, " ;;
        v)    vo=1 ;;
    esac
    done; shift $(($OPTIND-1))

    if [ ! "$cmd" ] && [ ! "$1" ]; then
    echo -e \
    "Usage: router [Options] {command,command,...}"\
    "\nOptions:"\
    "\n  -C\t\tConsole into router using Minicom"\
    "\n  -R\t\tRestart router"\
    "\n    \t\t\"C\" and \"R\" ignore all commands/options!\n"\
    "\n  -W\t\tRefresh WAN IP address"\
    "\n  -n\t\tClear IP NAT translations"\
    "\n  -v\t\tVerbose output (list command script)\n"\
    "\nCommands:"\
    "\n  ! <command>\tExecute a shell command during RunScript"\
    "\n  sleep <sec>\tSleep for a number of seconds"\
    "\n  <command>\tRouter command (send <command>)"\
    "\n  key_enter\tCarriage return (send \\\r\\\n)\n"\
    "\nExamples:"\
    "\n  router -nv clear ip route *, ! ddclient, sleep 30"\
    "\n  router -v config t, int fa1, duplex, exit, exit"\
    "\n  router -R"
    return 1; fi

    cmd=$bh$cmd$([ "$1" ] && echo $@",")$bf; IFS=","
    for line in $cmd; do
        line=$(echo $line | sed "s/^ *//;s/  */ /;s/ *$//")
        if [ "$line" ]; then
            case ${line%% *} in
                !)            ;;
                sleep)        ;;
                key_enter)    line="send \r\n" ;;
                *)            line="send "$line ;;
            esac
            echo $line >>$tmp
        fi
    done; echo "! command pkill minicom" >>$tmp; IFS=
    [ "$vo" ] && echo -e $(cat $tmp | awk '{$1="\033[1;33m> \033[1;37m"$1"\033[0m"; print $0}')
    minicom -S $tmp 2>&1 >/dev/null
    rm $tmp
}

Last edited by GraveyardPC (2009-11-30 19:10:21)

Offline

#700 2009-12-02 03:21:39

Gen2ly
Member
From: Sevierville, TN
Registered: 2009-03-06
Posts: 1,529
Website

Re: Post your handy self made command line utilities

#!/bin/bash
# github-sync - sync important $HOME files to github

# Base directory
basedir="$HOME"

# Files and directories to upload to github repository
gitadd=(.bashrc .bin .vim .vimrc)
gitignore=(.vim/backup)

# Text color variables
txtund=$(tput sgr 0 1)          # Underline
txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) #  red
bldblu=${txtbld}$(tput setaf 4) #  blue
bldwht=${txtbld}$(tput setaf 7) #  white
txtrst=$(tput sgr0)             # Reset
info=${bldwht}*${txtrst}        # Feedback
pass=${bldblu}*${txtrst}
warn=${bldred}!${txtrst}


cd "$basedir"
echo "$info Preparing git local repository: ${txtund}"$basedir"${txtrst}"

# Set ignore files and directories
for i in ${gitignore[@]}; do
  if [ ! -e "$i" ]; then
    echo "$warn No file or directory by the name of${txtbld}"$basedir""$i"${txtrst}"
    exit
  else
    echo "$i" >> .gitignore || exit
    echo "$pass Ignore ${txtund}"$i"${txtrst} added to git index"
  fi
done

sort -u .gitignore -o .gitignore || exit

# Add files and directories to git index
for i in ${gitadd[@]}; do
  if [ ! -e "$i" ]; then
    echo "$warn No file or directory by the name of${txtbld}"$basedir""$i"${txtrst}"
    exit
  else
    git add $i 2> /dev/null || exit
    echo "$pass Added ${txtund}"$i"${txtrst} to git index"
  fi
done

# Record changes to all files, rm not in index; add commit message.
git commit -a -m "weekly update - $(date "+%F")" || exit
echo -e "$pass Recorded repository contents, created commit message"

# Start ssh-agent, enter password
echo -e "$info Starting ssh-agent, automatically entering password (takes about five seconds)"

eval $(ssh-agent)

entpass=$(echo "spawn ssh-add /home/todd/.ssh/id_rsa
expect \"Enter passphrase for key.*\"
send \"inspectorgadget\\n\"
expect eof" | expect -f -)

echo $entpass || exit

# Sync local to github repository
echo -e "$info Syncing local repository to github repository"
git push

Last edited by Gen2ly (2009-12-02 03:23:20)


Setting Up a Scripting Environment | Proud donor to wikipedia - link

Offline

Board footer

Powered by FluxBB