You are not logged in.

#501 2009-09-04 21:53:22

colbert
Member
Registered: 2007-12-16
Posts: 809

Re: Post your handy self made command line utilities

^^ That's great! I just installed the aif package and copied the generic example to ~/Desktop/myaif, wonder if you could help me to edit it a bit/see if it's ok? Here's what I have so far and my ?'s on certain parts:

# this config explains the (all) available options.
# the variables are optional and we define their defaults here (so you could omit the
# definitions), unless otherwise specified.

SOURCE=cd
FILE_URL=file:///src/core/pkg
SYNC_URL=
HARDWARECLOCK=localtime
TIMEZONE=Canada/Eastern
# Do you want to have additional pacman repositories or packages available at runtime (during installation)?
# RUNTIME_REPOSITORIES = array like this ('name1' 'location of repo 1' ['name2' 'location of repo2',..])
RUNTIME_REPOSITORIES='core' 'extra'
# space separated list
RUNTIME_PACKAGES=

# packages to install
TARGET_GROUPS=base       # all packages in this group will be installed (defaults to base if no group and no packages are specified)
TARGET_PACKAGES_EXCLUDE= # Exclude these packages if they are member of one of the groups in TARGET_GROUPS.  example: 'nano reiserfsprogs' (they are in base)
TARGET_PACKAGES=openssh xorg-server screen mpd bashburn # you can also specify separate packages to install (this is empty by default)

# you can optionally also override some functions...
worker_intro () {
        infofy "Automatic procedure running the generic-install-on-sda example config.  THIS WILL ERASE AND OVERWRITE YOUR /DEV/SDA.  IF YOU DO NOT WANT THIS PRESS CTRL+C WITHIN 10 SECONDS"
        sleep 10
}

worker_configure_system () {
        prefill_configs
        sed -i 's/^HOSTNAME="myhost"/HOSTNAME="arch-generic-install"/' $var_TARGET_DIR/etc/rc.conf
}

^ Here, do I replace myhost with the hostname I want or?

# These variables are mandatory

GRUB_DEVICE=/dev/sdb
PARTITIONS='/dev/sda 100:ext2:+ 512:swap *:ext4'
BLOCKDATA='/dev/sda1 raw no_label ext2;yes;/boot;target;no_opts;no_label;no_params
/dev/sda2 raw no_label swap;yes;no_mountpoint;target;no_opts;no_label;no_params
/dev/sda3 raw no_label ext4;yes;/;target;no_opts;no_label;no_params'

^ I'm a bit confused by this, particularly the PARTITIONS line, the 100:ext2:+ 512:swap etc. part. Not sure what to edit there... Thx for any help smile

Offline

#502 2009-09-05 08:52:37

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

Re: Post your handy self made command line utilities

colbert wrote:

^^ That's great! I just installed the aif package and copied the generic example to ~/Desktop/myaif, wonder if you could help me to edit it a bit/see if it's ok? Here's what I have so far and my ?'s on certain parts:
(...)

RUNTIME_REPOSITORIES must be a bash array (see my example above your line)
for the hostname, replace 'arch-generic-install' by the hostname you want (i suggest you read up a bit more about sed. this is the most common sed expression)
your other stuff looks okay.

partitions line:
for each hard disk you want to use: '<hard disk> + one or more filesystems on it', where a filesystem is first the size in MB (or '*', which means all space that remains), behind it the filesystem type, and a '+' to set bootable to 1 in the partition table..
with BLOCKDATA you just say how those partitions need to be used.


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

Offline

#503 2009-09-06 11:49:23

mcover
Member
From: Germany
Registered: 2007-01-25
Posts: 133

Re: Post your handy self made command line utilities

So many useful scripts here. Well I thought its time I tried contributing:

This one has been a life-saver for me, as laptop-mode-tools doesn't work for me and XFCE battery plugin is not reliable enough (some kind of lag, and one day my laptop just switched off without shutting down).

/etc/rc.d/check-battery

#!/bin/bash
#
# File: check-battery
# Description: Daemon checking battery status and executing critical action when almost empty.
# Created: 01/01/2009, 09:00 GMT
# Author: Marco (mcover)

[ -z "$CRITICAL_CHARGE" ] && CRITICAL_CHARGE=5
[ -z "$CRITICAL_ACTION" ] && CRITICAL_ACTION="shutdown -h now"
[ -z "$POWER_SUPPLY" ] && POWER_SUPPLY=/sys/class/power_supply
[ -z "$BATTERY" ] && BATTERY=BAT0
[ -z "$AC" ] && AC=AC0
[ -z "$LOGFILE" ] && LOGFILE=/var/log/check-battery.log

if [ "$(id -u)" != "0" ]; then
    echo "This program must be run as root."
    exit 1
fi

if [ "$1" = "start" -o "$1" = "stop" -o "$1" = "restart" ];then
    CB_PIDFILE="/var/run/check-battery-$BATTERY.pid"
    case "$1" in
        start)
            if [ ! -f $CB_PIDFILE ]; then
                $0 > /dev/null &
                echo $! > $CB_PIDFILE
                echo "Starting battery checker ..."
            fi
        ;;
        stop)
            if [ -f $CB_PIDFILE ]; then
                kill -9 `cat $CB_PIDFILE`
                rm $CB_PIDFILE
                echo "Not checking battery anymore ..."
            fi
        ;;
        restart)
            $0 stop
            sleep 2s
            $0 start
        ;;
    esac
    unset CB_PIDFILE
    exit 0
fi

if [ ! -e $POWER_SUPPLY/$BATTERY ]; then
    echo "warning: could not find battery!"
    exit 1
fi

CAPACITY=`cat $POWER_SUPPLY/$BATTERY/energy_full`

if [ $CAPACITY -eq 0 ]; then
    echo "error: last full capacity is 0!"
    exit 1
fi

echo "Keeping an eye on battery ..."
while true
do
    if [ "$(cat $POWER_SUPPLY/$AC/online)" = 1 ];then
        echo "on ac: exiting"
        exit 0
    fi

    REMAINING=`cat $POWER_SUPPLY/$BATTERY/energy_now`
    CHARGE_CURRENT=$(($REMAINING * 100 / $CAPACITY))
    echo "current charge: $CHARGE_CURRENT critical charge: $CRITICAL_CHARGE"
    if [ $CHARGE_CURRENT -le $CRITICAL_CHARGE ]; then
        echo "critical charge reached!"
        echo "$(date ), $HOSTNAME $0: executing critical action \"$CRITICAL_ACTION\" at ${CHARGE_CURRENT}%" >> $LOGFILE

        $CRITICAL_ACTION
    fi
    sleep 20s

done

/etc/acpi/events/battery

event=battery.*
action=/etc/rc.d/check-battery restart

I've written a bunch of scripts, but I thought this one might be useful to someone. If there is a way to do the same thing somehow, that is also lightweight enough and reliable, please let me know wink

Offline

#504 2009-09-06 19:38:57

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

Re: Post your handy self made command line utilities

mcover, if your battery does not report events and/or has no ALARM support the laptop-mode-tools project now ships with an alternative to the auto-hibernate module, a module helper somewhat simillar to your script is included with recent versions.


You need to install an RTFM interface.

Offline

#505 2009-09-07 05:23:42

bmdavll
Member
Registered: 2009-09-07
Posts: 7

Re: Post your handy self made command line utilities

Since I started using Linux two years ago, I've tried out a few stickies-type applications (e.g. Tomboy on Gnome and zim). Now that I've moved on to a more lightweight Xfce on Arch (I have a 5 year-old Thinkpad), I haven't been able to find a suitable replacement. I just wanted something to manage my notes and misc. text files. I also didn't like text editing in any of those apps because I usually use Vim.

So I wrote my own command-line utility--log. The idea was to do the text editing with an editor that's worth a damn and then provide a command line interface for searching, printing, etc. This is the first version, so I appreciate any feedback on it smile

Offline

#506 2009-09-08 07:24:53

initbox
Member
Registered: 2008-09-27
Posts: 168

Re: Post your handy self made command line utilities

#!/bin/sh
#save your config files into a single database file
name="$2"
location="$3"

# insert the names of the configs you want to try to add with autocreate!
list="bashrc vimrc Xdefaults %wgetrc"

noargs () {
    echo '   
    not enough arguments!
    first enter the function you want to access:
    add|del|upd|show|rest|create|help
    and then the relevant argument.'
    exit
}

add () {
    loccontent=$(cat $location | sed "s/'/\'\'/g")
    sqlite3 confdb "insert into dbase values ('$name','$location','${loccontent}')"
    echo "Inserted '$name' into database."
}

delete () {
    if [ "$name" = "all" ]; then
        echo "Delete ALL data from the database? (y/n)"
        read confirm
        if [ "$confirm" = "y" ]; then
            sqlite3 confdb "delete from dbase"
        else
            echo "Delete cancelled."
        fi
    else
        sqlite3 confdb "delete from dbase where name='$name'"
        echo "Deleted '$name' from database."
    fi
}

update () {
    if [ "$name" = "all" ]; then
        for location in `sqlite3 confdb "select location from dbase"`; do
            updcontent=$(cat $location | sed "s/'/\'\'/g")
            sqlite3 confdb "update dbase set data='${updcontent}' where location='$location'"
        done
        echo "Updated the whole database."
    else
        location=`sqlite3 confdb "select location from dbase where name='$name'"`
        loccontent=$(cat $location | sed "s/'/\'\'/g")
        sqlite3 confdb "update dbase set data='${location}' where name='$name'"
        echo "Updated '$name' in database."
    fi
}

show () {
    if [ "$name" = "all" ]; then
        echo 'Showing all stored config files:
================================='
        sqlite3 -separator ½ confdb "select name,location from dbase" | sed "s/½/\\t \\t/g"
    else
        sqlite3 confdb "select data from dbase where name='$name'"
    fi
}

restore () {
    if [ "$name" = "all" ]; then
        for location in `sqlite3 confdb "select location from dbase"`; do
            sqlite3 confdb "select data from dbase where location='$location'" > "$location"
        done
    else
        location=`sqlite3 confdb "select location from dbase where name='$name'"`
        sqlite3 confdb "select data from dbase where name='$name'" > "$location"
        echo "Restored '$name' from database."
    fi
}

createdb () {
    if [ "$name" = "none" ]; then
    sqlite3 confdb "create table dbase(name text, location text, data text)"
    echo "New database created."
    exit
    fi
   
    if [ "$name" = "defaults" ]; then
        for conf in $list; do
            if [ `echo $conf | head -c1` = "%" ]; then
                conf=`echo $conf | cut -b 1 --complement`
                location=`find /etc -name "$conf*" | head -1`
                loccontent=$(cat $location | sed "s/'/\'\'/g")
                sqlite3 confdb "insert into dbase values ('$conf','$location','${loccontent}')"
            else
                location=`find /home/$USER -name ".$conf*" | head -1`
                loccontent=$(cat $location | sed "s/'/\'\'/g")
                sqlite3 confdb "insert into dbase values ('$conf','$location','${loccontent}')"
            fi
        done
    fi
}

help () {
        echo '
    Please input the subject you want help
    on as the second argument!'
        case $name in
        add)
        echo '
    This command will add a new config file into the database
    syntax:
        confdb add bashrc /home/$user/.bashrc'
        ;;
        del)
        echo '
    This command will delete a config file from the database
    syntax:
        confdb del bashrc
        confdb del all'
        ;;
        upd)
        echo '
    This command will update a config file into the database
    syntax:
        confdb upd bashrc
        confdb upd all'
        ;;
        show)
        echo '
    This command will output a config file from the database
    syntax:
        confdb show bashrc
        confdb show all'
        ;;
        restore)
        echo '
    This command will restore the config file from the database into
    the file
    syntax:
        confdb rest bashrc
        confdb rest all'
        ;;
        create)
        echo '
    This command creates the database that stores the config files
    syntax:
        confdb create none
        confdb create defaults
   
    Note: "create defaults" will try to add config files into your data-
    base from the pre-defined list at the start of this script.
    It uses find, so it isnt entirely accurate and searches
    /home/$USER and /etc. Prepend your config-names with % if they
    are located in /etc.'
        ;;
        *)
        echo "invalid subject '$name'!"
        ;;
        esac
}

if [ $# -lt 2 ]; then
    noargs
fi

case $1 in
    add)
    add
    ;;
    del)
    delete
    ;;
    upd)
    update
    ;;
    show)
    show
    ;;
    rest)
    restore
    ;;
    create)
    createdb
    ;;
    help)
    help
    ;;
    *)
    echo "invalid first argument '$1'!"
    ;;
esac

This is my script that enables you to store your config files in a database. The code isn't probably the most elegant possible, but it works for me and that's that.

You can manually add config files by issuing

sh filename add bashrc /home/maiuser/.bashrc

Every other command works without the filename at the end.

sh filename del bashrc

You can use "all" instead of a specific config name to delete/etc. everything.

You can restore every config file from the database back into your filesystem if needed with a simple command.

If you want to automatically add the config files you want, just add them into the list-variable. It searches for the files in the users home directory and if you prepend the name with % it searches for them in /etc.

sh filename create defaults

You need to first create the database file with "sh filename create none".

It creates the database file into the directory that you run the script in. (Easy to change if you want to.)

I guess you can figure out the rest from the code, it's not that complicated.

Last edited by initbox (2009-09-08 07:32:26)

Offline

#507 2009-09-08 18:20:09

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

Re: Post your handy self made command line utilities

Hello.
First script create a file list with Installed packages and current time in your home dir smile.

  1 #!/bin/bash
  2 cd $HOME
  3 rm -r packages
  4 touch packages
  5 date >> packages
  6 pacman -Qqe >> packages
  7 cat packages

2nd script/alias is handy to go to upper dir it uses dmenu smile

alias up='cd "$(ls | dmenu -fn glisp -nb "#100" -nf "#b9c0af" -sb "#000" -sf "#afff2f" -i)"'

This viev list of dir in current dir and when you choose dir it go to it (It viev files to I don't know have to viev only dir sorry).


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

Offline

#508 2009-09-08 19:33:47

gladstone
Member
Registered: 2009-01-03
Posts: 74

Re: Post your handy self made command line utilities

SpeedVin wrote:
alias up='cd "$(ls | dmenu -fn glisp -nb "#100" -nf "#b9c0af" -sb "#000" -sf "#afff2f" -i)"'

This viev list of dir in current dir and when you choose dir it go to it (It viev files to I don't know have to viev only dir sorry).

You could do:

cd "$(ls -d */ | dmenu)"

or perhaps:

find . -maxdepth 1 -type d ! -name ".*" | dmenu

to display only directories

Last edited by gladstone (2009-09-08 19:43:42)

Offline

#509 2009-09-09 14:00:59

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

Re: Post your handy self made command line utilities

gladstone wrote:
SpeedVin wrote:
alias up='cd "$(ls | dmenu -fn glisp -nb "#100" -nf "#b9c0af" -sb "#000" -sf "#afff2f" -i)"'

This viev list of dir in current dir and when you choose dir it go to it (It viev files to I don't know have to viev only dir sorry).

You could do:

cd "$(ls -d */ | dmenu)"

or perhaps:

find . -maxdepth 1 -type d ! -name ".*" | dmenu

to display only directories

Ok first option helps me thatnk you gladstone.
Upated version of script:

alias up='cd "$(ls -d */ | dmenu -fn glisp -nb "#100" -nf "#b9c0af" -sb "#000" -sf "#afff2f" -i)"'

Last edited by SpeedVin (2009-09-09 18:59:09)


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

Offline

#510 2009-09-11 14:42:55

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

Re: Post your handy self made command line utilities

I wanted to keep notes about some of the songs in my music collection, but not use id3 tags or something like that, so here is a simple script to store notes in a single file.

It should work fine with a different command than mpc to get an identifier. And gvim is only used for the command line search switches to highlight and put the cursor at the right spot.

#! /bin/dash
#write music notes
#In the database notes are paragraphs where the first line is the identifier.
#usage:
#-i: print current song's notes
#-e: edit current/last note
#nothing: add/edit current note
#(depending on if the current song already has a note)
FILENAME=~/.musicnotes
identifier=$(mpc --format '%title% :: %album%' | head -n 1)
escape=$(echo "$identifier" | sed 's/[].^$*+?\\\/[]/\\&/g')

if [ x"$1" = x"-i" ]; then
  awk 'BEGIN{RS="";FS="\n"} { if ( $1 == "'"$identifier"'" ) { for (i=2;i<=NF;i++) print $i }}' $FILENAME
elif grep -F -q "$identifier" $FILENAME; then
  gvim -c "/$escape/" $FILENAME
elif [ x"$1" = x"-e" ]; then
  gvim -c '$' $FILENAME
else
  echo "" >> $FILENAME
  echo "$identifier" >> $FILENAME
  echo "" >> $FILENAME
  gvim -c "/$escape/" -c '$' -c 'start' $FILENAME
fi

edit: added an $escape variable with regex characters escaped so gvim can find it.

Last edited by Procyon (2009-09-12 12:45:17)

Offline

#511 2009-09-17 18:35:29

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

Re: Post your handy self made command line utilities

I just made a small change to my search script, it googles what ever you have highlighted, requires xsel and firefox.

more of a line then a script,  really

i have chenged it to use thge lmgtfy insted of just plain google. so it looks cooler big_smile 

#!/bin/bash
firefox "http://lmgtfy.com/?q=`xsel -p -o`&ie=UTF-8&oe=UTF-8"

i have it set to a hot key on my mouse, which is fun big_smile

Last edited by markp1989 (2009-09-17 18:37:32)


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

#512 2009-09-17 19:21:58

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

Re: Post your handy self made command line utilities

Script to download all xkcd comics, save in a "number-name" filename format, and use imagemagick to stick the title and alt-text into the image (above and below):

#!/bin/zsh

i=1
stop=-1

[ "$1" != "" ] && i=$1
[ "$2" != "" ] && stop=$2

[ -f index.html ] && rm index.html &>/dev/null

wget "http://www.xkcd.com/" &>/dev/null
endcomic=`md5sum index.html`
checksum=" "
rm index.html

while [[ $i != $stop ]] && [[ "$checksum" != "$endcomic" ]]; do
    if [[ $i != 404 ]]; then # There is no comic 404 ^^

        wget "http://www.xkcd.com/$i" &>/dev/null
        checksum=`md5sum index.html`

        file=`cat index.html | grep "img src.*comics" | sed "s/\(.*src=\"\|\".*\)//g"`
        wget "$file" &>/dev/null
        
        filename=`echo $file | sed "s/.*\///g"`
        name=`cat index.html | grep "h1" | sed "s/.*>\(.*\)<\/h.*/\\1/"`
        alt=`cat index.html | grep "img.*title=" | sed "s/\(.*title=\"\|\".*\)//g"`
        
        rm index.html &>/dev/null
        
        width=`identify "$filename" | sed "s/.* \([0-9]*\)x.*/\\1/"`
        height=`identify "$filename" | sed "s/.*x\([0-9]*\).*/\\1/"`
        
        convert -background black -fill white -size "$width"x16 -gravity center label:$name name.png
        convert -background black -fill white -size "$width"x   -gravity center -pointsize 13 caption:$alt alt.png
        
        altheight=`identify alt.png | sed "s/.*x\([0-9]*\).*/\\1/"`
        
        n=$i
        if [[ $i -lt 10 ]]; then
            n="00$i"
        elif [[ $i -lt 100 ]]; then
            n="0$i"
        fi
        
        if [[ ! -f "$n-$filename" ]]; then        
            convert -size "$width"x$[$height +  $altheight + 24] xc:white "$n-$filename"       
         
            composite -geometry "$width"x16+0+0 name.png "$n-$filename" "$n-$filename"
            composite -geometry "$width"x"$height"+0+20 $filename "$n-$filename" "$n-$filename"
            composite -geometry "$width"x"$altheight"+0+$[$height + 24] alt.png "$n-$filename" "$n-$filename"

            echo "Done $n-$filename"
        fi
        
        rm $filename name.png alt.png
    fi
    i=$[$i + 1]
done

$1 and $2 are, if specified, the start and stop comic numbers.

Last edited by Barrucadu (2009-09-17 19:24:20)

Offline

#513 2009-09-17 19:26:36

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

Re: Post your handy self made command line utilities

Barrucadu wrote:

Script to download all xkcd comics, save in a "number-name" filename format, and use imagemagick to stick the title and alt-text into the image (above and below):

#!/bin/zsh

i=1
stop=-1

[ "$1" != "" ] && i=$1
[ "$2" != "" ] && stop=$2

[ -f index.html ] && rm index.html &>/dev/null

wget "http://www.xkcd.com/" &>/dev/null
endcomic=`md5sum index.html`
checksum=" "
rm index.html

while [[ $i != $stop ]] && [[ "$checksum" != "$endcomic" ]]; do
    if [[ $i != 404 ]]; then # There is no comic 404 ^^

        wget "http://www.xkcd.com/$i" &>/dev/null
        checksum=`md5sum index.html`

        file=`cat index.html | grep "img src.*comics" | sed "s/\(.*src=\"\|\".*\)//g"`
        wget "$file" &>/dev/null
        
        filename=`echo $file | sed "s/.*\///g"`
        name=`cat index.html | grep "h1" | sed "s/.*>\(.*\)<\/h.*/\\1/"`
        alt=`cat index.html | grep "img.*title=" | sed "s/\(.*title=\"\|\".*\)//g"`
        
        rm index.html &>/dev/null
        
        width=`identify "$filename" | sed "s/.* \([0-9]*\)x.*/\\1/"`
        height=`identify "$filename" | sed "s/.*x\([0-9]*\).*/\\1/"`
        
        convert -background black -fill white -size "$width"x16 -gravity center label:$name name.png
        convert -background black -fill white -size "$width"x   -gravity center -pointsize 13 caption:$alt alt.png
        
        altheight=`identify alt.png | sed "s/.*x\([0-9]*\).*/\\1/"`
        
        n=$i
        if [[ $i -lt 10 ]]; then
            n="00$i"
        elif [[ $i -lt 100 ]]; then
            n="0$i"
        fi
        
        if [[ ! -f "$n-$filename" ]]; then        
            convert -size "$width"x$[$height +  $altheight + 24] xc:white "$n-$filename"       
         
            composite -geometry "$width"x16+0+0 name.png "$n-$filename" "$n-$filename"
            composite -geometry "$width"x"$height"+0+20 $filename "$n-$filename" "$n-$filename"
            composite -geometry "$width"x"$altheight"+0+$[$height + 24] alt.png "$n-$filename" "$n-$filename"

            echo "Done $n-$filename"
        fi
        
        rm $filename name.png alt.png
    fi
    i=$[$i + 1]
done

$1 and $2 are, if specified, the start and stop comic numbers.

wont that end up pissing xkcd of abit?

Last edited by markp1989 (2009-09-17 19:26:46)


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

#514 2009-09-17 20:07:13

gnud
Member
Registered: 2005-11-27
Posts: 181

Re: Post your handy self made command line utilities

Well, XKCD provides an url for hotlinking, and the comics are CC-BY-NC. So unless you do this every other day, I think it would be fine.

The script ought to add "http://xkcd.org" in the bottom corner as well, though.

Offline

#515 2009-09-17 20:42:48

colbert
Member
Registered: 2007-12-16
Posts: 809

Re: Post your handy self made command line utilities

markp1989 wrote:

I just made a small change to my search script, it googles what ever you have highlighted, requires xsel and firefox.

more of a line then a script,  really

i have chenged it to use thge lmgtfy insted of just plain google. so it looks cooler big_smile 

#!/bin/bash
firefox "http://lmgtfy.com/?q=`xsel -p -o`&ie=UTF-8&oe=UTF-8"

i have it set to a hot key on my mouse, which is fun big_smile

That is real neat, but my noob question is how do I use it? I just made it as highlight-google.sh in ~/scripts, so when I run it it just takes me to lmgtfy. Thanks big_smile smile

Offline

#516 2009-09-17 21:16:41

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

Re: Post your handy self made command line utilities

colbert wrote:
markp1989 wrote:

I just made a small change to my search script, it googles what ever you have highlighted, requires xsel and firefox.

more of a line then a script,  really

i have chenged it to use thge lmgtfy insted of just plain google. so it looks cooler big_smile 

#!/bin/bash
firefox "http://lmgtfy.com/?q=`xsel -p -o`&ie=UTF-8&oe=UTF-8"

i have it set to a hot key on my mouse, which is fun big_smile

That is real neat, but my noob question is how do I use it? I just made it as highlight-google.sh in ~/scripts, so when I run it it just takes me to lmgtfy. Thanks big_smile smile

you need to install xsel for the script to work sudo pacman -S xsel

i just have mine so it runs on when i press a spare button on my mouse.

Last edited by markp1989 (2009-09-17 21:18:42)


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

#517 2009-09-18 15:06:35

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

Re: Post your handy self made command line utilities

Huh... xkcd...

#!/bin/bash

#: xkcd downloader, which remains the mouse-hover comment

TMP='/tmp/xkcd.cURL.tmp'
XKCD='http://www.xkcd.com'
DIR="$HOME/comics/xkcd"   #Anywhere you want to store your xkcd comics. Create this by hand.
LOG='_xkcd.last'                 #This is put inside $DIR.

cd "$DIR" || exit 1

function grab()
{
idx=$1
url="$XKCD/$idx/" ; prev=$((idx-1)) ; next=$((idx+1))
curl -s "$url" -o "$TMP"
image=$(grep '<img src="http://imgs.xkcd.com/comics/' "$TMP" | sed 's|.*img src="\([^"]*\)".*|\1|')
name="$idx.${image/http:\/\/imgs.xkcd.com\/comics\//}"
alt=$(grep '<img src="http://imgs.xkcd.com/comics/' "$TMP" | sed 's|.*" alt="\(.*\)".*|\1|')
aria2c -o "$name" "$image" #or wget
echo '<html>' >> $idx.html
echo '<div align=center>'"$alt"'</div>' >> $idx.html
echo '<div align=left>' >> $idx.html
echo '<li><a href="'"$prev"'.html">< Prev</a></li>' >> $idx.html
echo '</div>' >> $idx.html
echo '<div align=center>' >> $idx.html
grep '<img src="http://imgs.xkcd.com/comics/' "$TMP" | sed 's|http://imgs.xkcd.com/comics/|'$idx'.|' >> $idx.html
echo '</div>' >> $idx.html
echo '<div align=right>' >> $idx.html
echo '<li><a href="'"$next"'.html">Next ></a></li>' >> $idx.html
echo '</div>' >> $idx.html
echo '</html>' >> $idx.html
}

if [ "$1" == '-v' ] ; then
    uzbl file://"$DIR"/${2:-1}.html  #or firefox
    exit
elif [ "$#" != '0' ] ; then
    for i in $@ ; do
        grab $i
    done
else
    [ -f "$LOG" ] && last=$(cat "$LOG") || last='1'
    latest=$(curl -s "$XKCD" | grep 'Permanent link to this comic' |
             sed s'|.*xkcd.com/\(.*\)/<.*|\1|')
    for ((idx=last;idx<=latest;idx++)) ; do
        [ -f $idx.html ] || grab $idx
    done
    echo $((latest+1)) > "$LOG"
    echo "==> Updated $last ~ $latest. Enjoy :)"
fi

So you basically:
1. Create your local xkcd directory manually, run this script without parameters, and you get all xkcd comics to date.
2. Run the script followed by "-v 638", and you are enjoying this comic about Kepler mission and delivery pizza. Yeah, uzbl!
3. Repeat step 1, and your local xkcd repo is synced again.

How it looks:
http://kimag.es/share/15663614.png

That's it. Enjoy.

Last edited by lolilolicon (2009-09-18 15:12:34)


This silver ladybug at line 28...

Offline

#518 2009-09-19 13:10:39

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

Re: Post your handy self made command line utilities

I updaed my packages.sh script!

1 #!/bin/bash
  2 LogDir=$HOME
  3 cd $LogDir
  4 if [ -e packages.log ]
  5 then
  6 rm -r packages.log
  7 touch packages.log
  8 date >> packages.log
  9 pacman -Qqe >> packages.log
 10 cat packages.log
 11 else
 12 touch packages.log
 13 date >> packages.log
 14 pacman -Qqe >> packages.log
 15 cat packages.log
 16 fi

And my new clean system script (Don't fear to use it I tested it on my own system).

  1 echo "This scripts will clean your system!"
  2 cd /var/log
  3 if [ -e mpd ]
  4 then
  5 cd $HOME
  6 sudo rm -rf /var/log/
  7 sudo mkdir /var/log
  8 cd /var/log
  9 sudo mkdir mpd
 10 cd /var/log/mpd
 11 sudo touch mpd.log
 12 echo "Cleaning Pacman Cache"
 13 sudo pacman -Scc
 14 else
 15 sudo rm -rf /var/log/
 16 sudo mkdir /var/log
 17 echo "Cleaning Pacman Cache"
 18 sudo pacman -Scc
 19 fi

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

Offline

#519 2009-09-19 14:08:35

rwd
Member
Registered: 2009-02-08
Posts: 643

Re: Post your handy self made command line utilities

SpeedVin wrote:

I updaed my packages.sh script!

1 #!/bin/bash
 (...)
  6 sudo rm -rf /var/log/
  7 sudo mkdir /var/log
 (...)
 19 fi

Why not:  sudo rm -rf /var/log/*

Last edited by rwd (2009-09-19 14:09:26)

Offline

#520 2009-09-19 14:46:47

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

Re: Post your handy self made command line utilities

rwd wrote:
SpeedVin wrote:

I updaed my packages.sh script!

1 #!/bin/bash
 (...)
  6 sudo rm -rf /var/log/
  7 sudo mkdir /var/log
 (...)
 19 fi

Why not:  sudo rm -rf /var/log/*

Nice Idea (Before I don't know how to remove all files in dir).
Thanks
Updated script:

  1 echo "This scripts will clean your system!"
  2 cd /var/log
  3 if [ -e mpd ]
  4 then
  5 cd $HOME
  6 sudo rm -rf /var/log/*
  7 #Depreaced remove dir method.
  8 #sudo rm -rf /var/log/
  9 #sudo mkdir /var/log
 10 cd /var/log
 11 sudo mkdir mpd
 12 cd /var/log/mpd
 13 sudo touch mpd.log
 14 echo "Cleaning Pacman Cache"
 15 sudo pacman -Scc
 16 cd $HOME
 17 touch delate.log
 18 sudo pacman -Qdt >> delate.log
 19 sudo pacman -Rdns | cat delate.log
 20 else
 21 cd $HOME
 22 sudo rm -rf /var/log/*
 23 #Depreaced remove dir method.
 24 #sudo rm -rf /var/log/
 25 #sudo mkdir /var/log
 26 echo "Cleaning Pacman Cache"
 27 sudo pacman -Scc
 28 cd $HOME
 29 touch delate.log
 30 sudo pacman -Qdt >> delate.log
 31 sudo pacman -Rdns | cat delate.log
 32 fi

Last edited by SpeedVin (2009-09-19 14:54:13)


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

Offline

#521 2009-09-19 14:47:54

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

Re: Post your handy self made command line utilities

even simpler might be

find /var/log -depth -mindepth 1 ! -name 'mpd*' -delete && pacman -Scc

/edit: a typo in that small ass post? wtf.

Last edited by brisbin33 (2009-09-19 14:48:52)

Offline

#522 2009-09-19 14:49:00

bluewind
Administrator
From: Austria
Registered: 2008-07-13
Posts: 165
Website

Re: Post your handy self made command line utilities

rm /var/log/* won't remove dotfiles. I think the find command would.


"Everything should be made as simple as possible, but not simpler."
-- Albert Einstein

Offline

#523 2009-09-19 14:58:36

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

Re: Post your handy self made command line utilities

i believe by default find -name avoids dot files (else . and .. would cause issues).  but would there really be any dotfiles in /var/log anyway?

Offline

#524 2009-09-19 15:00:45

bluewind
Administrator
From: Austria
Registered: 2008-07-13
Posts: 165
Website

Re: Post your handy self made command line utilities

Just a notice in case he wants to use that method somewhere else wink


"Everything should be made as simple as possible, but not simpler."
-- Albert Einstein

Offline

#525 2009-09-19 23:17:22

V for Vivian
Member
Registered: 2009-04-28
Posts: 52

Re: Post your handy self made command line utilities

Nothing serious from me.

I'm trying to decentralize my web usage and not use firefox for everything. This script lets me search stuff on the web on predefined sites. There are tokens for each site which must be prepended. When started without arguments it displays the selection of sites with zenity and opens the result with uzbl. One can also call it with the input as arguments and it will be loaded using lynx.

#!/bin/bash

# this lets you search for a term on predefined websites and 
# displays the result. the config file shall look like this:
# token sitename url
# where the sitename shall be one word. the searchterm within 
# the url shall be substituted with <term>. the userinput 
# shall look like this:
# token searchterm
# it can be used from command line by giving the userinput as  
# arguments or graphically (no arguments).

# config file
wsrc="$HOME/.websearchrc"

# input
if [ -z "$1" ]; then
  message="-"
  while read line; do
    token=`echo $line | cut -d' ' -f1`
    name=`echo $line | cut -d' ' -f2`
    message="$message $token:$name - "
  done < "$wsrc"
  input=$(zenity --entry --title "websearch" --text "$message")
else
  input="$*"
fi

# output
input_token=`echo $input | cut -d' ' -f1`
term=`echo $input | cut -d' ' -f2- | tr [:space:] +`
while read line; do
  token=`echo $line | cut -d' ' -f1`
  if [ "$input_token" == "$token" ]; then
    website=`echo $line | cut -d' ' -f3`
    url=`echo $website | sed "s/<term>/$term/"`
    if [ -z "$1" ]; then
      uzbl $url
    else
      lynx $url
    fi
    break
  fi
done < "$wsrc"

edit: fixed little bug. It could handle only one word as the search term when used from command line.

Here is my .websearchrc as an example.

m mahalo http://www.mahalo.com/search?q=<term>
w wikipedia http://en.wikipedia.org/wiki/Special:Search?search=<term>&go=Go
d dict http://www.dict.cc/?s=<term>
aw archwiki http://wiki.archlinux.org/index.php?title=Special%3ASearch&search=<term>&go=Go
aur AUR http://aur.archlinux.org/packages.php?O=0&K=<term>&do_Search=Go

The second one is even more silly. It plays a soundfile at specific times which must be given in a config file (like `date +%R` returns them). I did this as a replacement for the kinda defect schoolbell. I'm sure it could be done much easier.

#!/bin/bash

configfile="$HOME/scripts/own/gong/times"
soundfile="$HOME/scripts/own/gong/gong.mp3"

times=`cat $configfile`
time=`date +%R`

#synchronize
printf 'synchronizing... '
while [ "$time" == `date +%R` ]; do
  time=`date +%R`
  sleep 1
done
echo '[done]'

#start
echo running...
while [ 1 ]; do
  time=`date +%R`
  for line in $times; do
    if [ "$line" = "$time" ]; then 
      echo "it is $time"
      mpg123 -q $soundfile &
    fi
  done
  sleep 60
done

Last edited by V for Vivian (2009-09-20 09:26:53)


YES WE CAN
(but that doesn't necessarily mean we're going to)

Offline

Board footer

Powered by FluxBB