You are not logged in.

#151 2009-01-26 22:55:23

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

Re: Post your handy self made command line utilities

all these are nothing special, but they work fine for what i need:

toggles the mute status of mpd, have this tied to the mute key on my keyboard.

#!/bin/sh

if mpc | tail -n 1 | grep "volume:  0%" > /dev/null
then
 mpc volume +70
else
 mpc volume -100
 fi

checks if mpd is running, if it is not running then it runs it , and plays. if it is running it plays or pauses the music, i have this tied to the play/pause key on my pc.

#!/bin/sh
if pidof mpd | grep [0-9] > /dev/null
then
 mpc toggle  >/dev/null 2>&1
else
 mpd  >/dev/null 2>&1
 mpc play  >/dev/null 2>&1
 fi

this one displays the current stats of any torrent flux downloads, i use this through conky.

#!/bin/dash
dir=/media/downloads ## replace with torrentflux download dir
cutno=26 #Specifies the number of characters to show in the title name, usefull to stop
host=http://192.168.1.99/torrentflux
user=mark
pass=******


curl -c .tf_cookie -d username=$user -d iamhim=$pass $host/login.php >/dev/null 2>&1
curl -H "Expect:" -b .tf_cookie $host/index.php  >/dev/null 2>&1 > .torrentstats.tmp

echo RX Speed `cat .torrentstats.tmp | grep -i '<strong' | tail -n 4| head -n 1 | cut -f3 -d'>' | cut -f1 -d'<';` Kb/s
echo TX Speed `cat .torrentstats.tmp | grep -i '<strong' | tail -n 3| head -n 1 | cut -f3 -d'>' | cut -f1 -d'<';` Kb/s
echo Free Space `cat .torrentstats.tmp | grep -i '<strong' | tail -n 2| head -n 1 | cut -f3 -d'>' | cut -f1 -d'<';`

cd $dir/.torrents
echo Transfers: `ls *.stat  | wc -l` ##counts the amount transfers 
echo " "
for file in *.stat; do
size=`cat $file | tail -n 1;`
echo $file | cut -f1 -d'.' | cut -c 1-$cutno | tr '_' ' ' | tr -d '[{}(),\!]' | tr -d "\'" | tr '[a-z]' '[A-Z]'; ## displays torrent names, in upper case, without any puncuation 
echo `cat $file | head -n 3 | tail -n 1 | tr '[a-z]' '[A-Z]';`  : `cat $file | head -n 2 | tail -n 1;`% ## displays the status of the torrent
echo RX speed: `cat $file |  head -n 4 | tail -n 1;`  ##displays the current download speed per torrent 
echo TX speed: `cat $file |  head -n 5 | tail -n 1;` ##displays the current upload speed per torrent 
echo size: `expr $size / 1048576` MB ##displays the file size 
echo Seeds: `cat $file |  head -n 7 | tail -n 1 | cut -f1 -d'+';` ##displays the amount of seeds 
echo Peers: `cat $file |  head -n 8 | tail -n 1 ;` ##displays the amount of peers
echo " "
done
rm .torrentstats.tmp

this downloads the latest observation feed from bbc weather, then it prints out a bit of info. if you want to use this your self, you will have to change the link to the rss feed for your town, currently its set for london, also this is used with conky.

curl http://feeds.bbc.co.uk/weather/feeds/rss/obs/world/0008.xml  >/dev/null 2>&1 > .weatherfeedrs
echo Temperature:     `cat .weatherfeedrs | grep "Temperature"| cut -f2 -d' ' | tr '&#xB0' ' ' | cut -c 1-4`C
echo Wind Direction:  `cat .weatherfeedrs| grep "Temperature"| cut -f6 -d' ' | tr -d ','`
echo Wind Speed:      `cat .weatherfeedrs | grep "Temperature"| cut -f9 -d' '` mph
echo Humidity         `cat .weatherfeedrs | grep "Temperature"| cut -f13 -d' ' | tr '&#xB0' ' ' | cut -c 1-3`%
echo pressure `cat .weatherfeedrs | grep "Temperature"| cut -f15 -d' '` `cat .weatherfeedrs | grep "Temperature"| cut -f16 -d' '`
echo Visability:      `cat .weatherfeedrs | grep "Temperature"| cut -f7 -d':'| cut -c2-20`
rm .weatherfeedrs

Last edited by markp1989 (2009-01-29 16:05:09)


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

#152 2009-01-28 19:32:34

Apo
Member
Registered: 2009-01-28
Posts: 3

Re: Post your handy self made command line utilities

This is a short C program to update dwm's status bar. It shows load averages and the time.
clicky

Offline

#153 2009-01-29 02:14:04

JT
Member
Registered: 2009-01-16
Posts: 21

Re: Post your handy self made command line utilities

No longer working with XFCE update...

Last edited by JT (2009-03-18 05:26:27)

Offline

#154 2009-01-29 03:34:06

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

Re: Post your handy self made command line utilities

markp1989 wrote:

toggles the mute status of mpd, have this tied to the mute key on my keyboard.

Why not just use «mpc toggle»?

Offline

#155 2009-01-29 13:09:28

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

Re: Post your handy self made command line utilities

Daenyth wrote:
markp1989 wrote:

toggles the mute status of mpd, have this tied to the mute key on my keyboard.

Why not just use «mpc toggle»?

becase all that does is play or pause the music, rather thun muting or un muting it.


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

#156 2009-01-29 15:28:56

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

Re: Post your handy self made command line utilities

Woops, brain fart. My bad smile

Offline

#157 2009-02-01 11:41:08

b3n
Member
Registered: 2008-11-12
Posts: 20

Re: Post your handy self made command line utilities

Clean packages:

#!/bin/sh

for package in `pacman -Qt | cut -d' ' -f1`
do
    pacman -Qi $package | grep -E "(Name|Vers|Desc|URL)"
    echo -ne "\ndelete? "
    read doit
    case $doit in [yY]*)
        pacman -Ru $package
        #echo $package >> ~/.pacleaves_history
    esac
    echo -e "\n\n"
done

Last edited by b3n (2009-04-18 23:16:57)

Offline

#158 2009-02-01 12:37:27

Themaister
Member
From: Trondheim, Norway
Registered: 2008-07-21
Posts: 652
Website

Re: Post your handy self made command line utilities

Dummypkg: Let pacman know if a program has been installed manually from source: (kernel and nvidia driver (libgl) in my case tongue)
Usage:
dummypkg -S <package> <version> # Installs dummypkg
-R <package> #removes it
-l #lists all packages installed by dummypkg
The script uses sudo, so beware tongue

#!/bin/bash

###########
#####
##       Dummypkg v0.1
#####
###########

## Script to install dummy packages in pacman

## Use at own risk!

function install(){
    if [ -d ~/.dummybuild-tmp/$PACKAGE ]; then
       rm -r ~/.dummybuild-tmp/$PACKAGE 
    fi
    
    mkdir -p ~/.dummybuild-tmp/$PACKAGE
    echo "pkgname=$PACKAGE" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "pkgver=$PKGVER" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "pkgrel=1" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "pkgdesc=\"Dummy package created by dummypkg\"" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "arch=('i686' 'x86_64')" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "url=""" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "license=\"GPL\"" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "depends=()" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "source=()" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "build(){" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "mkdir -p ~/.dummybuild-tmp/$PACKAGE/pkg/etc/dummy" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "echo >> \"Installed by dummypkg\" >> ~/.dummybuild-tmp/$PACKAGE/pkg/etc/dummy/$PACKAGE-$PKGVER" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    echo "}" >> ~/.dummybuild-tmp/$PACKAGE/PKGBUILD
    
    cd ~/.dummybuild-tmp/$PACKAGE/
    makepkg || exit 1
    sudo pacman -U *pkg.tar.gz
    cd ~
    rm -r ~/.dummybuild-tmp/
    exit 0
}

function remove(){
   if [ -e /etc/dummy/$RPACKAGE* ]; then
     sudo pacman -R $RPACKAGE
   else
     echo "This package is not installed by dummypkg ... Exiting"
     exit 1
   fi
   exit 0
}

function list(){
    for file in `ls /etc/dummy -1` 
    do
       
          echo ">>  $file"
       
    done
    exit 0
}

function usage(){
    echo "usage: info [[--install] [--list] [--help] [--remove] [--version]]"
    exit 0
}


INSTALL=0
REMOVE=0
LIST=0



if [ "$1" = "" ]; then
    usage ; exit 1
fi 
while [ "$1" != "" ]; do
    case $1 in
        -S | --install )    
            INSTALL=1 
            PACKAGE="$2"
            PKGVER="$3"
            if [ "$2" = "" ]; then
                echo "--install requires a package name"
                exit 1
            fi
            if [ "$3" = "" ]; then
                echo "--install requires a package version"
                exit 1
            fi
            shift
            shift
            ;;
        -R | --remove )    
                REMOVE=1 
                RPACKAGE="$2"
                if [ "$2" = "" ]; then
                    echo "--remove requires a package name"
                    exit 1
                fi
                shift 
                ;;
        -h | --help  )    usage; exit 0 ;;
        -l | --list   )    LIST=1 ;;
        * )               usage ; exit 1 
    esac
    shift
done



if [ $INSTALL = 1 ]; then
  install
fi
if [ $REMOVE = 1 ]; then
   remove
fi
if [ $LIST = 1 ]; then
   list
fi

Offline

#159 2009-02-01 21:30:25

Samus_
Member
Registered: 2007-05-25
Posts: 13

Re: Post your handy self made command line utilities

implementing "join" in bash (python's join, php's implode, etc.).

NOTE: the $ means "type what follows at your terminal prompt" (some people thinks that the $ is part of the command).

    $ list_join() { 
        local OLDIFS=$IFS
        IFS=${1:?"Missing separator"}; shift
        echo "$*"
        IFS=$OLDIFS
    }

    $ list_join : one two three
    one:two:three

it only works for single characters, so this won't work as expected:

    $ list_join ', ' one two three
    one,two,three

tongue

also notice that you need to pass the list expanded (hence the name "list_join") so if you have an array you do:

    $ myarray=(one two three)
    
    $ list_join : "${myarray[@]}"
    one:two:three

this function is pretty handy to use with fgrep (grep -f); fgrep is faster than grep because it does not use regular expressions so unless you actually need a regexp it's best to use that instead of normal grep, fgrep also accepts several words to search at once and works like an OR operation (if you chain several greps you get an AND operation) the only problem is that fgrep expects you to separate the words by newlines -quite ugly- so you can use the function like this:

    $ fgrep "$(list_join $'\n' samus root)" /etc/group
    root::0:root
    bin::1:root,bin,daemon
    daemon::2:root,bin,daemon
    sys::3:root,bin
    adm::4:root,daemon
    disk::6:root
    wheel::10:root,samus
    log::19:root
    audio::92:samus
    optical::93:hal,samus
    storage:x:95:hal,samus

nice huh? smile

PS: arch++

Offline

#160 2009-02-04 04:37:08

tlawson
Member
From: MN, USA
Registered: 2009-01-24
Posts: 24

Re: Post your handy self made command line utilities

this is a little chunk of code to extract the next window ID in line, after the current window, that matches the name you pass to it.  requires wmctrl.

#!/bin/bash

ACTIVE=`xprop -root _NET_ACTIVE_WINDOW | awk '{print $5}' | sed 's/0x//' | tail -1`
FIRST=`wmctrl -l -x | grep $1 | awk '{print $1}' | head -1`
AFTER=`wmctrl -l -x | grep $1 | awk '{print $1}' | grep -A 1 $ACTIVE | head -2 | tail +2`
echo $AFTER $FIRST | awk '{print $1}'

then you bind a key (mine is W-x) to the command

bash -c "wmctrl -i -a `windowafter urxvt` || urxvt"

and pressing W-x cycles through all instances of urxvt, or opens a new one if none exists.  binding several (editor+urxvt+browser) = no more hunting with alt-tab trying to figure out if the right terminal was 2, 3, 4 windows ago.

also handy to bind W-C-x to force a new terminal open.

Last edited by tlawson (2009-02-04 13:00:10)

Offline

#161 2009-02-04 13:04:23

rson451
Member
From: Annapolis, MD USA
Registered: 2007-04-15
Posts: 1,233
Website

Re: Post your handy self made command line utilities

tlawson wrote:

this is a little chunk of code to extract the next window ID in line, after the current window, that matches the name you pass to it.  requires wmctrl.

#!/bin/bash

ACTIVE=`xprop -root _NET_ACTIVE_WINDOW | awk '{print $5}' | sed 's/0x//' | tail -1`
FIRST=`wmctrl -l -x | grep $1 | awk '{print $1}' | head -1`
AFTER=`wmctrl -l -x | grep $1 | awk '{print $1}' | grep -A 1 $ACTIVE | head -2 | tail +2`
echo $AFTER $FIRST | awk '{print $1}'

then you bind a key (mine is W-x) to the command

bash -c "wmctrl -i -a `windowafter urxvt` || urxvt"

and pressing W-x cycles through all instances of urxvt, or opens a new one if none exists.  binding several (editor+urxvt+browser) = no more hunting with alt-tab trying to figure out if the right terminal was 2, 3, 4 windows ago.

also handy to bind W-C-x to force a new terminal open.

Nifty.  Thanks for this.


archlinux - please read this and this — twice — then ask questions.
--
http://rsontech.net | http://github.com/rson

Offline

#162 2009-02-04 13:58:10

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

Re: Post your handy self made command line utilities

Nice script!

Offline

#163 2009-02-04 14:58:43

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

Re: Post your handy self made command line utilities

i remember seeing something like this in a blog but i couldn't find it so i wrote my own.  it's really simple but i can never remember which order to pass the arguments to ln -s so this script will take them in any order and still create the correct link based on which one already exists.

> cat Scripts/symlink
#!/bin/bash

if [ -e $1 ]; then
  if [ -e $2 ]; then
    echo both $1 and $2 exist. exiting.
    exit 1
  else
    ln -s $1 $2
  fi
else
  if [ -e $2 ]; then
    ln -s $2 $1
  else
    echo neither $1 nor $2 exist. exiting.
    exit 2
  fi
fi

exit 0

Offline

#164 2009-02-04 15:09:56

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

Re: Post your handy self made command line utilities

Nice! I have the same problem with ln.

Offline

#165 2009-02-04 15:17:40

Dusty
Schwag Merchant
From: Medicine Hat, Alberta, Canada
Registered: 2004-01-18
Posts: 5,986
Website

Re: Post your handy self made command line utilities

brisbin33 wrote:

it's really simple but i can never remember which order to pass the arguments to ln -s

This cleared up for me when somebody reminded me its the same order as commands like mv and cp. In those commands you always mv|cp|ln oldfile newfile. Might help somebody someday.

Dusty

Offline

#166 2009-02-04 16:40:44

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

Re: Post your handy self made command line utilities

Dusty wrote:
brisbin33 wrote:

it's really simple but i can never remember which order to pass the arguments to ln -s

This cleared up for me when somebody reminded me its the same order as commands like mv and cp. In those commands you always mv|cp|ln oldfile newfile. Might help somebody someday.

Dusty

that makes sense, somehow my brain always focuses on the word _to_

mv oldfile _to_ new file
cp oldfile _to_ new file
link something _to_ somethingelse.... nope

link _to_ something _from_ somethingelse...

anyways, i like scripting so i find stupid reasons to write useless programs wink

Offline

#167 2009-02-04 17:07:23

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

Re: Post your handy self made command line utilities

I hit that same snag with "to"

Offline

#168 2009-02-04 18:19:54

fwojciec
Member
Registered: 2007-05-20
Posts: 1,411

Re: Post your handy self made command line utilities

Compare versions of packages in local repo with current versions in AUR.

I like to build packages from AUR manually and put them in a local repository.  This script basically compares versions of packages in a local repository with versions available from AUR.  It is designed to work with cron -- the script only produces output when more recent versions of packages are found on AUR -- which makes cron send an email with the output to my local mail account.  It doesn't have to be used with cron, of course. 

It is my first script in python so feel free to criticize smile

#!/usr/bin/env python

import re,os,urllib2,string
repo = 'myrepo' # put the name of your local repo here
aururl = 'http://aur.archlinux.org/rpc.php?type=info&arg='

def GetAURVersion(pkgname):
    aurinfo = urllib2.urlopen(aururl+pkgname).read()
    if "No result found" in aurinfo:
        return 0
    else:
        index1=string.find(aurinfo, "Version")
        index2=string.find(aurinfo, "Category")
        return aurinfo[index1+10:index2-3]

repopkgs=os.popen('pacman -Sl '+repo).readlines()
for repopkg in repopkgs:
    reporegex=re.compile(r' ')
    lpkgname=reporegex.split(repopkg)[1]
    aurversion = GetAURVersion(lpkgname)
    if aurversion == 0:
        continue
    else:
        lpkgversion=re.sub('\n','',reporegex.split(repopkg)[2])
        if aurversion > lpkgversion:
            print lpkgname+'\tlocal: '+lpkgversion+'\tAUR:'+aurversion

Offline

#169 2009-02-04 18:35:10

rson451
Member
From: Annapolis, MD USA
Registered: 2007-04-15
Posts: 1,233
Website

Re: Post your handy self made command line utilities

brisbin33 wrote:
Dusty wrote:
brisbin33 wrote:

it's really simple but i can never remember which order to pass the arguments to ln -s

This cleared up for me when somebody reminded me its the same order as commands like mv and cp. In those commands you always mv|cp|ln oldfile newfile. Might help somebody someday.

Dusty

that makes sense, somehow my brain always focuses on the word _to_

mv oldfile _to_ new file
cp oldfile _to_ new file
link something _to_ somethingelse.... nope

link _to_ something _from_ somethingelse...

anyways, i like scripting so i find stupid reasons to write useless programs wink

I just pretend it's cp. It acts the same in a sense, but like copying by reference instead of by value wink


archlinux - please read this and this — twice — then ask questions.
--
http://rsontech.net | http://github.com/rson

Offline

#170 2009-02-05 13:58:29

rson451
Member
From: Annapolis, MD USA
Registered: 2007-04-15
Posts: 1,233
Website

Re: Post your handy self made command line utilities

A little script I wrote because migrating my webserver gave me a headache because of some permissions issues.  It's easier to show output than explain.

[randy@voodoo ~]$ lspt --help
Usage: lspt [options] [path]
    List permissions tree.

  Options:
    -d, --depth N          only traverse N levels up the tree
                             Default: -1 (traverse to /)
    -h, --help             display this usage message
    -n, --numeric-mode     display numeric permissions
    -t, --text-mode        display text permissions (default)

[randy@voodoo ~]$
[randy@voodoo ~]$
[randy@voodoo ~]$ lspt test/a/b/c/d/e/f/g
rwxr-xr-x root:root     /
rwxr-xr-x root:root     /home
rwxr-xr-x randy:users   /home/randy
rwxr-xr-x randy:users   /home/randy/test
rwxr-xr-x randy:users   /home/randy/test/a
rwxr-xr-x nobody:nobody /home/randy/test/a/b
rwxr-xr-x nobody:nobody /home/randy/test/a/b/c
rwxr-xr-x root:users    /home/randy/test/a/b/c/d
rwxr-xr-x nobody:nobody /home/randy/test/a/b/c/d/e
rwxr-xr-x bitlbee:dbus  /home/randy/test/a/b/c/d/e/f
rwxr-xr-x root:root     /home/randy/test/a/b/c/d/e/f/g
[randy@voodoo ~]$
[randy@voodoo ~]$
[randy@voodoo ~]$ lspt -n -d 3 test/a/b/c/d/e/f/g
755 root:users    /home/randy/test/a/b/c/d
755 nobody:nobody /home/randy/test/a/b/c/d/e
755 bitlbee:dbus  /home/randy/test/a/b/c/d/e/f
755 root:root     /home/randy/test/a/b/c/d/e/f/g

And the code (probably a lot uglier than most of you are used to):

#!/usr/bin/python

import getopt
import grp
import os
import pwd
import stat
import sys
import string
from glob import glob

class Usage(Exception):
  def __init__(self, msg):
    self.msg = msg

class Lspt():
  """Usage: lspt [options] [path]
    List permissions tree.

  Options:
    -d, --depth N          only traverse N levels up the tree
                             Default: -1 (traverse to /)
    -h, --help             display this usage message
    -n, --numeric-mode     display numeric permissions
    -t, --text-mode        display text permissions (default)
  """

  def __init__(self):
    self._depth = -1
    self._modeView = "text"
    self._pad = 0
    self._leaf = None

  def lspt(self, path):
    # exit case
    if path == "":
      path = "/"

    # who owns this
    st = os.stat(path)
    mode = st[stat.ST_MODE]
    user = pwd.getpwuid(st[stat.ST_UID])[0]
    group = grp.getgrgid(st[stat.ST_GID])[0]

    owner = user + ":" + group
    if len(owner) > self._pad:
      self._pad = len(owner)

    if path != "/" and self._depth != 0:
      self._depth -= 1
      self.lspt(os.path.abspath(path).rsplit("/", 1)[0])

    # convert numerical mode to text if requested
    if self._modeView == "text":
      perms = ""
      for level in "USR", "GRP", "OTH":
        for perm in "R", "W", "X":
          if int(mode) & getattr(stat,"S_I"+perm+level):
            perms += perm
          else:
            perms += "-"
      mode = perms.lower()
    else:
      mode = oct(mode & 0777)[1:]

    owner = string.ljust(owner, self._pad)
    print mode, owner, os.path.abspath(path)

def main():
  lspt = Lspt()

  try:
    opts, args = getopt.gnu_getopt(sys.argv[1:], "d:hnt",
                               ["depth", "help", "numeric-mode", "text-mode"])
  except getopt.error, e:
    print "lspt: " + str(e) + ", see -h or --help for options"
    return 1

  for o, a in opts:
    if o in ("-h", "--help"):
      print Lspt.__doc__
      return 0
    elif o in ("-t", "--text-mode"):
      lspt._modeView = "text"
    elif o in ("-n", "--numeric-mode"):
      lspt._modeView = "numeric"
    elif o in ("-d", "--depth"):
      try:
        a = int(a)
        if a > 0:
          lspt._depth = a
        else:
          raise ValueError
      except ValueError:
        print "lspt: depth must be a positive integer"
        return 1

  if len(args) == 0:
    lspt._leaf = "."
  elif len(args) > 1:
    print "lspt: too many arguments"
    return 1
  else:
    if os.path.exists(args[0]):
      lspt._leaf = args[0]
    else:
      print "lspt: " + args[0] + " does not exist"
      return 1

  lspt.lspt(lspt._leaf)

if __name__ == '__main__':
  sys.exit(main())

Last edited by rson451 (2009-02-05 13:59:52)


archlinux - please read this and this — twice — then ask questions.
--
http://rsontech.net | http://github.com/rson

Offline

#171 2009-02-05 21:06:23

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

Re: Post your handy self made command line utilities

b3n wrote:

Clean packages

I modified your code a bit:
First you get presented the packages one by one (Orphans first, then explicitly installed packages). Now you can select "yes" for certain packages. These are put into a file "/tmp/removeus" with some comments.
Then you can edit that file to remedy your choice again until you do something like:

sudo pacman -Rns $(grep -v "^#.*" /tmp/removeus | xargs)

on the generated list.

inspect-packages.sh

list_stuff () {
for pkg in $(pacman $1 | cut -d' ' -f1); do
  LC_ALL="C" pacman -Qi $pkg | grep --color=auto -E "(Name|Description|URL|Installed Size)"
  echo -ne "\ncandidate? "
  read doit
  case $doit in [yY]*)
    echo -e "\n\n" >> /tmp/removeus
    LC_ALL="C" pacman -Qi $pkg | grep -E "(Description|URL|Installed Size|Depends On)" | sed -r "s/(.*)/# \1/" >> /tmp/removeus
    echo $pkg >> /tmp/removeus
  esac
  echo -e "\n\n"
done
}

echo -e "\n\033[1m\033[1;33mOrphans...\n----------\n\033[0m"
list_stuff -Qdt

echo -e "\n\033[1m\033[1;33mExplicitly Installed...\n-----------------------\n\033[0m"
list_stuff -Qet

Last edited by kljohann (2009-02-05 21:30:59)

Offline

#172 2009-02-05 21:21:48

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

Re: Post your handy self made command line utilities

OK, everyone, I have news.

GREP CAN TAKE THE FILENAME TO SEARCH AS AN ARGUMENT!

Serriously, stop doing «cat | grep»

Offline

#173 2009-02-05 21:23:53

haxit
Member
From: /home/haxit
Registered: 2008-03-04
Posts: 1,247
Website

Re: Post your handy self made command line utilities

Daenyth wrote:

OK, everyone, I have news.

GREP CAN TAKE THE FILENAME TO SEARCH AS AN ARGUMENT!

Serriously, stop doing «cat | grep»

No wai!  Srsly bro?
(Just kidding.)


Archi686 User | Old Screenshots | Old .Configs
Vi veri universum vivus vici.

Offline

#174 2009-02-05 21:32:33

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

Re: Post your handy self made command line utilities

hehe, was previously using sth. different in greps position.

Offline

#175 2009-02-05 22:00:14

pointone
Wiki Admin
From: Waterloo, ON
Registered: 2008-02-21
Posts: 379

Re: Post your handy self made command line utilities

Another AUR helper... in Python!

I build my packages in ~/aur by hand. I'm not a trusting person, so I like to look through every PKGBUILD before building. I don't know how you guys can use that yogurt thing.

The library--including a PKGBUILD class:

#! /usr/bin/env python
#
# Desmond Cox
# Jan 21, 2008
#
# aur.py: helpful classes and functions for working with the Arch Linux 
# User/Community Repository (AUR)

### Imports

import os, urllib, urlparse

### Constants 

AUR = 'http://aur.archlinux.org'
HOME = os.path.expanduser('~')
TEMP = os.path.join(HOME, 'upaur.tmp')
DEST = os.path.join(HOME, 'aur')
FETCH = '/usr/bin/wget -N -P %(dest)s %(source)s'

### Exceptions

class aurError(Exception):
    pass

### Classes

class PKGBUILD(dict):
    def __init__(self, pkg):
        dict.__init__(self)

        self.vars = ('pkgname', 'pkgver', 'pkgrel', 'pkgdesc', 'url', 'license', 'arch', 'depends', 'optdepends', 'makedepends', 'conflicts', 'provides', 'options')
        self.url = urlparse.urljoin(AUR, 'packages/%(pkg)s/%(pkg)s/PKGBUILD'     % {'pkg': pkg})
        self.tgz = urlparse.urljoin(AUR, 'packages/%(pkg)s/%(pkg)s.tar.gz'     % {'pkg': pkg})

        urllib.urlretrieve(self.url, TEMP)

        try:
            f = open(TEMP, 'r')
            data = f.read()
            f.close()
        finally:
            os.remove(TEMP)

        for line in data.split('\n'):
            x = line.strip()
            for var in self.vars:
                if x.startswith(var):
                    val = x.split('=', 1)[1].strip()
                    val = val.strip("'")
                    val = val.strip('"')
                    self[var] = val

    def get_tarball(self):
        os.system(FETCH % {'dest': DEST, 'source': self.tgz})

The program--upaur (think uproar):

#! /usr/bin/env python
#
# Desmond Cox
# Jan 21, 2008
#
# upaur.py: check the Arch Linux User/Community Repository (AUR) for updates to
# foreign packages

### Imports

from subprocess import *
import aur, os, urlparse

### Constants 

PACKAGES = Popen(['pacman', '-Qm'], stdout=PIPE).communicate()[0].split('\n')
FORMAT = " %(pkg)-30s -- %(status)s"
HOME = os.path.expanduser('~')

### Exceptions

class upaurError(Exception):
    pass

### Main

if __name__ == '__main__':
    print ":: Updating foreign packages..."

    for line in PACKAGES:
        if not line:
            continue

        pkg, local_ver = line.split()
        pkgbuild = aur.PKGBUILD(pkg)
        remote_ver = '%(pkgver)s-%(pkgrel)s' % pkgbuild
    
        if remote_ver == local_ver:
            status = 'CURRENT'
        else:
            status = 'OUTDATED'
    
        print FORMAT % {'pkg': pkg, 'status': status}

        if status == 'OUTDATED':
            update = raw_input(":: Retrieve tarball? [Y/n] ")
            if update in 'Yy':
                print
                pkgbuild.get_tarball()

Enjoy!


M*cr*s*ft: Who needs quality when you have marketing?

Offline

Board footer

Powered by FluxBB