You are not logged in.

#401 2009-05-31 22:04:39

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

cp: cannot copy a directory, `/', into itself

That's exactly what I meant, it would be like trying to lift yourself by your shoestrings (at least that's how I see it).

Offline

#402 2009-05-31 22:05:28

Peasantoid
Member
Registered: 2009-04-26
Posts: 928
Website

Re: Post your handy self made command line utilities

Right! But if the directory is mounted and you use the -x flag, cp stays out and doesn't end up trying to "bootstrap" itself.

Or something like that.

Last edited by Peasantoid (2009-05-31 22:07:03)

Offline

#403 2009-06-01 01:11:37

wujaklija
Member
From: /Serbia/Ruma
Registered: 2009-02-14
Posts: 55

Re: Post your handy self made command line utilities

#!/bin/bash

function script_help {
    echo "usage : kompres <compression_type> [<file_names>...]"
    echo "compression_types : tar.bz2, tar.gz, tar.Z, bz2, gz, jar, tar, tbz2, tgz, zip, Z, lzma, 7z"
}

defaultCompression="tar.bz2"
compressonType=(tar.bz2 tar.gz tar.Z bz2 gz jar tar tbz2 tgz zip Z lzma 7z)

if [ -z "$1" ]; then
    echo "Error : no arguments entered"
    script_help
    exit 1
else 
    count=$#
    for m in ${compressonType[@]} ; do
        if [ "$1" = "$m" ]; then
            
            strlen=${#cmdline}
            cmdline=${cmdline##"$1 "}     # Strip longest match of $1 from front of $cmdline
            if [ $strlen = ${#cmdline} ] ; then
                echo "Error : Only compression type entered"
                script_help
                exit 3
            else
                compression=$m
                count=$(($# - 1))
                break
            fi
        else
            compression=$defaultCompression
            cmdline=$@
        fi
    done

    for n in $cmdline ; do
        if [ ! -e $n ]; then            # check for file existence
            echo "Error : '$n' doesn't exist"
            script_help
            exit 2
        fi
    done

    if [ $count != 1 ]; then        # if more than one file enter archive name
        echo -e "Enter archive name : \c "
        read  archive
    else
        archive=$cmdline
    fi

     case "$compression" in            # compression
        tar.bz2) tar cjf "$archive".tar.bz2 $cmdline ;;
        tar.gz) tar czf "$archive".tar.gz $cmdline ;;
        tar.Z) tar czf "$archive".tar.Z $cmdline ;;
        bz2) bzip2 "$archive".bz2 $cmdline ;;
        gz) gzip -r "$archive".gz $cmdline ;;
        jar) zip -r -q "$archive".jar $cmdline ;;
        tar) tar cf "$archive".tar $cmdline ;;
        tbz2) tar cjf "$archive".tbz2 $cmdline ;;
        tgz) tar czf "$archive".tgz $cmdline ;;
        zip) zip -r -q "$archive".zip $cmdline ;;
        Z) compress -r "$archive" ;;
        lzma) lzma "$cmdline" ;;    
        7z) 7z a -r "$archive".7z $cmdline ;;
        *) echo "Error : '$archive' cannot be compressed" ;;
    esac    
        
fi

exit 0

Last edited by wujaklija (2009-06-04 19:45:46)

Offline

#404 2009-06-01 04:45:52

deltaecho
Member
From: Georgia (USA)
Registered: 2008-08-06
Posts: 193

Re: Post your handy self made command line utilities

Here's one you may appreciate:

#!/bin/bash

### commbox ####################################################################
# A simple script that makes it easy to generate a nicely formatted comment    #
# box around text (that looks something like this :)                           #
################################################################################

# Check for the correct number of args
if [ $# -eq 0 ]; then
        echo "usage: ${0##*/} [title] [text]" 1>&2
        exit 1
fi

# The number of columns to use for wrapping,
#+ minus 4 so the comment box doesn't exceed
#+ the specified width [default: 80]

columns=76

# The border to print
border=''

# Generate the border to be used along the
#+ top and bottom of the text.
for f in $(seq $((columns + 4))); do
        border=${border}'#'
done

# Print the top border
echo -n ${border}

# If the user specified a title, print it
if [ $# -gt 1 ]; then
        echo -e "\r### $1 "
        shift
else
        echo
fi

# Print the user's message
while read line; do
        printf "# %-${columns}s #\n" "$line"
done < <(fold -w ${columns} -s << EOF
$*
EOF)

# Print the bottom border
echo ${border}

An example of its usage:

$ commbox commbox "A simple script that makes it easy to generate a nicely formatted comment box around text (that looks something like this :)"
### commbox ####################################################################
# A simple script that makes it easy to generate a nicely formatted comment    #
# box around text (that looks something like this :)                           #
################################################################################

Or, if you prefer:

$ commbox "commbox: A simple script that makes it easy to generate a nicely formatted comment box around text (that looks something like this :)"
################################################################################
# commbox: A simple script that makes it easy to generate a nicely formatted   #
# comment box around text (that looks something like this :)                   #
################################################################################

I find it useful smile


Dylon

Offline

#405 2009-06-01 05:39:37

Purch
Member
From: Finland
Registered: 2006-02-23
Posts: 229

Re: Post your handy self made command line utilities

m1sha wrote:
BASE=$HOME"/etk/"
DATE=`date +%Y%j
STORE=$BASE$DATE
YEST=$BASE$[$DATE-1]

Try these or with the %j option:

$ date -d yesterday +"%Y%m%d"
20090531
$ date +"%Y%m%d"
20090601

Offline

#406 2009-06-01 06:25:55

sujoy
Member
From: Finland
Registered: 2008-02-08
Posts: 95

Re: Post your handy self made command line utilities

I wrote a python script to take as input a directory and move all image filesinside it to a specified directory \\DIR="pictures"\\ by creating respective directories in the \\DIR\\ if it doesnt already exist, based on the image files' resolution. If the files are svg or xcf, then a directory called, "svgFiles" and "xcfFiles" respectively are created inside \\DIR\\ where they are moved.

#!/usr/bin/env python

import sys
import os
import glob
import shutil
from xml.parsers.expat import ExpatError
from xml.dom import minidom
from PIL import Image

def checkfiles(start_path):
    if not os.path.islink(start_path):
        if os.path.isfile(start_path):
            #print "%s - file" % start_path
            return processImages(os.path.abspath(start_path))
        elif os.path.isdir(start_path):
            #print "%s - directory" % start_path
            start_path=os.path.join(start_path,"*")
            for path in glob.iglob(start_path):
                checkfiles(path)
    else:
       print "links not traversed\n"

def movefile(src,dest,dest_dir):
    try:
        if os.path.isfile(dest):
            if not QUIET: print "not moving %s, file exists in %s" % (src,dest_dir)
        else:
            if not QUIET: print "moving:: %s to %s" % (src,dest)
            shutil.move(src,dest)
            return True
        return False
    except OSError:
        print "Copy failed!"
        sys.exit()

def create_if_not_exists(dest_dir):
    try:
        if os.path.isfile(dest_dir):
            raise OSError("file %s exists" % dest_dir)
        elif not os.path.exists(dest_dir):
            if not QUIET: print "creating directory ... %s" % dest_dir
            os.makedirs(dest_dir)
    except OSError:
        print "Failed to create directory %s" % dest_dir
        sys.exit()

def process_xcf(filename):
    global COUNT
    try:
        file=open(filename)
        metadata=file.readline()[0:9]
        if metadata=="gimp xcf ":
            if  DEBUG: print "%s confirmed as xcf file" % filename
            path_mvdir=os.path.join(DIR,"xcfFiles")
            create_if_not_exists(path_mvdir)
            newfile=os.path.join(path_mvdir, os.path.basename(filename))
            if movefile(filename,newfile,path_mvdir):
                COUNT +=1
            return True
        else:
            return False
    except (IOError,OSError), error:
        print error
        sys.exit()

def process_svg(filename):
    global COUNT
    try:
        svgfile = minidom.parse(filename)
        if svgfile.getElementsByTagName('svg'):
            if DEBUG: print "%s confirmed as svg file" % filename
            path_mvdir=os.path.join(DIR,"svgFiles")
            create_if_not_exists(path_mvdir)
            newfile=os.path.join(path_mvdir, os.path.basename(filename))
            if movefile(filename,newfile,path_mvdir):
                COUNT +=1
            return True
        else:
            return False
    except ExpatError, error:
        print error
    except OSError, error:
        print error
        sys.exit()
    

def processImages(filename):
    global COUNT
    if DEBUG: print filename
    try:
        im=Image.open(filename,"r")
        mvdir="%sx%s" % (im.size)
        path_mvdir=os.path.join(DIR,mvdir)
        if DEBUG: print "%s to be moved to %s" % (os.path.basename(filename),path_mvdir)
        create_if_not_exists(path_mvdir)
        newfile=os.path.join(path_mvdir, os.path.basename(filename))
        if movefile(filename,newfile,path_mvdir):
            COUNT +=1
    except IOError:
        if not (process_xcf(filename) or process_svg(filename)):
            print "%s : Not an image file" % filename
    except OverflowError:
        print "%s : Too big to process" % filename

def main():
    args=sys.argv[1:]
    for arg in args:
        checkfiles(arg)
    print "%d files processed" % COUNT

if __name__=="__main__":
    COUNT=0
    DEBUG,QUIET=False,True
    DIR="pictures"
    DIR=os.path.join(os.getenv("HOME"),DIR)
    main()

This would have been more usefull if I could deal with tags, and sort them based on tag info like "nature", "holiday", etc, but I am yet to figure out a way to do that. Currently, it just keeps my picture folder a tad organised when I need to find wallpapers of a specific resolution tongue

Offline

#407 2009-06-01 08:13:26

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

Re: Post your handy self made command line utilities

wujaklija wrote:
function script_help {
    echo "usage : kompres <compression_type> [<file_names>...]"
    echo "compression_types : tar.bz2, tar.gz, tar.Z, bz2, gz, jar, tar, tbz2, tgz, zip, Z, lzma, 7z"
}

defaultCompression="tar.bz2"
compressonType=(tar.bz2 tar.gz tar.Z bz2 gz jar tar tbz2 tgz zip Z lzma 7z)

if [ -z "$1" ]; then
    echo "Error : no arguments entered"
    script_help
    exit 1
else 
    count=$#
    for m in ${compressonType[@]} ; do
        if [ "$1" = "$m" ]; then
            
            strlen=${#cmdline}
            cmdline=${cmdline##$1}     # Strip longest match of $1 from front of $cmdline
            if [ $strlen = ${#cmdline} ] ; then
                echo "Error : Only compression type entered"
                script_help
                exit 3
            else
                compression=$m
                count=$(($# - 1))
                break
            fi
        else
            compression=$defaultCompression
            cmdline=$@
        fi
    done

    for n in $cmdline ; do
        if [ ! -e $n ]; then            # check for file existence
            echo "Error : '$n' doesn't exist"
            script_help
            exit 2
        fi
    done

    if [ $count != 1 ]; then        # if more than one file enter archive name
        echo -e "Enter archive name : \c "
        read  archive
    else
        archive=$cmdline
    fi

     case "$compression" in            # compression
        tar.bz2) tar cjf "$archive".tar.bz2 $cmdline ;;
        tar.gz) tar czf "$archive".tar.gz $cmdline ;;
        tar.Z) tar czf "$archive".tar.Z $cmdline ;;
        bz2) bzip2 "$archive".bz2 $cmdline ;;
        gz) gzip -r "$archive".gz $cmdline ;;
        jar) zip -r -q "$archive".jar $cmdline ;;
        tar) tar cf "$archive".tar $cmdline ;;
        tbz2) tar cjf "$archive".tbz2 $cmdline ;;
        tgz) tar czf "$archive".tgz $cmdline ;;
        zip) zip -r -q "$archive".zip $cmdline ;;
        Z) compress -r "$archive" ;;
        lzma) lzma "$cmdline" ;;    
        7z) 7z a -r "$archive".7z $cmdline ;;
        *) echo "Error : '$archive' cannot be compressed" ;;
    esac    
        
fi

exit 0

Good bash script ot have about.  A couple things though: When entering just one folder to compress the archive will be saved with a space in front of it (i.e " Myscripts.tgz"), and second, there is not argument to check if the first value is a compression type.  Perhaps something like this would do??

    if [[ $1 != {7z, bz2, gz, jar, lzma, tar, tgz, tar.Z ,zip, Z} ]]; then

Anyways.  Nice job.

Last edited by Gen2ly (2009-06-01 08:26:18)


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

Offline

#408 2009-06-01 10:23:26

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

You can add an option for .xz compression (in case you don't want it to be called lzma or 7z).

Offline

#409 2009-06-04 19:42:21

wujaklija
Member
From: /Serbia/Ruma
Registered: 2009-02-14
Posts: 55

Re: Post your handy self made command line utilities

Gen2ly wrote :
When entering just one folder to compress the archive will be saved with a space in front of it (i.e " Myscripts.tgz"), and second, there is not argument to check if the first value is a compression type.  Perhaps something like this would do??

if [[ $1 != {7z, bz2, gz, jar, lzma, tar, tgz, tar.Z ,zip, Z} ]]; then

Thank you for pointing that out ... you're right about space in front of filename ... i fixed that ... there is compression type argument checking in the for loop

for m in ${compressonType[@]} ; do
        if [ "$1" = "$m" ]; then

so both ways will do the job done ... if there is no compression type argument , script will use defaultCompression value ...

Last edited by wujaklija (2009-06-05 01:32:34)

Offline

#410 2009-06-15 00:19:38

ravn
Member
Registered: 2008-12-02
Posts: 10

Re: Post your handy self made command line utilities

Hi, my first contribution to this thread...

The scenario: I'm using mt-daapd to share several media-folders over the local network at home, and needed a fast way to re-generate m3u-files for all media in the folders directly beneath each share-root (things move around a lot in there at times)...so I started out writing a script, but thought that this had to have been done before so I checked the net, googled for my own work-title: genm3u, and found a few scripts named just so, but none quite what I needed, so I ended up writing my own anyways. tongue
So, here it is, my very own genm3u:

#!/bin/bash

# Name:     genm3u
# Version:  0.1
# Purpose:  to generate m3u-files with relative paths
# Author:   Ravn Revheim
# Date:     06/14/09
VERSION=0.1

# prepare the array holding the file-types to include
declare -a extensions
extensions=(.mp3 .m4a .m4p .ogg .oga .wma .flac)
verbosity="0"

function scandir {
  cd "$rootdir"

  echo -e "Generating m3u-files in the directories below:\n  $rootdir"

  # remove old and possibly stale entries
  find "$rootdir" -name \*.m3u -delete

  # scan for media-files, and create m3u-files
  for dir in *
    do
      if [ -d "$dir" ]; then
        for ext in ${extensions[*]}
          do
            find "$rootdir/$dir" -iname \*$ext -printf "%P\n">>"$rootdir/$dir/$dir.m3u"
          done
          sort "$rootdir/$dir/$dir.m3u" -o "$rootdir/$dir/$dir.m3u"
      fi
    done

  cd - > /dev/null
  echo -e "\nDone"
}

function showabout {
    echo "genm3u Version $VERSION, by Ravn Revheim"
}

function showhelp {
    echo "Options:
  -h, --help      Show this text

Usage:
  $0 [path]

If the path option is not set, genm3u will scan the current directory."
}

case "$1" in

  -h|--help)
    showhelp
    ;;

  -v|--version)
    showabout
    ;;

  *)
    if [ $# == 0 ]; then
      rootdir=`pwd`
    else
      if [ $# == 1 ] && \
         [ -e "$1" ] && \
         [ -d "$1" ]; then
        rootdir="$1"
      else
        echo "The directory $1 doesn't seem to exist..."
        showhelp
        exit 1
      fi
    fi
    scandir

esac

exit 0

Enjoy,

Last edited by ravn (2009-06-15 00:24:54)

Offline

#411 2009-06-22 08:01:25

Jon.Caldwell
Member
From: Los Angeles, CA, USA
Registered: 2009-06-22
Posts: 5
Website

Re: Post your handy self made command line utilities

Very simple (one line) script to make text big in urxvtc.

01:01:23 bin more Big

#!/bin/bash

printf '\e]710;%s\007' "xft:Mono:pixelsize=20"

Offline

#412 2009-06-24 23:11:44

segoe
Member
Registered: 2009-06-23
Posts: 5

Re: Post your handy self made command line utilities

A one-liner i use in .bashrc.

Works like cd + locate combined.
Goes to the directory where the file/folder is located.
(first result)

Usage:
"cdf filename"
"cdf foldername/"

cdf () { cd "$(dirname "$(locate "$1" | head -n 1)")" ; }

Last edited by segoe (2009-06-24 23:14:44)

Offline

#413 2009-06-25 01:12:45

HashBox
Member
Registered: 2009-01-22
Posts: 271

Re: Post your handy self made command line utilities

segoe wrote:

A one-liner i use in .bashrc.

Works like cd + locate combined.
Goes to the directory where the file/folder is located.
(first result)

Usage:
"cdf filename"
"cdf foldername/"

cdf () { cd "$(dirname "$(locate "$1" | head -n 1)")" ; }

Such a simple yet ingenious idea! I love it!

Edit: I will suggest a slight modification,

cdf () { cd "$(dirname "$(locate -i "$*" | head -n 1)")" ; }

Now it will match without case sensitivity and you can use it like this, "cdf folder with spaces in name"

Last edited by HashBox (2009-06-25 01:16:39)

Offline

#414 2009-06-28 01:10:34

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

Re: Post your handy self made command line utilities

Small snippets for ROX-Filer users,
ROX-Extract.sh -- script for the "Send To..." menu that replicates the "Extract here" function found in other file managers
http://sysphere.org/~anrxc/local/scr/so … Extract.sh

ROX-Desktop.sh -- script for the "Send To..." menu that replicates the "Send to Desktop" function found in Nautilus file manager
http://sysphere.org/~anrxc/local/scr/so … Desktop.sh

ROX-Fox.sh -- script for the "Open Containing Folder" Firefox menu that makes it possible to use ROX-Filer (no file:// URI)
http://sysphere.org/~anrxc/local/scr/sources/ROX-Fox.sh

Edit: forgot roxfox.

Last edited by anrxc (2009-06-30 22:14:08)


You need to install an RTFM interface.

Offline

#415 2009-06-28 08:16:31

cdwillis
Member
From: /home/usa
Registered: 2008-11-20
Posts: 294

Re: Post your handy self made command line utilities

I hacked together this simple script to update your twitter feed. If you don't provide any input to update your status it prints the last twenty updates from your friends feed:

#!/bin/bash

# A Simple script to update your twitter feed. If you don't provide any input to update your status it prints the last twenty updates from your friends feed

TWEET=$1
USERNAME=yourUsername
PASSWORD=yourPassword

if [ -z "$1" ]; then
        echo No status update entered. Showing last twenty updates:
        curl --basic --silent --user $USERNAME:$PASSWORD --get http://twitter.com/statuses/friends_timeline.xml | sed --quiet --expression='s/<name>\(.*\)<\/name>/\1/p' --expression='s/<text>\(.*\)<\/text>/\1/p'
        exit
fi

curl -s -u $USERNAME:$PASSWORD http://twitter.com/statuses/update.xml -d status="$TWEET" > /dev/null
echo Status updated.

exit

Offline

#416 2009-07-04 11:21:18

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

Re: Post your handy self made command line utilities

A small xsel tool for modifying or reporting of selection. E.g. select x amount of lines, run program, type wc -l, and it will tell you how many lines there were. (it will pop dmenu again with the new value and it will also modify the selection)

It uses eval so you can add as many commands as you want like sed s#[0-9]#7# | grep 7 will work.

#! /bin/dash
cmd=$(xsel -o -p | dmenu -xs -i -l 5 -rs -ni -p "xsel -o | ... | xsel -i & dmenu ")
[ -z "$cmd" ] && exit
[ "$cmd" = "$(xsel -o -p | head -n 1)" ] && exit
eval xsel -o -p \| $cmd | tee /tmp/dmenu_xsel_script | xsel -i -p
dmenu -xs -i -l 5 -rs -ni -p Result < /tmp/dmenu_xsel_script > /dev/null

Offline

#417 2009-07-04 11:30:43

rebugger
Member
From: Germany
Registered: 2007-10-28
Posts: 229

Re: Post your handy self made command line utilities

Well, i haven't written it, but it is very useful:

alias nocomment='egrep -v "^\s*(#|$)"'

Put it in your .bashrc/.zshrc/... and run it like that:

nocomment /etc/rc.conf

It will output your rc.conf without comments and empty lines - good for quick settings checking.

Offline

#418 2009-07-04 23:54:11

rizzix
Member
Registered: 2005-10-22
Posts: 55

Re: Post your handy self made command line utilities

Perhaps someone has done this already, but here's mine:

gcopy:

#!/usr/bin/python

import sys
import pygtk
import gtk

cp = gtk.clipboard_get()

s = sys.stdin.read()
if s[-1] == '\n': s = s[:-1]
cp.set_text(s)
cp.store()

gpaste:

#!/usr/bin/python

import pygtk
import gtk

cp = gtk.clipboard_get()

if cp.wait_is_text_available():
    print cp.wait_for_text()

You can do stuff like the following after you've copied some text to clipboard:

gpaste | wc

And visa-versa:

date | gcopy

Or, both:

gpaste | wc | gcopy

Of course there are  but only trivial examples smile

Last edited by rizzix (2009-07-05 00:01:04)

Offline

#419 2009-07-05 04:41:49

cdwillis
Member
From: /home/usa
Registered: 2008-11-20
Posts: 294

Re: Post your handy self made command line utilities

rebugger wrote:

Well, i haven't written it, but it is very useful:

alias nocomment='egrep -v "^\s*(#|$)"'

Put it in your .bashrc/.zshrc/... and run it like that:

nocomment /etc/rc.conf

It will output your rc.conf without comments and empty lines - good for quick settings checking.

That's a good one. Regular expressions ftw

Offline

#420 2009-07-05 09:25:24

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

Re: Post your handy self made command line utilities

rebugger wrote:

Well, i haven't written it, but it is very useful:

alias nocomment='egrep -v "^\s*(#|$)"'

Put it in your .bashrc/.zshrc/... and run it like that:

nocomment /etc/rc.conf

It will output your rc.conf without comments and empty lines - good for quick settings checking.

thats pretty usefull thanks


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

#421 2009-07-09 05:39:39

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

Re: Post your handy self made command line utilities

#!/bin/bash

delay=$1
shift
(sleep $delay ; zenity --info --text="$*") > /dev/null &

Simple script for quick reminders. For example, if you got a pizza in the oven that will be done in 15 minutes, you type:

qnote 15m OMNOMNOM

Offline

#422 2009-07-09 14:03:17

shagrat
Member
From: Norway
Registered: 2004-05-25
Posts: 18
Website

Re: Post your handy self made command line utilities

Whipped this up today to change cpufreq governors and check the active governor and frequency:

#!/usr/bin/env python
#
# Highlights the active cpufreq governor and frequency
# or changes to a governor if it's given as an argument.
#
from __future__ import with_statement

import os
import sys
import glob

SYS_DIR = "/sys/devices/system/cpu"
AVAILABLE = "cpufreq/scaling_available_governors"
GOVERNOR = "cpufreq/scaling_governor"
FREQ = "cpufreq/scaling_cur_freq"
FREQS = "cpufreq/scaling_available_frequencies"

def available(cpu):
    with open("%s/%s/%s" % (SYS_DIR, cpu, AVAILABLE)) as f:
        return f.read().split()

def active(cpu):
    with open("%s/%s/%s" % (SYS_DIR, cpu, GOVERNOR)) as f:
        return f.read().strip()

def change(cpu, gov):
    with open("%s/%s/%s" % (SYS_DIR, cpu, GOVERNOR), 'w') as f:
        f.write(gov)

def freq(cpu):
    with open("%s/%s/%s" % (SYS_DIR, cpu, FREQ)) as f:
        return int(f.read().strip())/1000

def freqs(cpu):
    with open("%s/%s/%s" % (SYS_DIR, cpu, FREQS)) as f:
        return [int(f)/1000 for f in f.read().split()]


def color(str):
    return "\033[1;32m%s\033[0m" % str

if __name__ == '__main__':
    args = sys.argv[1:]
    cpus = [c.split("/")[-1] for c in glob.glob(SYS_DIR + "/cpu[0-9]")]

    if len(args):
        for cpu in cpus:
            if args[0] in available(cpu):
                change(cpu, args[0])

    for cpu in cpus:
        govs = [color(g) if g == active(cpu) else g for g in available(cpu)]
        frqs = [color(f) if f == freq(cpu) else str(f) for f in freqs(cpu)]
        print "%s (%s MHz): %s" % (cpu, " ".join(frqs), " ".join(govs))

It should work for various amounts of cpu/cores. The active governor and frequency is highlighted with color.

Offline

#423 2009-07-09 21:09:43

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

Re: Post your handy self made command line utilities

scj wrote:
#!/bin/bash

delay=$1
shift
(sleep $delay ; zenity --info --text="$*") > /dev/null &

Simple script for quick reminders. For example, if you got a pizza in the oven that will be done in 15 minutes, you type:

qnote 15m OMNOMNOM

thats very usefull, i added it to my bashrc as follows

reminder(){
delay=$1
shift
(sleep $delay ; zenity --info --text="$*") > /dev/null &
}

I find these short scripts more useful then the other that do many more things.

Last edited by markp1989 (2009-07-09 21:12:24)


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

#424 2009-07-15 03:39:18

mikewu
Member
Registered: 2009-06-20
Posts: 8

Re: Post your handy self made command line utilities

Script to convert to .wav. Combining with youtube-dl and oggenc/vorbiscomment works out well

#! /bin/sh
audiofile="$1"
dirname=`dirname "${audiofile}"`
basename=`basename "${audiofile}"`
wavname="${dirname}/audiodump.wav"

echo "Converting $audiofile to $oggfile"

if [ -f "${audiofile}" ];
then
    mplayer -vc dummy -vo null -ao pcm:file=%`expr length "$wavname"`%"$wavname" "$audiofile"
else
    echo "File does not exist."
fi

Goes through a maildir and prints out folders with new messages. I have it print out to xmobar.

#! /bin/bash
maildir=/home/michael/.mail
excluded_folders="(All|Drafts|Sent|Spam|Starred|Trash)"
messages=""
for folder in ${maildir}/*;
do
    if [ ! -z `echo $folder | /bin/grep -Ev ${excluded_folders}` ];
    then
        if [ -d "${folder}/new" ];
        then
            foldernewmessages=`find "${folder}/new" -maxdepth 1 -type f | wc -l`
            if [ $foldernewmessages -gt 0 ];
            then
                messages="$messages `basename \"$folder\"`"
            fi
            foldernewmessages=0
        fi
    fi
done
echo -e "$messages"

Offline

#425 2009-07-15 14:19:25

linkmaster03
Member
Registered: 2008-12-27
Posts: 269

Re: Post your handy self made command line utilities

scj wrote:

Simple script for quick reminders. For example, if you got a pizza in the oven that will be done in 15 minutes, you type:

qnote 15m OMNOMNOM

I made this exact program a while ago, then wrapped it with pyGTK because I wanted to play around with Glade. Very useful.
17715-Jul-Wed_10:14.png

Last edited by linkmaster03 (2009-07-15 14:19:39)

Offline

Board footer

Powered by FluxBB