You are not logged in.

#526 2009-09-19 23:45:36

ataraxia
Member
From: Pittsburgh
Registered: 2007-05-06
Posts: 1,553

Re: Post your handy self made command line utilities

I have several things...

A backup script that uses rdiff-backup and writes to a dm-crypt volume:

#!/bin/bash

if [ `id -u` != "0" ] ; then
  echo "You must be root"
  exit 1
fi

logger -t backup "backup started"

# /dev/rawbackup is created by a udev rule
cryptsetup luksOpen /dev/rawbackup lb
mount /dev/mapper/lb /backup || exit 3

sync

rdiff-backup \
--include /boot/grub/menu.lst \
--include /etc \
--include /home \
--include /var/lib/pacman/local \
--exclude '**' \
/ \
/backup/$(hostname)

sync

rdiff-backup --list-changed-since 1B /backup/$(hostname)
df -h /backup

umount /backup
cryptsetup luksClose lb

logger -t backup "backup finished"

My status bar script for dwm:

#!/bin/sh

music=""
battery=""
loadavg=""
clock=""

while true ; do

  music="$(mpc current 2>/dev/null)"
  if [ "x$music" != "x" ] ; then
    music="$music | "
  fi

  if [ -x /usr/bin/acpi ] ; then
    battery="$(acpi -b | sed -e 's/.*, \(.*%\).*/\1/')"
    if [ "x$battery" != "x" ] ; then
      battery="$battery | "
    fi
  fi

  loadavg="$(cat /proc/loadavg) | "

  clock="$(date +'%a %b %-d %-I:%M')"

  xsetroot -display :0 -name "${music}${battery}${loadavg}${clock}"
  sleep 5

done

A "crontab -e"-style tag editor for Ogg Vorbis files:

#!/bin/bash

vorbiscomment -l "$1" > "${1%%.ogg}.tag"
vim "${1%%.ogg}.tag"
echo -n "Replace tag on ${1}?[Y/n]"
read ok
[[ "$ok" != "n" ]] && vorbiscomment -w -c "${1%%.ogg}.tag" "$1"
rm -f "${1%%.ogg}.tag"

A C utility to print the window ID of the currently focused window on stdout:

/* xgetfocus.c - link against libX11 */
#include <X11/Xlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
Display *display;
Window focus;
int revert;

display = XOpenDisplay(NULL);
XGetInputFocus(display, &focus, &revert);
printf("%d\n", (unsigned)focus);

return 0;
}

Offline

#527 2009-09-20 00:02:48

smartboyathome
Member
From: $HOME
Registered: 2007-12-23
Posts: 334
Website

Re: Post your handy self made command line utilities

A script that kills tacos! Requires osdsh.

#!/bin/sh

DOOM=100
until [ $DOOM -lt 0 ]; do
    osdctl -b "Killing all your tacos in:",$DOOM
    let DOOM-=1
    sleep .1
done
osdctl -s "Killing all your tacos now!"

Offline

#528 2009-09-21 09:24:08

wayne
Member
From: Taiwan, ROC
Registered: 2009-08-13
Posts: 6

Re: Post your handy self made command line utilities

An easy script to help me browse SVN repository without X.  Any comments are welcome! smile

#!/bin/bash
#
# This script is used to browse SVN repository.
#
# by wayne chen
#
# 20090921 - initial version
#

tmp=`mktemp`
user=<svn account>
password=<svn password>

# Determine whether here is a working copy.
if [ ! -d '.svn' ]; then
    echo "Here is not a SVN working copy!"
    exit 1
fi

# The corresponding repository URL.
path=`svn info | grep URL | cut -d ' ' -f 2 | sed -e 's/\ //g'`

while [ 1 ]; do

    echo "Repository URL:"
    echo "$path";
    echo

    echo "Files in repository:"
    echo "../" > $tmp
    svn ls $path >> $tmp
    for i in `cat $tmp | grep '.*' -n`; do
        echo $i
    done
    echo

    # User input to select a file/directory.
    echo "Enter q to leave program."
    read -p "Select an entry (entering a number): " input

    if [ $input = 'q' ]; then
        echo "Bye!"
        break
    elif [ $input = '1' ]; then
        path=`dirname $path`
        continue
    elif ! (echo $input | grep -q '^[0-9]*$'); then
        echo "Wrong input!"
        break
    fi

    selected="`head -n $input $tmp | tail -n 1`"

    # Handle selected entry.
    if (echo $selected | grep -q '^.*\/$'); then
        path="$path/$selected"
        continue
    else
        wget_tmp=`mktemp`
        wget --user=$user --password=$password $path/$selected -O $wget_tmp
        vim $wget_tmp
        rm -f $wget_tmp
        break
    fi

# End of main while loop.
done

rm $tmp
exit 0

Last edited by wayne (2009-09-21 09:26:24)

Offline

#529 2009-09-21 20:06:23

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

Re: Post your handy self made command line utilities

Just had an idea for a file chooser. With stderr it creates a small menu where only left/right/enter work, and you can pick a file from the sorted list (in this case ls -1t by modification time).
Usage:
feh "$(browse_recent)"
What it will look like:
$ feh "$(browse_recent)"
0: scrot_2009_11_11.jpg
<RIGHT>
$ feh "$(browse_recent)"
1: scrot_2009_11_10.jpg

#! /bin/bash
IFS="
"
index=0
for file in $(ls -1t); do
files[$index]=$file
((index++))
done
max=$index
((max--))
index=0
while true; do
echo -ne '\e[2K\r' >&2
echo -n $index: "${files[$index]}" >&2
read -s -n 3
if [ "$REPLY" = "$(echo -e "\e[D")" ]; then
[ $index -eq 0 ] && continue
((index--))
elif [ "$REPLY" = "$(echo -e "\e[C")" ]; then
[ $index -eq $max ] && continue
((index++))
elif [ -z "$REPLY" ]; then
echo -ne '\e[2K\r' >&2
echo "${files[$index]}"
break
fi
done

notes: if you press a key that doesn't have 3 parts like anything except cursor keys, then you need to press a few other keys until read starts at no input. (or just change the keys to jk)

Offline

#530 2009-09-21 20:29:37

Dieter@be
Forum Fellow
From: Belgium
Registered: 2006-11-05
Posts: 2,000
Website

Re: Post your handy self made command line utilities

Procyon wrote:

Just had an idea for a file chooser. With stderr it creates a small menu where only left/right/enter work, and you can pick a file from the sorted list (in this case ls -1t by modification time).
Usage:
feh "$(browse_recent)"
What it will look like:
$ feh "$(browse_recent)"
0: scrot_2009_11_11.jpg
<RIGHT>
$ feh "$(browse_recent)"
1: scrot_2009_11_10.jpg

#! /bin/bash
IFS="
"
index=0
for file in $(ls -1t); do
files[$index]=$file
((index++))
done
max=$index
((max--))
index=0
while true; do
echo -ne '\e[2K\r' >&2
echo -n $index: "${files[$index]}" >&2
read -s -n 3
if [ "$REPLY" = "$(echo -e "\e[D")" ]; then
[ $index -eq 0 ] && continue
((index--))
elif [ "$REPLY" = "$(echo -e "\e[C")" ]; then
[ $index -eq $max ] && continue
((index++))
elif [ -z "$REPLY" ]; then
echo -ne '\e[2K\r' >&2
echo "${files[$index]}"
break
fi
done

notes: if you press a key that doesn't have 3 parts like anything except cursor keys, then you need to press a few other keys until read starts at no input. (or just change the keys to jk)

hey this is pretty cool, but why not use dmenu? it's similar but you can filter the list by typing characters as well.  and it's graphical (kinda).


< Daenyth> and he works prolifically
4 8 15 16 23 42

Offline

#531 2009-09-21 20:54:40

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

Re: Post your handy self made command line utilities

@Dieter: Ah yeah, ls -t | dmenu would be the same. Maybe I can think of a better use for the stderr + read menu.

Offline

#532 2009-09-22 18:58:02

Lich
Member
Registered: 2009-09-13
Posts: 437

Re: Post your handy self made command line utilities

wget version

#!/bin/sh
WGET="wget --user-agent=Firefox"
TARGET="$HOME"
while (true); do
SELECTION=`ls -l $TARGET | grep ^d | awk '{print $8}' | dmenu -nb "#272727" -nf "#C4DF90" -sb "#C4DF90" -sf "#272727" -p $TARGET`
if [ -n "$SELECTION" ]; then
    TARGET="$TARGET/$SELECTION"
else break
fi
done
URL="$8"
cd "$TARGET"
xterm -bg "#272727" -fg "#C4DF90" -title "Download" -e "echo \"Target: $TARGET/\" && $WGET $URL && echo \"Download complete. Press any key to close\" && read"

curl ( cleaner) version

#!/bin/sh
WGET="curl --progress-bar -O"
TARGET="$HOME"
while (true); do
SELECTION=`ls -l $TARGET | grep ^d | awk '{print $8}' | dmenu -nb "#272727" -nf "#C4DF90" -sb "#C4DF90" -sf "#272727" -p $TARGET`
if [ -n "$SELECTION" ]; then
    TARGET="$TARGET/$SELECTION"
else break
fi
done
URL="$8"
cd "$TARGET"
xterm -bg "#272727" -fg "#C4DF90" -title "Download" -e "echo \"Target: $TARGET/\" && $WGET $URL && echo \"Download complete. Press any key to close\" && read"

UZBL download.sh
Uses dmenu to let you choose where to download(recursive, starts in your home directory), then spawns a terminal for download

Last edited by Lich (2009-09-22 19:44:47)


Archlinux | ratpoison + evilwm | urxvtc | tmux

Offline

#533 2009-09-23 22:36:49

Lich
Member
Registered: 2009-09-13
Posts: 437

Re: Post your handy self made command line utilities

Updated (and sort of final) version of the above script. Only thing that I see worthy of adding to this tiny tool is some sort of filename input, not sure how that would go though..I'll think about it, would sure be all that uzbl needs download-wise

#!/bin/sh
DOWNLOADER="wget --user-agent=Firefox"
#DOWNLOADER="curl --progress-bar -O"
URL="$8"
SAVE="Save file"
CANCEL="Cancel saving"
UP=".."
#If you modify the above 3 variables, make sure you name them in such a manner that you will never have a folder with the same name

TARGET="$HOME"
FGCOLOR="#CC896D"
BGCOLOR="#1b1b1b"
SELCOLOR="#C4DF90"

#could have "hardcoded" these or course but this is easier in case you want to modify something :)

#->-
while (true); do
DIRLIST=`ls -l $TARGET | grep ^d | awk '{print $8}'`
if dmenu --help 2>&1 | grep -q '\[-rs\] \[-ni\] \[-nl\] \[-xs\]'
then
    SELECTION=`echo -e -n "$SAVE\n$CANCEL\n$UP\n$DIRLIST" | dmenu -nb "$BGCOLOR" -nf "$FGCOLOR" -sb "$SELCOLOR" -sf "$BGCOLOR" -p $TARGET -xs -rs -l 10`
else
    SELECTION=`echo -e -n "$SAVE\n$CANCEL\n$UP\n$DIRLIST" | dmenu -nb "$BGCOLOR" -nf "$FGCOLOR" -sb "$SELCOLOR" -sf "$BGCOLOR" -p $TARGET`
fi
if [ "$SELECTION" = "$SAVE" ]; then 
    break
fi
if [ "$SELECTION" = "$CANCEL" ]; then 
        exit
fi
if [ -z "$SELECTION" ]; then 
        exit
fi
if [ "$SELECTION" = "$UP" ]; then 
        TARGET=$(dirname $TARGET)
else
    TARGET="$TARGET/$SELECTION"
fi
done
#-<-

cd "$TARGET"
xterm -bg "$BGCOLOR" -fg "$FGCOLOR" -title "Download" -e "echo \"Target: $TARGET/\" && $DOWNLOADER $URL && echo \"Download complete. Press any key to close\" && read"

tMmVzdA

Last edited by Lich (2009-09-23 22:44:48)


Archlinux | ratpoison + evilwm | urxvtc | tmux

Offline

#534 2009-09-24 16:39:33

tlvb
Member
From: Sweden
Registered: 2008-10-06
Posts: 297
Website

Re: Post your handy self made command line utilities

This is what I (from now on) use to connect to the wifi on my university, dunno if it is as effective as it can be or if it's a horrible (or wonderful ...right) Rube Goldberg machine, as I'm new to bash scripting, so comments would be appreciated.

What it does is:
- Check for root privileges, exits if not privileged.
- ups the wireless if it's down.
- releases the wireless if it's configured. (eh somewhat, my terminology is probably a bit off)
- scans the wireless souroundings and does some processing:
- - if an access point is not encrypted, print signal strength and essid on same line.
- - sort based on signal strength (good first).
- - remove duplicate essids (sorting first, so that it's the bad signal strength essids that are removed).
- - sort again since the above mucks up the order.
- - remove signal strength information (only useful for sorting).
- - remove entries not matching what is listed in $known.
- - append semicolon to each essid.
- - remove all newlines, so that $available is a one line string.
- Iterate over the essids in $available using semicolon as the delimiter (This is because at least one essid in my uni has a space in it).
- - Try to connect (because of the sorting before, it tries to connect to the strongest first).
- - Exit the script if successful.

#!/bin/bash

known="LU_unsecure_with_web_logon, NETLOGON, LU weblogon, netlogon, Netlogon"

if [[ $(whoami) != "root" ]]; then
        echo Fool! You need to be root to mess with the network settings.
        exit 1
fi

if [[ -z $(ifconfig|grep wlan0) ]]; then
        ifconfig wlan0 up
        sleep 10
fi

if [[ -n $(ps aux | grep "dhcpcd wlan0" | grep -v grep) ]]; then
        dhcpcd -k wlan0
fi

available=$(
        iwlist wlan0 scan                                                            |\
        egrep "Quality|Encryption|ESSID"                                             | \
        sed -n "N;N;s/.*Quality=\([0-9]\+\).*key:off.*ESSID:\"\(.*\)\".*/\1 \2/;T;p" |  \
        sort -r | sort -uk2 | sort -r | cut -d\  -f2                                 |   \
        egrep "^$(echo $known| sed "s/, /$|^/g")$"                                   |    \
        sed -n "s/^.\+$/&;/;T;p"                                                     |     \
        tr -d "\n"
)

if [[ -z $available ]]; then
        echo No known networks found
        exit 1
else
        IFS=';'
        for essid in $available; do
                echo Trying to connect to $essid
                iwconfig wlan0 essid $essid
                sleep 10
                if $(dhcpcd wlan0); then
                        echo Connected to $essid
                        exit 0
                fi  
        done
        echo All attempts unsuccessful
        exit 1
fi

Anyway, since I learn how to make stuff stick together in a working fashion, the amount of glue used is secondary ^^ (flame on)

Last edited by tlvb (2009-09-24 22:33:54)


I need a sorted list of all random numbers, so that I can retrieve a suitable one later with a binary search instead of having to iterate through the generation process every time.

Offline

#535 2009-09-24 17:19:03

anrxc
Member
From: Croatia
Registered: 2008-03-22
Posts: 834
Website

Re: Post your handy self made command line utilities

V for Vivian wrote:

This script lets me search stuff on the web on predefined sites. There are tokens for each site which must be prepended.

yubnub.org does this, there are already thousands of commands for every site imagineable (including Arch package repositories) but users can also define their own. Simple example of using it from the command line:

    function web () { $BROWSER "http://yubnub.org/parser/parse?command=$*" }

$ web aur tuxracer


You need to install an RTFM interface.

Offline

#536 2009-09-24 22:24:43

markp1989
Member
Registered: 2008-10-05
Posts: 431

Re: Post your handy self made command line utilities

tlvb wrote:

This is what I (from now on) use to connect to the wifi on my university, dunno if it is as effective as it can be or if it's a horrible (or wonderful ...right) Rube Goldberg machine, as I'm new to bash scripting, so comments would be appreciated.

What it does is:
- Check for root privileges, exits if not privileged.
- ups the wireless if it's down.
- releases the wireless if it's configured. (eh somewhat, my terminology is probably a bit off)
- scans the wireless souroundings and does some processing:
- - if an access point is not encrypted, print signal strength and essid on same line.
- - sort based on signal strength (good first).
- - remove duplicate essids (sorting first, so that it's the bad signal strength essids that are removed).
- - sort again since the above mucks up the order.
- - remove signal strength information (only useful for sorting).
- - remove entries not matching what is listed in $known.
- - append semicolon to each essid.
- - remove all newlines, so that $available is a one line string.
- Iterate over the essids in $available using semicolon as the delimiter (This is because at least one essid in my uni has a space in it).
- - Try to connect (because of the sorting before, it tries to connect to the strongest first).
- - Exit the script if successful.

#!/bin/bash

known="LU_unsecure_with_web_logon, NETLOGON, LU weblogon, netlogon, Netlogon"

if [[ $(whoami) != "root" ]]; then
        echo Fool! You need to be root to mess with the network settings.
        exit 1
fi

if [[ -z $(ifconfig|grep wlan0) ]]; then
        ifconfig wlan0 up
        sleep 10
fi

if [[ -n $(ps aux | grep "dhcpcd wlan0" | grep -v grep) ]]; then
        dhcpcd -k wlan0
fi

available=$(
        iwlist wlan0 scan                                                            |\
        egrep "Quality|Encryption|ESSID"                                             | \
        sed -n "N;N;s/.*Quality=\([0-9]\+\).*key:off.*ESSID:\"\(.*\)\".*/\1 \2/;T;p" |  \
        sort -r | sort -uk2 | sort -r | cut -d\  -f2                                 |   \
        egrep "^$(echo $known| sed "s/, /$|^/g)$"                                    |    \
        sed -n "s/^.\+$/&;/;T;p"                                                     |     \
        tr -d "\n"
)

if [[ -z $available ]]; then
        echo No known networks found
        exit 1
else
        IFS=';'
        for essid in $available; do
                echo Trying to connect to $essid
                iwconfig wlan0 essid $essid
                sleep 10
                if $(dhcpcd wlan0); then
                        echo Connected to $essid
                        exit 0
                fi  
        done
        echo All attempts unsuccessful
        exit 1
fi

Anyway, since I learn how to make stuff stick together in a working fashion, the amount of glue used is secondary ^^ (flame on)

this sound cool, dont know if its somthing i have done wrong, but i cannot use it, when i run it i get the error:

[mark@blackeee ~]$ sudo ./wifidetect.sh 
./wifidetect.sh: line 24: unexpected EOF while looking for matching `"'
./wifidetect.sh: line 46: syntax error: unexpected end of file
[mark@blackeee ~]$

Desktop: E8400@4ghz - DFI Lanparty JR P45-T2RS - 4gb ddr2 800 - 30gb OCZ Vertex - Geforce 8800 GTS - 2*19" LCD
Server/Media Zotac GeForce 9300-ITX I-E - E5200 - 4gb Ram - 2* ecogreen F2 1.5tb - 1* wd green 500gb - PicoPSU 150xt - rtorrent - xbmc - ipazzport remote - 42" LCD

Offline

#537 2009-09-24 22:37:40

tlvb
Member
From: Sweden
Registered: 2008-10-06
Posts: 297
Website

Re: Post your handy self made command line utilities

markp1989 wrote:

this sound cool, dont know if its somthing i have done wrong, but i cannot use it, when i run it i get the error:

[mark@blackeee ~]$ sudo ./wifidetect.sh 
./wifidetect.sh: line 24: unexpected EOF while looking for matching `"'
./wifidetect.sh: line 46: syntax error: unexpected end of file
[mark@blackeee ~]$

That seems to be an error on my part, line 24:

# corrected:
        egrep "^$(echo $known| sed "s/, /$|^/g")$"                                   |    \
# original:
        egrep "^$(echo $known| sed "s/, /$|^/g)$"                                   |    \

Note the " between g and ). My original post has been updated.

Last edited by tlvb (2009-09-24 22:40:16)


I need a sorted list of all random numbers, so that I can retrieve a suitable one later with a binary search instead of having to iterate through the generation process every time.

Offline

#538 2009-09-24 23:21:07

Barrucadu
Member
From: York, England
Registered: 2008-03-30
Posts: 1,158
Website

Re: Post your handy self made command line utilities

A script to generate a menu out of a series of text files, your Xdefaults, and a menu-entry-to-command mapping file. Currently Zsh dependent, but it should be really easy to make it work in other shells.

#!/usr/bin/env zsh
 
menupath=""
menufile=""
menutrack=""
choice=""
 
dmenunf="`xrdb -query | grep '*color14:' | sed 's/.*#/#/'`"
dmenusf="`xrdb -query | grep '*color10:' | sed 's/.*#/#/'`"
dmenunb="`xrdb -query | grep '*color0:' | sed 's/.*#/#/'`"
dmenusb="`xrdb -query | grep '*color0:' | sed 's/.*#/#/'`"
 
function resetmenu ()
{
    menupath="$HOME/menu/menus"
    menufile="main"
    menutrack="main"
    choice="main"
}
 
function getchoice ()
{
    menucontent=`cat $menupath/$menufile | sort && echo "Return"`
    choice="`echo $menucontent | dmenu -nf $dmenunf -nb $dmenunb -sf $dmenusf -sb $dmenusb | sed 's/ //g'`"
    
    [ "$choice" = "Return" ] && [ "$menufile" = "main" ] && exit
    [ "$choice" = "" ]       && exit
 
    menutrack="$menutrack-$choice:l"
    menufile="$choice:l"
 
    [ "$choice" = "Return" ] && resetmenu
}
 
resetmenu
 
while [[ -f $menupath/$choice:l ]]; do
    getchoice
done
 
command=`grep $menutrack $menupath/../commands`
cmd=`echo $command | sed "s/\([a-z0-9\-]*\) *//"`
 
echo $menupath
echo $menufile
echo $menutrack
echo $choice
echo $command
 
echo $cmd
 
setopt SH_WORD_SPLIT
$cmd &>/dev/null &

Example of text/command files: http://github.com/Barrucadu/home/tree/master/menu/

Offline

#539 2009-09-25 16:01:33

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

Re: Post your handy self made command line utilities

I find that ompload ruby script in AUR doesn't work for me anymore. So I made up one in bash.

#!/bin/bash

###:: ompload bash version

# TODO: Add 'slow down, cowboy' sleeps

URL='http://omploader.org/'
TMP='/tmp/ompload.tmp'
Q='-#' ; U=0 ; F='OmPlOrD'

while getopts 'quf:h' opt ; do
    case $opt in
        q) Q='-s' ;;
        u) Q='-s' ; U=1 ;;
        f) F="$OPTARG"  ;;
        h) echo '-q for quiet; -u for url only; -f for stdin.name' ; exit 0 ;;
    esac
done
shift $((OPTIND-1))

if [ ${#@} -eq 0 ] ; then
    curl $Q -F "file1=@-;filename=${F}" ${URL}upload -o "${TMP}"
    URI=$(grep '<!-- View file' "${TMP}" | grep -m1 -o ${URL}'[[:alnum:]]*')
    echo "${URI}"
else
    for IMG ; do
        curl $Q -F "file1=@${IMG}" ${URL}upload -o "${TMP}"
        URI=$(grep '<!-- View file' "${TMP}" | grep -m1 -o ${URL}'[[:alnum:]]*')
        [ $U == 0 ] && echo "${IMG}" '-->' "${URI}" || echo "${URI}"
    done
fi

Can somebody tell me why the good old ompload ruby script doesn't work anymore? I think it's 'coz the ruby version bump... How do I fix it?

Edit: So I updated the script as Daenyth suggested, allowing stdin as input. smile

Last edited by lolilolicon (2009-09-26 04:09:03)


This silver ladybug at line 28...

Offline

#540 2009-09-25 16:35:29

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

Re: Post your handy self made command line utilities

You should add a -t 0 check to let it read from STDIN

Offline

#541 2009-09-27 02:53:00

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

Re: Post your handy self made command line utilities

well, a decent result to from the night's bordem... i call it "whatdidido".  print package upgrades listed in pacman log using -Syu's as timestamps...

here's the help:

> whatdidido help
usage:

  /home/patrick/.bin/whatdidido M
     show me what i've upgraded looking back
     a maximum M -Syu 's (default 1)

  /home/patrick/.bin/whatdidido M N
     show me what i've upgraded looking back
     between minimum N and maximum M -Syu 's

some sample output:

> whatdidido
-------------[  -Syu 1   ]---------------<
 upgraded db (4.7.25.4-1 -> 4.8.24-1)
 upgraded apr-util (1.3.9-2 -> 1.3.9-3)
 upgraded apache (2.2.13-2 -> 2.2.13-3)
 upgraded heimdal (1.2.1-6 -> 1.2.1-7)
 upgraded kernel26 (2.6.31-1 -> 2.6.31.1-1)
 upgraded libsasl (2.1.23-1 -> 2.1.23-2)
 upgraded pam (1.0.4-1 -> 1.0.4-2)
 upgraded perl (5.10.0-6 -> 5.10.1-2)
 upgraded php (5.3.0-3 -> 5.3.0-4)
 upgraded python (2.6.2-5 -> 2.6.2-6)
 upgraded redland (1.0.9-3 -> 1.0.9-4)
 upgraded ruby (1.9.1_p243-1 -> 1.9.1_p243-2)
 upgraded subversion (1.6.5-4 -> 1.6.5-5)
 upgraded kernel26-bfs (2.6.31-232 -> 2.6.31.1-232)
 upgraded openerp-client (5.0.3-1 -> 5.0.5-1)
 upgraded openerp-server (5.0.3-1 -> 5.0.5-1)
 upgraded scrotwm (0.9.6-1 -> 0.9.7-1)
 upgraded virtualbox_bin (3.0.6-2 -> 3.0.6-3)
 upgraded python (2.6.2-6 -> 2.6.2-5)
 upgraded libxpm (3.5.7-2 -> 3.5.7-2)
 upgraded irssi (0.8.14-1 -> 0.8.14-1)
 upgraded python (2.6.2-5 -> 2.6.2-6)
 upgraded perl (5.10.1-2 -> 5.10.1-2)
 upgraded perl (5.10.1-2 -> 5.10.0-4)
-------------[    Now    ]---------------<

> whatdidido 3 2
-------------[  -Syu 3   ]---------------<
 upgraded enscript (1.6.4-3 -> 1.6.4-4)
 upgraded iptables (1.4.4-1 -> 1.4.5-1)
 upgraded python-matplotlib (0.99.1-2 -> 0.99.1.1-1)
 upgraded uzbl-git (20090826-2 -> 20090826-2)
 upgraded nvidia-utils-beta (190.32-2 -> 190.36-1)
-------------[  -Syu 2   ]---------------<

and the script itself:

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

message() {
  echo "usage:"  
  echo
  echo "  $0 M"
  echo "     show me what i've upgraded looking back"
  echo "     a maximum M -Syu 's (default 1)"
  echo
  echo "  $0 M N"
  echo "     show me what i've upgraded looking back"
  echo "     between minimum N and maximum M -Syu 's"
  echo
  exit 1
}

# pacman log
log='/var/log/pacman.log'

# some temp files
tmp='/tmp/timelime'
tmp2='/tmp/upgrades'

# a help
[ "$1" = "help" ] && message

# $0 M maybe N
case $# in
  0) M=1  ; N=0  ;;
  1) M=$1 ; N=0  ;;
  2) M=$1 ; N=$2 ;;
  *) message     ;;
esac

grep '.*upgraded.*(.*)$\|starting full system upgrade' $log | cut -d ']' -f 2 | uniq > $tmp

max=$(grep -c '^ starting' $tmp)

count=1
grep -n '^ starting' $tmp | while read line; do
  echo "$count $line" >> $tmp2
  count=$((count+1))
done

line_M=$(awk "/^$((max-M+1))\ /"'{print $2}' $tmp2 | cut -d ":" -f 1)

if [ $N -eq 0 ]; then
  line_N=$(wc -l < $tmp)
else
  line_N=$(awk "/^$((max-N+1))\ /"'{print $2}' $tmp2 | cut -d ":" -f 1)
fi

echo "-------------[  -Syu $M  ]---------------<"
head -n$((line_N-1)) $tmp | tail -n$((line_N-line_M-1))

if [ $N -eq 0 ]; then
  echo "-------------[    Now    ]---------------<"
else
  echo "-------------[  -Syu $N  ]---------------<"
fi

rm $tmp $tmp2

Last edited by brisbin33 (2009-09-27 18:10:33)

Offline

#542 2009-09-27 05:27:47

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

Re: Post your handy self made command line utilities

What no color?  Blasphemy!  tongue

Nice script, brisbin.


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

Offline

#543 2009-09-27 12:57:16

anotherjohn
Member
Registered: 2009-09-23
Posts: 10

Re: Post your handy self made command line utilities

Maybe this is a bit too simple to be worth posting (in light of the above), but I find it useful:

#!/bin/bash

du --max-depth=1 | sort -nr

Example usage:

[/usr] du0
3989396    .
2000024    ./share
1466052    ./lib
256156     ./bin
221060     ./include
37724      ./src
8296       ./sbin
40         ./doc
36         ./local
4          ./man

Edit for SpeedVin:
The command shows the size of the current directory and each directory off the current directory (including hidden), sorted by size, The size is given in k, though actually this looks a bit better:

#!/bin/bash

du -h --max-depth=1 | sort -hr

Giving:

3.9G    .
2.0G    ./share
1.4G    ./lib
251M    ./bin
216M    ./include
37M     ./src
8.2M    ./sbin
40K     ./doc
36K     ./local
4.0K    ./man

Last edited by anotherjohn (2009-09-27 15:15:26)

Offline

#544 2009-09-27 14:54:48

SpeedVin
Member
From: Poland
Registered: 2009-04-29
Posts: 955

Re: Post your handy self made command line utilities

anotherjohn wrote:

Maybe this is a bit too simple to be worth posting (in light of the above), but I find it useful:

#!/bin/bash

du --max-depth=1 | sort -nr

Example usage:

[/usr] du0
3989396    .
2000024    ./share
1466052    ./lib
256156     ./bin
221060     ./include
37724      ./src
8296       ./sbin
40         ./doc
36         ./local
4          ./man

If I understand that command/script good I can see hieded dirs and it's size?


Shell Scripter | C/C++/Python/Java Coder | ZSH

Offline

#545 2009-09-27 15:08:15

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

Re: Post your handy self made command line utilities

A small monitor for RSS. It scans the source code of the links in the RSS, so be wary of html tags in your terms, and don't forget to use regex characters like \<, \>.

#! /bin/bash
# $1 = *.rss
#
# Continuously check the articles in an rss for terms.
# Put terms in ~/.rss_getter_terms, newline separated.

[ $# = 1 ] || exit 1
IFS="
"
while true; do

for article in $(curl -s "$1" | sed -n 's/<link>\(.*\)<\/link>/\1/p' | sed 's/#.*//;s/[[:blank:]]//g' | tail -n +2 | tac); do
(curl -s "$article" | grep -o -i "$(cat ~/.rss_getter_terms)" && echo -e "$article\t\t$(date)" ) | tr '\n' ' ' | sed -n 's/.$/&\n/p'
sleep 2
done

sleep 100
done

Offline

#546 2009-09-28 01:53:08

chpln
Member
From: Australia
Registered: 2009-09-17
Posts: 361

Re: Post your handy self made command line utilities

Aliases specific to the current directory.  Handy for those commands which vary slightly by directory.

pwda.sh:

#!/bin/zsh

typeset -A alias

case $PWD in
    "$HOME/code/project")
            alias=(
                "clean" "make clean"
                "tag" "git tag $2 $3"
                "archive" "git archive --format=tar --prefix=project-$2/ $2 | gzip > project-$2.tar.gz"
                "build" "./configure --enable-this --disable-that --prefix=/usr && make"
                "mkrelease" "pwda.sh clean && pwda.sh build && pwda.sh tag $2 $3 && pwda.sh archive $2"
            );;
    "path/to/dir")
            alias=(
                "alias1 "command1"
                "alias2" "command2"
            );;
esac

ran_command=1

# Prepare source if necessary
test -z $alias[.before-action] || eval $alias[.before-action]

# Perform specified actions
test -z $alias[$1] || ran_command=0; eval $alias[$1]

# Perform any necessary cleanups
test -z $alias[.after-action] || eval $alias[.after-action]

exit $ran_command

To have it provide aliases transparently, try:

.zshrc:

command_not_found_handler() {
    /path/to/pwda.sh "$@"
}

or

.bashrc:

command_not_found_handle() {
    /path/to/pwda.sh "$@"
}

The one drawback of this is it requires zsh to provide decent syntax for associative arrays.  I'd be interested if anyone knows a way to implement this in bash cleanly.

Last edited by chpln (2009-09-29 00:09:56)

Offline

#547 2009-09-28 09:27:26

vik_k
Member
From: Pune, India
Registered: 2009-07-12
Posts: 227
Website

Re: Post your handy self made command line utilities

brisbin33 wrote:

i keep my music collection on shuffle in mpd.  when a good song comes up i run this script with no options.  after a few months of use, i have a nice little playlist that i can access via the same script with some other options listed in the help message.  requires mpd/mpc and an at least mildly OCD tagging of your music collection.  enjoy!

#!/bin/bash
#
# GoodSong V 0.1
#
# pbrisbin 2009
#
# keep a running list of good songs as they
# pop up in your playlist
#
# requires a mpd and mpc
#
###

# A place to keep the list
list="$HOME/.goodsongs"

# Get the now playing song from mpc and check
# if it's already in the list
song="$(mpc | head -n1)"
check=$(grep "$song" "$list")

# just the help message
message() {
  echo ""
  echo " GoodSong keeps a text file of good songs pulled from"
  echo " mpd. When run with no options, it simply appends the"
  echo " currently mpd playing song to the list.  other"
  echo " options are as follows:"
  echo ""
  echo "        -s | --show  Displays a random song from the"
  echo "                     existing list."
  echo ""
  echo "        -p | --play  Plays a random song from the"
  echo "                     existing list."
  echo ""
  echo "        -b | --build Builds a playlist of your full"
  echo "                     existing list."
  echo ""
  echo "        -h | --help  Displays this message and quits."
  echo ""

  exit 1
}

# get the filename from a line in the list
getfilename() {
  artist="$(echo $1 | sed 's/\ \-\ /+/g' | cut -d "+" -f 1)"
  title="$(echo $1 | sed 's/\ \-\ /+/g' | cut -d "+" -f 2)"
  filename="$(mpc search artist "$artist" title "$title" | head -n1)"
}

# create it if it doesn't exist
[ -f $list ] || touch $list

# parse the CLI options if they're there
case $1 in
  -h|--help)
    message
  ;;
  -s|--show)
    track="$(cat $list | sort -R | head -n1)"
    echo $track
  ;;
  -p|--play)
    track="$(cat $list | sort -R | head -n1)"
    getfilename "$track"
    mpc clear
    mpc add "$filename"
    mpc play
  ;;
  -b|--build)
    mpc clear
    cat $list | while read track; do
      getfilename "$track"
      echo $filename
    done
    mpc play
  ;;
  *)
    [ -z "$check" ] && echo "$song" >> "$list"
    echo "Added \"$song\" to the list.  try -h for more options."
  ;;
esac

exit 0

may break if you have the string " - " anywhere in an artist or title tag

edit: quick bugfix, i'll probably do that a few times...

first thing first, I'm not that much good in scripting like you people & I found above script much useful.
but if u have got "[" in your song title then it adds that song again to the good songs list.
so i am proposing a way to avoid this & might be there is another way to achieve same.
changes only in the "case" statement where script gets called without argument ie adding songs

*)          mpc | grep -q playing || exit 1
              song="$(mpc | head -n1)"
              tmp="$(echo "$song" | sed -e 's/\[/\\[/g')"
              grep -qx "$tmp" "$list" || echo "$song" >> "$list" ;;

"First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack." ~ George Carrette

Offline

#548 2009-09-28 19:04:39

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

Re: Post your handy self made command line utilities

mpdfav;

#!/bin/sh
# mpdfav
# trapd00r
# WTFPL etc.
#
# Feel free to patch and send me the diff

## Thu Sep 17 18:14:03 CEST 2009
# fixed 'bug' with empty id3-tags and retarded people who cannot spell
#

## Sat Sep 12 07:57:56 CEST 2009
# Creating playlists based on date was pretty useless for me; instead, it now
# reads the 'genre'-id3-tag. 



# First off, some nice colors ey?
GRAY="\033[1;30m"
LIGHT_GRAY="\033[0;37m"
CYAN="\033[0;36m"
LIGHT_CYAN="\033[1;36m"
ORANGE="\033[1;31m"
NO_COLOR="\033[0m"

BOLD="\033[1m"

# Where do you want your playlists hidden?
LISTDIR=/mnt/Music_1/Playlists
GENRE=$(mpc --format %genre%|head -1)


# If called with an argument, that'll be the name of the playlist
if [ "$1" ]; 
then
    NAME="$1.m3u"

elif [ -z $GENRE ];
then
        NAME="random.m3u"
else
    NAME="$(echo $GENRE|tr A-Z a-z|sed 's/[Pp]sychadelic/psychedelic/').m3u"
fi

# Check if file exists ... 
if [ -f "$LISTDIR/$NAME" ]; 
then
    mpc --format %file%|head -1 >> "$LISTDIR/$NAME"

# If not... (some people claim this is useless since >> would automagically
# create the file if it does not exist)
else
    mpc --format %file%|head -1 > "$LISTDIR/$NAME"
fi



echo -e "$BOLD $ORANGE
CONTENT: $NO_COLOR\n
$CYAN`cat "$LISTDIR/$NAME"`$NO_COLOR \n$ORANGE 
`cat "$LISTDIR/$NAME"|wc -l`$NO_COLOR tracks in $GRAY "$LISTDIR/$NAME"
$NO_COLOR
$BOLD $ORANGE
Latest: $NOCOLOR$CYAN`cat "$LISTDIR/$NAME"|tail -1`$NO_COLOR



"

If some dude have a solution for this part;

    NAME="$(echo $GENRE|tr A-Z a-z|sed 's/[Pp]sychadelic/psychedelic/').m3u"

I'd be very happy to hear about it since my solution is terrible (the sed part).

Offline

#549 2009-09-28 23:48:17

scj
Member
From: Sweden
Registered: 2007-09-23
Posts: 158

Re: Post your handy self made command line utilities

dmz wrote:

If some dude have a solution for this part;

    NAME="$(echo $GENRE|tr A-Z a-z|sed 's/[Pp]sychadelic/psychedelic/').m3u"

I'd be very happy to hear about it since my solution is terrible (the sed part).

Fix your tags.

#!/bin/bash

library=$HOME/media/audio/Music
IFS=$'\n'
for file in $(mpc list filename genre Psychadelic); do
  id3 -2v -g Psychedelic "$library/$file"
done
mpc update

The script uses id3 (in [extra]) to set the id3v2 genre tag and update the mpd library.

Offline

#550 2009-09-29 02:20:01

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

Re: Post your handy self made command line utilities

I made this the other day to auto download torrent files exclusively from Digital Hive. Might be useful for someone else, as well. It will increment the episode and season numbers as it downloads each new episode, so there's no reason to constantly edit the configuration file. Just use cron to run it every 15 minutes or so and it'll throw the torrents into your watch directory automatically. (I use rtorrent btw.)

dhr.py

#!/usr/bin/python
# Digital Hive RSS (DHR)
# TV Episode Auto Downloader

import feedparser, re, urllib2, sys, ConfigParser

def inArray(value,array):
        for i in array:
                if i == value: return True
        return False

def searchFeed():
        # RegEx for Name, Season, Episode conventions (will understand "S02E01", "2x01" and "201")
        title   = re.compile(r"(?P<name>^.*?)\.(?:(?P<n>\d{3,4})|(?:[Ss]?(?P<s>\d+)(?:[Ee]|[Xx])(?P<e>\d+)))\.")
        feed    = feedparser.parse("http://www.digitalhive.org/rss.php?feed=dl=passkey="+PASS+"&uid="+UID+"&pass="+PASS+"&cat=7")

        for show in config.items("shows"):
                sName           = show[0].replace(" ",".")
                sID             = int(show[1])
                nID             = sID
                found           = []

                for entry in feed.entries:
                        match = title.match(entry["title"])
                        if not match: continue

                        n       = match.group("n")
                        s       = match.group("s")
                        e       = match.group("e")

                        eName   = match.group("name").lower()
                        eID     = int(n) if n else int(s)*100+int(e)

                        if sName != eName: continue
                        if eID >= sID:
                                if inArray(eID,found): continue
                                found.append(eID)

                                if eID > nID: nID = eID
                                config.set("shows",show[0],str(nID+1))

                                try: getFile(entry["link"],entry["title"])
                                except error: continue

def getFile(link,name):
        url             = "http://www.digitalhive.org/download.php?id="+link[42:link.find("&")]+"&name="+name+".torrent"
        headers         = {
                                "Referer":      "http://www.digitalhive.org/browse.php?cat=7",
                                "Cookie":       "uid="+UID+"; pass="+PASS
                          }
        response        = urllib2.urlopen(urllib2.Request(url,None,headers))
        output          = open(DIR+"/"+name+".torrent","wb")
        output.write(response.read())
        output.close()

path    = sys.argv[0][0:sys.argv[0].rfind("/")]+"/config"
config  = ConfigParser.ConfigParser()
config.read(path)

PASS    = config.get("config","pass")
UID     = config.get("config","uid")
DIR     = config.get("config","download_dir")

searchFeed()
config.write(open(path,"w"))

config

[config]
download_dir = /example/folder
uid = USER_ID (from cookies)
pass = PASSWORD_HASH (from cookies)

[shows]
this show = 201
another tv show = 2012
yet another = 511

Last edited by GraveyardPC (2009-09-29 03:14:39)

Offline

Board footer

Powered by FluxBB