You are not logged in.

#801 2010-01-23 06:07:04

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

Re: Post your handy self made command line utilities

I prefer mpd.

sub mpdrand {
    my @songs = $mpd->collection->all_pathes;
    my @randoms = shuffle(@songs);
    $mpd->playlist->clear;
    $mpd->playlist->add(@randoms[0..29]);
    $mpd->random(1);
    $mpd->repeat(1);
    $mpd->play;
}

http://trapd00r.se/hacks/perl/ppc/

Last edited by dmz (2010-01-23 06:14:55)

Offline

#802 2010-01-24 09:41:45

siddhant
Member
Registered: 2008-07-29
Posts: 18
Website

Re: Post your handy self made command line utilities

I don't know if you'll call it a utility. But its pretty helpful at times (at least for me). big_smile

In ~/.bashrc

smiley() {
    val=$?
    if [ "$val" = "0" ]
    then
        echo ":-)"
    else
        echo ":-("
    fi
}

And

PS1='[\u@\h \W $(smiley)] \$ '

And the terminal window looks something like this.

[mango@arch ~ :-)] $ man woman
No manual entry for woman
[mango@arch ~ :-(] $

Last edited by siddhant (2010-01-24 09:42:16)

Offline

#803 2010-01-24 09:53:01

milomouse
Member
Registered: 2009-03-24
Posts: 940
Website

Re: Post your handy self made command line utilities

Speaking of "man"........ I wanted a quick way to view manpages and have the window close when I'm done, so.. here it is; a poorly scripted manpage selector. Done before, yeah. I originally wanted one through ratpoison and it worked for the most part but I couldn't figured out how to get tab-completion. I'll figure it out later. In the meantime, this has a small lag when first ran since I avoided a cache file. Knicked some of this from Ion, which is one feature I missed when moving away from it. Tried keeping it short without all the "for's" and "if=:'s". du works.

#!/bin/sh
# Simple manpage selector with dmenu.

DMENU="dmenu -b -fn -*-fixed-medium-r-normal-*-9 -nb #000 -nf #625873 -sb #a488d9 -sf #000"

CACHE=`du -a "/usr/share/man"|sed 's:^.*/\([^/]*\.[0-9].*\)$:\1:p; d'|\
sed 's:^\(.*\)\.[0-9].*$:\1:p; d'|sort -d|awk ' !x[$0]--' `

CHOICE=`echo -e "$CACHE" | $DMENU ${1+"$@"}` && exec urxvt -e man $CHOICE

Last edited by milomouse (2010-01-24 09:55:11)

Offline

#804 2010-01-24 10:26:18

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

Re: Post your handy self made command line utilities

BASH function that when run from a Linux source tree builds a User Mode Linux kernel and modules using the default config.
Installs UML to ~/bin, modules to ~/bin/uml_modules for later copying to root fs.

function uml {
    [ -e README ] || return
    [[ $( head -n 1 README ) =~ Linux\ kernel\ release\ 2.6.xx ]] || return
    make mrproper
    make mrproper ARCH=um
    make defconfig ARCH=um
    make -j 3 ARCH=um
    cp linux $HOME/bin/linux-$( ./linux --version )
    make modules_install INSTALL_MOD_PATH=$HOME/bin/uml_modules ARCH=um
}

Offline

#805 2010-01-24 12:32:51

scragar
Member
Registered: 2009-07-14
Posts: 108

Re: Post your handy self made command line utilities

I actually wrote these few tiny functions after a bit of an annoyance writing another script, so I present as is:

isset(){
  eval "test \"\${$1+set}\" = 'set'"
  return $?
}
ar_pop(){
  eval "TMP=\"\${${1}[\${#${1}[@]}-1]}\""
  eval "unset ${1}[\${#${1}[@]}-1]"
  echo $TMP
}
ar_push(){
  eval "${1}[\${#${1}[*]}]=\"$2\""
}
isEmpty(){
  return $( head -c 1 "$1" | wc -c )
}

And some sample usage:

## First, isset:
isset1=test
isset2=''
isset3=0
unset isset4
for i in isset{1..4}; do
  echo testing $i
  isset $i && echo SET || echo UNSET
done

## Then the array functionality

ARTEST=()
ar_push ARTEST 'Test 1'
ar_push ARTEST 'Test 2'
echo $(ar_pop ARTEST)
ar_push 'Test 3'
echo ${ARTEST[@]}

## And finally the isEmpty check.
FILE=$(mktemp)
isEmpty $FILE && echo made empty || echo made with content.
echo testing 123 > $FILE
isEmpty $FILE && echo still empty || echo now with content.
> $FILE
isEmpty $FILE && echo empty again || echo still got content.
rm $FILE

Offline

#806 2010-01-27 01:39:08

dsdeiz
Member
Registered: 2009-08-17
Posts: 69

Re: Post your handy self made command line utilities

Here's something that a friend of mine has made. The idea was actually taken from an existing script. This is to test which DNS service resolves faster (not sure if I got the terms correctly). The test made me transfer to Google's public DNS. More info here: http://xmodx.com/google-dns-vs-opendns/

#!/bin/sh
isp=$(dig +noall +stats 2>&1 | awk '$2~/^SERVER:$/{split($3,dnsip,"#");print dnsip[1]}');
m="-------------------------------------------------------------------------------";
s="                                                                               ";
h="+${m:0:25}+${m:0:12}+${m:0:12}+${m:0:12}+${m:0:12}+${m:0:12}+";
header=("Domain${s:0:23}" "Your ISP${s:0:10}" "Google${s:0:10}" "4.2.2.2${s:0:10}" "OpenDNS${s:0:10}" "DNS Adv.${s:0:10}");
echo "${h}";
echo "| ${header[0]:0:23} | ${header[1]:0:10} | ${header[2]:0:10} | ${header[3]:0:10} | ${header[4]:0:10} | ${header[5]:0:10} |";
echo "${h}";
for i in "xmodx.com" "yahoo.com" "google.com";
do
  ii="${i}${s:23}";
  echo -ne "| ${ii:0:23} |";
  for j in "${isp}"  "8.8.8.8"  "4.2.2.2" "208.67.222.222" "156.154.70.1";
  do
    r="${s:10}$(dig +noall +stats +time=9 @${j} ${i} 2>&1 | awk '$2~/^Query$/{print $4" "$5}')";
    echo -ne " ${r:${#r}-10} |";
  done
  echo -e "\n${h}";
done

Edit: Thanks for correcting steve___!

Last edited by dsdeiz (2010-02-03 13:08:38)

Offline

#807 2010-01-27 02:49:23

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

Re: Post your handy self made command line utilities

I think the last echo comment should be:

echo -e "\n${h}";

Offline

#808 2010-01-27 06:21:02

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

Re: Post your handy self made command line utilities

A small screen starter script for windows friends who wants to use irssi smile Well it became handy and started to use it myself, too. One problem needs some advise, the power-detach. It just kills (logout) the script, but not the login. Howto duplicate the logout signal or otherwise catch it and then in the script forward it to shell? Screen does not like to be backgrounded from the script with &.

#!/bin/bash
#

ME=$(whoami)
STATUS="0"

# Use screen ID of $1
if [[ $1 != "" ]]; then
   SCREEN_ID="$1"
   # special conf file for this ID
   if [ -f /home/$ME/.screenrc."$1" ];then
      SCREENRC="/home/$ME/.screenrc."$1""
   else
      SCREENRC="/home/$ME/.screenrc"
   fi
# Use the default screen ID
else
   SCREENRC="/home/$ME/.screenrc.irkki"
   SCREEN_ID="irkki"
   if [ ! -f /home/$ME/.screenrc.irkki ];then
      echo "Create ~/.screenrc.irkki from .screenrc first"
      exit 1
   fi
fi

# screen ID was not found
screen -ls | sed -ne 's/\t// p' | grep -qi "\.$SCREEN_ID" || STATUS="1"
# screen ID dead, restart
screen -ls | sed -ne 's/\t// p' | grep -i "\.$SCREEN_ID" | grep -qi "(dead.*\?)" && STATUS="2"
# attach the old one
screen -ls | sed -ne 's/\t// p' | grep -i "\.$SCREEN_ID" | grep -qi -e "(detached" -e "(attached" && STATUS="3"

if [[ $STATUS == "1" ]]; then
   screen -dmS "$SCREEN_ID" -c "$SCREENRC"
   screen -raAdS "$SCREEN_ID"
elif [[ $STATUS == "2" ]]; then
   screen -wipe "$SCREEN_ID"
   screen -dmS "$SCREEN_ID" -c "$SCREENRC"
   screen -raAdS "$SCREEN_ID"
elif [[ $STATUS == "3" ]]; then
   screen -raAdS "$SCREEN_ID"
elif [[ $STATUS == "0" ]]; then
   echo "I am confused...."
   echo ""
   screen -list
fi

exit 0

Last edited by Purch (2010-01-27 07:39:28)

Offline

#809 2010-01-28 00:51:40

Cyrusm
Member
From: Bozeman, MT
Registered: 2007-11-15
Posts: 1,053

Re: Post your handy self made command line utilities

Automatic screenshot uploader with bbcode generation output for posting screenshots on the forum.

it's still a work in progress, and could be coded more elegantly, but it works smile

#!/bin/bash
########################################
# File: shotgen.sh                     #
# Author: Cyrus Metcalf                #
# Date: 1/27/2010                      #
########################################
# Constants
FILE=`date +%b`scrot.png
THUMB=`date +%b`scrot-thumb.png
LINKFILE=`date +%b`links.txt
WALLDIR=<path to wallpapers>
WEBPAGE=<your webpage goes here>
SERVER=<your ssh enabled server name goes here>
########################################
# Perform the Screenshot and
# modify the files as necissary.

myscrot.pl 

cp $FILE $THUMB
mogrify -resize 20% $THUMB
read -p "Would you like to upload a wallpaper? (y/n):" 
if [[ $REPLY == "y" ]] ; then
    ls $WALLDIR
    read -p "enter wallpaper filename: " WALLPAPER 
    WALLPAPER=`ls $WALLDIR | grep $WALLPAPER`
    while [ $? -ne 0 ]
    do
        read -p "wallpaper name invalid, please try again: " WALLPAPER 
        WALLPAPER=`ls $WALLDIR | grep $WALLPAPER` 
    done
elif [[ $REPLY == "n" ]] ; then
    :
else
    echo "blank is an assumed no."
    
fi
scp $FILE $THUMB $WALLDIR/$WALLPAPER $SERVER
########################################
# Perform error checking and exit
# gracefully.

if [ $? -eq 0 ] ; then
    echo "Files loaded to esus."
    SHOTLINK="[url=$WEBPAGE/$FILE][img]$WEBPAGE/$THUMB[/img][/url]"
    WALLLINK="The Original [url=$WEBPAGE/$WALLPAPER]Wallpaper[/url]"
    echo "$SHOTLINK" > $LINKFILE
        echo "$WALLLINK" >> $LINKFILE
    echo "Links Created!"
else
    echo "File upload Failed!"
fi
rm $FILE $THUMB
exit 0

the myscrot.pl line can be replaced with whatever command-line scrot app you have, as long as it outputs in the form `date +%b`scrot.png


Hofstadter's Law:
           It always takes longer than you expect, even when you take into account Hofstadter's Law.

Offline

#810 2010-01-28 03:59:15

sen
Member
From: .de
Registered: 2007-02-18
Posts: 153
Website

Re: Post your handy self made command line utilities

I'm not sure if they fit into this category but I created some scripts for notify-osd that someone might find useful:

oss volume: vol-notify.sh

#!/bin/sh

# ossv4 volume osd for notify-osd
# depends on: notify-osd, ossvol
# v1.0 by sen

MIXER_CONTROL="vmix0-outvol"

if [ $1 = '-i' ]; then
    ossvol -i 1
elif [ $1 = '-d' ]; then
    ossvol -d 1
elif [ $1 = '-t' ]; then
    ossvol -t
else
    exit 1
fi
VOLUME=$(echo "$(printf "%02.0f" $(ossmix |grep $MIXER_CONTROL |awk '{ print $4 }'))*4" |bc)
if [ $VOLUME -eq 0 ]; then
    ICON=notification-audio-volume-muted
else
    if [ $VOLUME -lt 25 ]; then
        ICON=notification-audio-volume-off
    elif [ $VOLUME -lt 50 ]; then
        ICON=notification-audio-volume-low
    elif [ $VOLUME -lt 75 ]; then
        ICON=notification-audio-volume-medium
    else
        ICON=notification-audio-volume-high
    fi
fi
notify-send "Volume" -i $ICON -h int:value:$VOLUME -h string:x-canonical-private-synchronous:

pacman: pacman-updater.awk

#!/bin/awk -f

# pacman updater
# v1.1 sen

BEGIN {

    # -- define terminal -- #
    #term="terminator -n --geometry=930x530 -T 'Pacman Updater' -e"
    term="urxvt -e"
    
    
    # -- count updates -- #
    ANZ_CMD = "pacman -Qu | wc -l";
        ANZ_CMD | getline;
            pk_count = $0;
        close(ANZ_CMD);
    
    
    # -- no updates -- #
    if (pk_count == 0)
    {
        system("notify-send -i system-software-update -h string:x-canonical-private-synchronous: 'No Updates Available' '++++++++++++++++'");
        exit 1
    }
    
    # -- create package list -- #
    PAC_CMD = "pacman -Qu";
        for( i=0; i<pk_count; i++)
        {
            PAC_CMD | getline;
                pk_list= pk_list $1 " ";
                notify = notify $1 "-" $2 " "
        }
    close(PAC_CMD);
    
    # -- install updates -- #
    system("notify-send -i system-software-update 'Updating...' '" notify"'");
    system(term " 'yaourt -S " pk_list"'"); #--noconfirm for automatic updating
}

mpd / conky album art: mpd_infos.py

#!/usr/bin/env python
#------------------------------------------------#
#mpd notify-osd & cover linking for conky
#v1.2 sen
#------------------------------------------------#
#dependencies: python-mpd, (libnotify, notify-osd)
#------------------------------------------------#
import mpd,os,time
home = os.path.expanduser('~')

# settings
mpd_dir = '/mnt/music/'                            #mpd music directory
notify_osd = True                                #enable/disable notify-osd 
conky = False                                    #enable/disable conky cover linking
cover_default = '/home/sen/.icons/yamaha.svg'    #default cover for notify-osd
        
# notify-osd output
def notify(cover,artist,album,title):
    os.system('notify-send -i "%s" "%s" "%s\n%s"'%(cover,title,artist,album))

# look for cover
def coverPath():
    cover = cover_default
    
    # look in ~/.covers
    if os.path.exists('%s/.covers/%s-%s.jpg'%(home,artist,album)):
        cover = '%s/.covers/%s-%s.jpg'%(home,artist,album)
    
    # look in album dir
    else:
        for img in('cover.jpg', 'folder.jpg', 'front.jpg', 'album.jpg'):
            if os.path.exists('%s%s/%s'%(mpd_dir,os.path.dirname(last_song),img)):
                cover= '%s%s/%s'%(mpd_dir,os.path.dirname(last_song),img)
                break
    
    # link cover to /tmp for conky
    if conky == True:
        try:
            if os.path.exists('/tmp/cover'):
                os.system('rm /tmp/cover')
            if cover != cover_default:
                os.system('ln -s "%s" /tmp/cover'%cover)
        except:
            pass
            
    return cover

# mpd status message
def action(status):
    if status == 'play':
        bubble = 'notification-audio-play' + ' MPD Playing'
        notify(coverPath(),artist,album,title)
    elif status == 'pause':
        bubble = 'notification-audio-pause' + ' MPD Paused'
    else:
        bubble = 'notification-audio-stop' + ' MPD Stopped'
    os.popen('notify-send -u critical -h string:x-canonical-private-icon-only: -h string:x-canonical-private-synchronous: -i %s'%bubble)

# connect to MPD
success = False
while success == False:
    try:
        client = mpd.MPDClient()
        client.connect('localhost', 6600) 
        success = True
    except:
        print 'connection to MPD could not be established'
        time.sleep(5)
        success = False

try:
    last_song = client.currentsong()['file']
    last_status = client.status()['state']
    artist = client.currentsong()['artist']
    album = client.currentsong()['album']
    title = client.currentsong()['title']
    cover = coverPath()
    if notify_osd == True:
        notify(cover,artist,album,title)
    
except:
    last_song = ""
    last_status = ""

while True:
    try:
        currentsong = client.currentsong()['file']
        status = client.status()['state']
    except:
        currentsong = last_song
        status = last_status

    if last_status <> status:
        try:
            last_status = client.status()['state']
            if notify_osd == True:
                action(status)
        except:
            pass

    if last_song <> currentsong and status == 'play':
        try:
            last_song = client.currentsong()['file']
            try:
                artist = client.currentsong()['artist']
            except:
                artist = 'Unknown'
            try:
                album = client.currentsong()['album']
            except:
                album = 'Unknown'
            try:
                title = client.currentsong()['title']
            except:
                title = 'Unknown'
            cover = coverPath()
            if notify_osd == True:
                notify(cover,artist,album,title)
        except:
            pass
            
    time.sleep(1)

The volume and pacman scripts are useful if you bind them to multimedia keys on you keyboard.

Offline

#811 2010-01-28 19:27:13

drcouzelis
Member
From: Connecticut, USA
Registered: 2009-11-09
Posts: 4,092
Website

Re: Post your handy self made command line utilities

EDIT: See the responses from other people below for better ways to implement this. wink

I just finished making "move-follow" and "copy-follow" commands. I've always wanted them, but never got around to making them.

Move-follow ("mvf") will move files like the regular mv command, then change directory to the directory that you just moved the files to. So doing:

mvf *.jpg ~/Desktop

would be equivalent to:

mv *.jpg ~/Desktop
cd ~/Desktop

I'm sure you can figure out what "cpf" does. wink

Note: I am a professional programmer, but I am not a professional BASH programmer. sad Feel free to clean these up if you want.

# Move-follow command
function mvf {

  # If the move command fails
  # then just quit.
  if ! mv "$@"; then
    return
  fi

  # Go to the directory where you
  # moved the file to.
  eval last_arg=\$$#
  if [ -d "$last_arg" ]; then
    # The final parameter was a directory.
    cd "$last_arg"
  elif [ -e "$last_arg" ]; then
    # The final parameter was a file.
    # Get the directory that the file is in.
    eval last_arg=${last_arg%/*}
    cd "$last_arg"
  fi

  pwd
}

# Copy-follow command
# (See the move-follow command)
function cpf {

  if ! cp "$@"; then
    return
  fi

  eval last_arg=\$$#
  if [ -d "$last_arg" ]; then
    cd "$last_arg"
  elif [ -e "$last_arg" ]; then
    eval last_arg=${last_arg%/*}
    cd "$last_arg"
  fi

  pwd
}

Last edited by drcouzelis (2010-01-28 20:25:42)

Offline

#812 2010-01-28 19:44:50

lagagnon
Member
From: an Island in the Pacific...
Registered: 2009-12-10
Posts: 1,087
Website

Re: Post your handy self made command line utilities

I put this in /etc/cron.weekly to automatically update my system clock once per week. Install "rdate" from the AUR. Use a time server closer to your location - this one for Canada:

#!/bin/sh
#
rdate -s time.nrc.ca && hwclock -w

Philosophy is looking for a black cat in a dark room. Metaphysics is looking for a black cat in a dark room that isn't there. Religion is looking for a black cat in a dark room that isn't there and shouting "I found it!". Science is looking for a black cat in a dark room with a flashlight.

Offline

#813 2010-01-28 19:50:51

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

Re: Post your handy self made command line utilities

@drcouzelis: you should surround $@ in double quotes or it won't work with filenames with spaces.

Offline

#814 2010-01-28 20:05:07

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

Re: Post your handy self made command line utilities

drcouzelis wrote:

I just finished making "move-follow" and "copy-follow" commands. I've always wanted them, but never got around to making them.

Move-follow ("mvf") will move files like the regular mv command, then change directory to the directory that you just moved the files to. So doing:

mvf *.jpg ~/Desktop

would be equivalent to:

mv *.jpg ~/Desktop
cd ~/Desktop

I'm sure you can figure out what "cpf" does. wink

Note: I am a professional programmer, but I am not a professional BASH programmer. sad Feel free to clean these up if you want.

# Move-follow command
function mvf {

  # If the move command fails
  # then just quit.
  if ! mv $@; then
    return
  fi

  # Go to the directory where you
  # moved the file to.
  eval last_arg=\$$#
  if [ -d "$last_arg" ]; then
    # The final parameter was a directory.
    cd "$last_arg"
  elif [ -e "$last_arg" ]; then
    # The final parameter was a file.
    # Get the directory that the file is in.
    eval last_arg=${last_arg%/*}
    cd "$last_arg"
  fi

  pwd
}

# Copy-follow command
# (See the move-follow command)
function cpf {

  if ! cp $@; then
    return
  fi

  eval last_arg=\$$#
  if [ -d "$last_arg" ]; then
    cd "$last_arg"
  elif [ -e "$last_arg" ]; then
    eval last_arg=${last_arg%/*}
    cd "$last_arg"
  fi

  pwd
}

nice idea!

hope you don't mind i cleaned it up a bit:

goto() { [ -d "$1" ] && cd "$1" || cd "$(dirname "$1")"; }

cpf() { cp "$@" && goto "$_"; }

mvf() { mv "$@" && goto "$_"; }

not extensively tested but i think it works.

Offline

#815 2010-01-28 20:09:04

JohannesSM64
Member
From: Norway
Registered: 2009-10-11
Posts: 623
Website

Re: Post your handy self made command line utilities

Cleaner, but requires zsh:

mvf ()
{             
  if [[ -d $*[-1] ]]; then
    mv $* && cd $*[-1]
  elif [[ -d ${*[-1]%/*} ]]; then
    mv $* && cd ${*[-1]%/*}
  fi
}

edit: brisbin beat me to it tongue didn't think of dirname and $_.

Last edited by JohannesSM64 (2010-01-28 20:12:32)

Offline

#816 2010-01-28 20:40:42

drcouzelis
Member
From: Connecticut, USA
Registered: 2009-11-09
Posts: 4,092
Website

Re: Post your handy self made command line utilities

brisbin33 wrote:

nice idea! hope you don't mind i cleaned it up a bit. not extensively tested but i think it works.

Thanks, brisbin! It seems to work for me too.

Offline

#817 2010-01-28 22:02:47

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

Re: Post your handy self made command line utilities

brisbin33 wrote:

nice idea!

hope you don't mind i cleaned it up a bit:

goto() { [ -d "$1" ] && cd "$1" || cd "$(dirname "$1")"; }

cpf() { cp "$@" && goto "$_"; }

mvf() { mv "$@" && goto "$_"; }

not extensively tested but i think it works.

Nice! Great idea drcouzelis.

Offline

#818 2010-01-28 22:10:41

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

Re: Post your handy self made command line utilities

Very nice cleanup brisbin! I've wanted this for some time. I'll add it to my bashrc later smile

Offline

#819 2010-01-29 01:47:40

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

Re: Post your handy self made command line utilities

no very handy but could give someone a few lafs big_smile

just wrote this because i was bored, another small prank script smile

it types a random word as if you the user typed them you need a word list (can be a complete dictionary or just a list of swear words). you can find them online. just needs to be a plain text file with each word on its own line.

it requires xdotool

#!/bin/bash
while true; do
maxdelay=3000
mindelay=60
sleeptime=$(seq $mindelay $maxdelay| sort -R | head -n 1) 
wordlist=~/wordlist.txt
word1=$(sort -R "$wordlist" | head -n 1)
xdotool type " "$word1
echo waiting for $sleeptime seconds ##just in during testing, not needed.
sleep $sleeptime
done

Last edited by markp1989 (2010-01-29 02:02:38)


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

#820 2010-01-29 10:40:29

scragar
Member
Registered: 2009-07-14
Posts: 108

Re: Post your handy self made command line utilities

markp1989 wrote:

no very handy but could give someone a few lafs big_smile

just wrote this because i was bored, another small prank script smile

it types a random word as if you the user typed them you need a word list (can be a complete dictionary or just a list of swear words). you can find them online. just needs to be a plain text file with each word on its own line.

it requires xdotool

#!/bin/bash
while true; do
maxdelay=3000
mindelay=60
sleeptime=$(seq $mindelay $maxdelay| sort -R | head -n 1) 
wordlist=~/wordlist.txt
word1=$(sort -R "$wordlist" | head -n 1)
xdotool type " "$word1
echo waiting for $sleeptime seconds ##just in during testing, not needed.
sleep $sleeptime
done

Is there some reason you are continually randomly sorting the whole list, then picking a random entry, as opposed to something more like:

maxdelay=3000
mindelay=60
wordlist=~/wordlist.txt
wlen=$(wc -l "$wordlist")

rand(){
  min=$1
  max=$2
  [ $min = $max ] && echo $min && return 0
  echo $[ $RANDOM % ( $max - $min + 1 ) + $min ]
}

while true; do
  sleeptime=$(rand $mindelay $maxdelay)
  word1=$(head -n $(rand 1 $wlen) "$wordlist" | tail -n 1)
  xdotool type " ${word1}"
  sleep ${sleeptime}
done

This should reduce the load by quite a bit, as well as saving some time reading the whole file in every time it runs if you only need half the file on average.

Offline

#821 2010-01-29 13:50:29

zoqaeski
Member
From: /earth/australia/.
Registered: 2009-09-30
Posts: 132

Re: Post your handy self made command line utilities

With a little help from nice people on #archlinux (especially 'rson') I managed to sort my images into folders based on size:

#!/bin/bash

cd ~/wallpapers
for image in *;
do 
    dims=$(feh -ls $image | cut -f3,4 --output-delimiter=x | sed 's/WIDTHxHEIGHT//')
    echo $dims
    mkdir $dims &> /dev/null
    mv $image $dims
done

Offline

#822 2010-01-29 14:02:26

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

Re: Post your handy self made command line utilities

Thank you! I was looking for something like that!

I'll modify it to sort by aspect ratio instead of strict dims though. wink

Last edited by Daenyth (2010-01-29 14:02:54)

Offline

#823 2010-01-30 21:13:53

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

Re: Post your handy self made command line utilities

there are probably alot better ways of doing this...

This script  gets called by rtorrent when a download is complete, moves the downloads to the corect folder, then emails me to tell me.

if echo "$1" | grep -q '.iso$'; then

        mv "/media/torrents/downloading/$1" /media/torrents/DiskImages/ 
    folder=/media/torrents/DiskImages

elif echo "$1" | grep -q 'Chuck'; then

    season=`ls /media/torrents/tv/Chuck/| tail -n 1`
    mv "/media/torrents/downloading/$1" /media/torrents/tv/Chuck/$season/
        folder=/media/torrents/Chuck/$season/

elif echo "$1" | grep -q '24.S'; then

    season=`ls /media/torrents/tv/24/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/24/$season/
    folder=$/media/torrents/24/$season/

elif echo "$1" | grep -q 'House'; then

        season=`ls /media/torrents/tv/House/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/House/$season/
    folder=/media/torrents/tv/House/$season/

elif echo "$1" | grep -q 'South.Park'; then

        season=`ls /media/torrents/tv/Southpark/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/Southpark/$season/
    folder=/media/torrents/tv/Southpark/$season/
elif echo "$1" | grep -q 'Two.and.a.Half.Men'; then

        season=`ls /media/torrents/tv/TwoAndAHalfMen/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/TwoAndAHalfMen/$season/
    folder=/media/torrents/tv/TwoAndAHalfMen/$season/

elif echo "$1" | grep -q 'Lie.to.me'; then

        season=`ls /media/torrents/tv/LieToMe/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/LieToMe/$season/
    folder=/media/torrents/tv/LieToMe/$season/

elif echo "$1" | grep -q 'FlashForward'; then

        season=`ls /media/torrents/tv/FlashForward/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/LieToMe/$season/
    folder=/media/torrents/tv/LieToMe/$season/

elif echo "$1" | grep -q 'NCIS.Los.Angeles'; then

        season=`ls /media/torrents/tv/NCIS-LA/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/NCIS-LA/$season/
        folder=/media/torrents/tv/NCIA-LA/$season/

elif echo "$1" | grep -q 'NCIS'; then

        season=`ls /media/torrents/tv/NCIS/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/NCIS/$season/
        folder=/media/torrents/tv/NCIS/$season/

elif echo "$1" | grep -q 'Burn.Notice'; then

        season=`ls /media/torrents/tv/BurnNotice/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/Notice/$season/
        folder=/media/torrents/tv/BurnNotice/$season/

elif echo "$1" | grep -q 'TheITCroud'; then

        season=`ls /media/torrents/tv/TheITCroud/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/TheITCroud/$season/
        folder=/media/torrents/tv/TheITCroud/$season/

elif echo "$1" | grep -q 'Scrubs'; then

        season=`ls /media/torrents/tv/Scrubs/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/Scrubs/$season/
        folder=/media/torrents/tv/Scrubs/$season/

elif echo "$1" | grep -q 'The.Big.Bang.Theory'; then

        season=`ls /media/torrents/tv/TheBigBangTheory/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/TheBigBangTheory/$season/
        folder=/media/torrents/tv/Scrubs/$season/

elif echo "$1" | grep -q 'Human.Target'; then

        season=`ls /media/torrents/tv/HumanTarget/| tail -n 1`
        mv "/media/torrents/downloading/$1" /media/torrents/tv/HumanTarget/$season/
        folder=/media/torrents/tv/HumanTarget/$season/
else
    mv "/media/torrents/downloading/$1" /media/torrents/finished
    folder=/media/torrents/finished
fi 


echo -e "$(date) : $1 - Download completed. \n\nfile has been moved to $folder" | mail -s "[rtorrent] - Download completed : $1" myemail@address.com

any pointers welcome smile


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

#824 2010-01-30 21:30:20

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

Re: Post your handy self made command line utilities

Use the "case" statement. It should make that *much* more readable. Also inside the case block I'd set a variable for the target dir and then move the mv call outside so you only call mv once instead of having it in every block.

eg:

case $1 in
    *.iso) target=/media/torrents/DiskImages ;;
    *Chuck*) target="/media/torrents/Chuck/$(ls /media/torrents/tv/Chuck/| tail -n 1)" ;;
...
esac
mv "/media/torrents/downloading/$1" "$target"

Offline

#825 2010-01-30 21:40:29

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

Re: Post your handy self made command line utilities

Daenyth wrote:

Use the "case" statement. It should make that *much* more readable. Also inside the case block I'd set a variable for the target dir and then move the mv call outside so you only call mv once instead of having it in every block.

eg:

case $1 in
    *.iso) target=/media/torrents/DiskImages ;;
    *Chuck*) target="/media/torrents/Chuck/$(ls /media/torrents/tv/Chuck/| tail -n 1)" ;;
...
esac
mv "/media/torrents/downloading/$1" "$target"

thanks, that helps alot!!! its going to make it alot faster to add new shows etc to the list.

thankyou for your help  smile

here is how i hhave it so far, im gona have to test in , im thinking i mite have problems with ncis and ncis la getting mixed up i will find it out when i test it properly

case $1 in
        *.iso) target=/media/torrents/DiskImages ;;
        *Chuck*) target="/media/torrents/tv/Chuck/$(ls /media/torrents/tv/Chuck/| tail -n 1)" ;;
        24.S*) target="/media/torrents/tv/24/$(ls /media/torrents/tv/24/| tail -n 1)" ;;
        *House*) target="/media/torrents/tv/House/$(ls /media/torrents/tv/House/| tail -n 1)" ;;
        *South.Park*) target="/media/torrents/tv/Southpark/$(ls /media/torrents/tv/Southpark/| tail -n 1)" ;;
        *Two.and.a.Half.Men*) target="/media/torrents/tv/TwoAndAHalfMen/$(ls /media/torrents/tv/TwoAndAHalfMen/| tail -n 1)" ;;
        *Lie.to.me*) target="/media/torrens/tv/LieToMe/$(ls /media/torrens/tv/LieToMe/ | tail -n 1)" ;;
        *FlashForward*) target="/media/torrents/tv/FlashForward/$(ls /media/torrents/tv/FlashForward/| tail -n 1)" ;;
        *NCIS.L*) target="/media/torrents/tv/NCIS-LA/$(ls /media/torrents/tv/NCIS-LA/| tail -n 1)" ;;
        *NCIS*) target="/media/torrents/tv/NCIS/$(ls /media/torrents/tv/NCIS/| tail -n 1)" ;;
        *TheITCroud*) target="/media/torrents/tv/TheITCroud/$(ls /media/torrents/tv/TheITCroud/| tail -n 1)" ;;
        *Burn.Notice*) target="/media/torrents/tv/BurnNotice/$(ls/media/torrents/tv/BurnNotice/| tail -n 1)" ;;
        *Scrubs*) target="/media/torrents/tv/Scrubs/$(ls /media/torrents/tv/Scrubs/| tail -n 1)" ;;
        *The.Big.Bang.Theory*) target="/media/torrents/tv/TheBigBangTheory/$(ls /media/torrents/tv/TheBigBangTheory/| tail -n 1)" ;;
        *Human.Target*) target="/media/torrents/tv/HumanTarget/$(ls /media/torrents/tv/HumanTarget/| tail -n 1)" ;;
        *) target=/media/torrents/finished ;;
esac

mv "/media/torrents/downloading/$1" "$target"

#echo testing:
#echo "would move $1 to $target"


echo -e "$(date) : $1 - Download completed. \n\nfile has been moved to $target" | mail -s "[rtorrent] - Download completed : $1" my@email.com

edit: just did test on ncis and ncis la, both got put where they were ment to smile all seems good big_smile

Last edited by markp1989 (2010-01-31 23:47: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

Board footer

Powered by FluxBB