You are not logged in.

#201 2009-02-28 13:50:00

virtual
Member
From: Thesaloniki/Greece
Registered: 2006-10-17
Posts: 9

Re: Post your handy self made command line utilities

A script to control pidgin windows: moves either the buddy list or the chat window (i have only one with tabs) to your present desktop/workspace. Normally both of these windows live on my 3rd desktop and i move them to where i am with an openbox keyboard shortcut. If the window is already on the present desktop the script will move it back to its default desktop (3rd).
Requires wmctrl.

cat toggle_pidgin.sh

#!/bin/bash
# Modified:: 2009-02-28 15:41:55
# toggles moving the pidgin buddy list or the chat window 
# between desktop Gamma (3rd one - default for these) and the present desktop
# Requires wmctrl
# if $1 == --chat it refers to the chat window , otherwise the buddy list
# assumes that both the buddy list and the chat window exist 

# Usage: bind a keyboard shortcut to toggle_pidgin.sh and another one
# to toggle_pidgin.sh --chat

tmpf=/tmp/togglepidgin.$$
# first find out PID for pidgin
pid=`ps ux|grep pidgin|awk '$11 == "pidgin" {print $2}'`
# get all pidgin windows (normally buddylist and chat)
wmctrl -l -p |awk -v pid=$pid '$3 == pid' >$tmpf
buddylist=`cat $tmpf | grep Buddy | awk '{print $1}'`
buddylist_desk=`cat $tmpf |grep Buddy |awk '{print $2}'`
chat=`cat $tmpf | grep -v Buddy | head -1 |awk '{print $1}'`
chat_desk=`cat $tmpf | grep -v Buddy | head -1 |awk '{print $2}'`
echo "$buddylist" "$chat"
# find out current desktop
curdesktop=`wmctrl -d |awk '$2 == "*" {print $1}'`
# echo $curdesktop

if [ "$1" == "--chat" ]; then
    # toggling the chat window only
    if [ "${chat_desk}" == "$curdesktop" ]; then
        # move chat to desktop Gamma
        wmctrl -i -r $chat -t 2
    else
        # move chat to current desktop and raise
        wmctrl -i -R $chat
    fi
else
    # working with the buddy list only
    if [ "${buddylist_desk}" == "$curdesktop" ]; then
        # move buddylist to Gamma
        wmctrl -i -r $buddylist -t 2
    else
        wmctrl -i -R $buddylist
    fi
fi

rm $tmpf

Offline

#202 2009-03-01 14:25:00

Wintervenom
Member
Registered: 2008-08-20
Posts: 1,011

Re: Post your handy self made command line utilities

dmenu launcher that displays the friendly names instead of the executable names for applications.

#!/bin/sh
apps='/usr/share/applications'
dmen="dmenu -i -b -fn '-*-terminus-*-r-normal-*-*-120-*-*-*-*-iso8859-*' -nb #000000 -nf #9999CC -sb #000066"
name=$(grep -h "^Name=" $apps/*.desktop | sed 's:Name=::' | $dmen)

if [[ "$name" != "" ]]; then
    dfile=$(grep -l "^Name=$name$" $apps/*.desktop)
    if [[ $(echo "$dfile" | wc -l) > 1 ]]; then
        dfile="$apps/$(echo -e "$dfile" | sed "s:${apps}/::" | $dmen -p "Which $name?")"
    fi
    xdg-open $dfile
fi

Here's another version that combines both friendly and executable names:

#!/bin/sh
apps='/usr/share/applications'
dmen="dmenu -i -b -fn '-*-terminus-*-r-normal-*-*-120-*-*-*-*-iso8859-*' -nb #000000 -nf #9999CC -sb #000066"
name=$(echo -e "$(grep -h "^Name=" $apps/*.desktop | sed 's:Name=::')\n$(dmenu_path)" | $dmen)

if [[ "$name" != "" ]]; then
    dfile=$(grep -l "^Name=$name$" $apps/*.desktop)
    if [ $dfile ]; then
        if [[ $(echo "$dfile" | wc -l) > 1 ]]; then
            dfile="$apps/$(echo -e "$dfile" | sed "s:${apps}/::" | $dmen -p "Which $name?")"
        fi
        xdg-open "$dfile"
    else
        which "$name" &> /dev/null && exec "$name" &
    fi
fi

My shell script skills aren't that clean, so if there's a more efficient way to write those, I'd like to hear the corrections.  tongue

Last edited by Wintervenom (2009-03-02 20:07:37)

Offline

#203 2009-03-02 18:45:44

mazzarelli
Member
Registered: 2008-08-27
Posts: 6

Re: Post your handy self made command line utilities

#!/bin/bash

CURR=$(xdotool getactivewindow)
BROWSER=$(xdotool search --onlyvisible --title 'Gran Para')
xdotool windowfocus $BROWSER && xdotool key F5
xdotool windowfocus $CURR

This will refresh the current tab in firefox, then give the focus back to the window you were in.

I assigned a global shortcut to F7, and can refresh Firefox without having to reach for the mouse or use alt+tab to change windows. Very convenient when doing web development.

Requires xdotool, and assumes the title of the window contains the string 'Gran Paradiso' in it.

Offline

#204 2009-03-06 22:51:44

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

Re: Post your handy self made command line utilities

; pkg-depends.scm
;
; simple chicken scheme program that generates a dot dependency graph.
; usage: pkg-depends [pkg1] .. [pkgN]
;
; compile with 'csc pkg-depends.scm'
;
(use posix regex extras srfi-1)

(define *db-path* "/var/lib/pacman/local")
(define *graph-style* '())
(define *style* "[color=black]")

(let ((conf-file (string-append (getenv "HOME") "/.config/pkg-depends.conf")))
    (if (file-exists? conf-file)
        (load conf-file)))

(define *deps* (make-hash-table))
(define (pkg-name-pattern name)
    (regexp (string-append "^" name "-[^A-Za-z]+-[0-9]+$")))

(define *pacman-db* (directory *db-path*))
(define field-sep (regexp "[<>=]+"))

(define (depends-file name)
    (string-append *db-path* "/" (find-pkg name) "/depends"))

(define (find-pkg name)
    (call/cc
        (lambda (return)
            (let ((pkg-pattern (pkg-name-pattern name)))
                (begin
                    (for-each (lambda (s)
                                            (if (string-match pkg-pattern s)
                                                    (return s))
                                                    #f)
                                        *pacman-db*)
                     name)))))

(define (get-deps name)
    (call/cc 
        (lambda (break)
                (let ((dep-file (depends-file name)))
                    (define (clean-names li)
                        (map (lambda (s)
                                     (car (string-split-fields field-sep s #:infix)))
                                 li))
                    (if (file-exists? dep-file)
                        (clean-names 
                                     (get-field "%DEPENDS%" (read-lines dep-file)))
                        (break '()))))))

(define (build-table name)
    (if (not (hash-table-exists? *deps* name))
        (begin 
            (let ((deps (get-deps name)))
                (hash-table-set! *deps* name deps)
                (for-each build-table deps)))))

(define (get-field field data)
    (cond ((eq? data '()) '())
                ((string=? field (car data))
                 (take-while (lambda (s) (not (= (string-length s) 0))) (cdr data)))
                (else (get-field field (cdr data)))))

(define (gen-dot)
    (begin
        (print "digraph deps {")
        (for-each print *graph-style*)
        (for-each (lambda (pkg)
                                (print (string-append "\"" pkg "\"" *style*)))
                            (command-line-arguments))
        (for-each (lambda (pkg)
                                (for-each 
                                    (lambda (dep) 
                                        (print (string-append "\t\"" pkg "\" -> \"" dep "\""))) 
                                    (hash-table-ref *deps* pkg)))
                            (hash-table-keys *deps*))
        (print "}")))

(for-each build-table (command-line-arguments))
(gen-dot)

I'm playing around with scheme and wrote (yet another) dependency graph printer, but it's quite a bit faster than the bash script it's replacing.

This is the generated dependency graph for mpd.
mpd.jpg

edit: updated after I did some profiling and I added support for a config file for changing the graph output.

Last edited by scj (2009-03-07 17:15:02)

Offline

#205 2009-03-06 23:04:38

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

Re: Post your handy self made command line utilities

How does it compare with pactree?

Offline

#206 2009-03-06 23:38:14

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

Re: Post your handy self made command line utilities

time pkg-depends moonlight | dot -Tpng -ompd.png

pkg-depends moonlight  0.05s user 0.01s system 58% cpu 0.097 total
dot -Tpng -ompd.png  1.43s user 0.08s system 79% cpu 1.891 total

pkg-depends moonlight  0.04s user 0.01s system 61% cpu 0.093 total
dot -Tpng -ompd.png  1.43s user 0.10s system 90% cpu 1.688 total

pkg-depends moonlight  0.05s user 0.01s system 60% cpu 0.094 total
dot -Tpng -ompd.png  1.39s user 0.10s system 87% cpu 1.699 total

time ./pactree.sh -g moonlight

./pactree.sh -g moonlight  5.18s user 2.18s system 88% cpu 8.289 total
scj@~/code/scheme$ time ./pactree.sh -g moonlight
./pactree.sh -g moonlight  5.22s user 2.10s system 90% cpu 8.099 total
scj@~/code/scheme$ time ./pactree.sh -g moonlight
./pactree.sh -g moonlight  5.27s user 2.03s system 89% cpu 8.127 total

edit: updated after profiling.

Last edited by scj (2009-03-07 17:18:35)

Offline

#207 2009-03-07 00:46:13

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

Re: Post your handy self made command line utilities

Heller_Barde wrote:

I wrote a small script to make urls tiny quickly. dependencies are curl and xclip (for convenience)
there are two possible ways to use this:
1. copy an url to the X clipboard, run the script (e.g. through a hotkey) and immediately paste the tinyurl again. smile
2. pass an URL as the first and only argument and tadaa, there is the tinified url on STDOUT (and also in the clipboard)

#!/bin/sh
#
# title: tinify
# author: Philip Stark
# desc:  pass an url as the first and only argument to make it tiny or 
#        leave it away and it takes the content of the clipboard by
#        calling xclip. 
# licenced under the WTFPL (http://sam.zoy.org/wtfpl/)
 
if [ "$1" = "" ]; then
  tinyurl=$(curl http://tinyurl.com/api-create.php?url=$(xclip -selection clipboard -o) 2> /dev/null)
  echo $tinyurl;
  echo $tinyurl | xclip -selection clipboard -i;
else
  url=$1;
  tinyurl=$(curl http://tinyurl.com/api-create.php?url=${url} 2> /dev/null)
  echo $tinyurl;
  echo $tinyurl | xclip -selection clipboard -i;
fi

version without xclip dependency (to keep it simple wink ):

#!/bin/sh
# title: tinify
# author: Philip Stark
# desc:  pass an url as the first and only argument to make it tiny or 
#        leave it away and it takes the content of the clipboard by
#        calling xclip. 
# licenced under the WTFPL (http://sam.zoy.org/wtfpl/)
[ "$1" == "" ] && echo "Usage: tinify url" && exit
url=$1;
tinyurl=$(curl http://tinyurl.com/api-create.php?url=${url} 2> /dev/null)
echo $tinyurl;

have fun
cheers Barde

that is quite cool, thanks for uplloading big_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

#208 2009-03-07 03:17:27

Fingel
Member
Registered: 2009-02-28
Posts: 98

Re: Post your handy self made command line utilities

Hey all. Kind of a coincidence, but I just recently started a webpage where I post useful little shell scripts and such that I find. If you guys think its a good idea, I'll expand the website so that peopel can submit their own (right now its just html) Let me know what you think:

http://www.toxiccode.com/index.html

Here is a cowsay script, except it uses a random cowfile each time:

rancow.png

#!/bin/bash
cows=(apt beavis.zen bong bud-frogs bunny cheese cower daemon default dragon dragon-and-cow elephant elephant-in-snake eyes flaming-sheep ghostbusters hellokitty kitty koala kosh luke-koala mech-and-cow meow milk moofasa moose mutilated ren satanic sheep skeleton small stegosaurus stimpy supermilker surgery three-eyes turkey turtle tux udder vader vader-koala www)
random=RANDOM%44
col="\033[1;34m";
norm="\033[0;39m";
echo -e -n $col;
cowsay -f ${cows[random]} `fortune`
echo -e -n $norm;

Offline

#209 2009-03-07 12:55:39

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

Re: Post your handy self made command line utilities

Fingel wrote:

Hey all. Kind of a coincidence, but I just recently started a webpage where I post useful little shell scripts and such that I find.

We kind of already have one, but not many people are posting to it.  http://scriptwiki.twilightlair.net/


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

Offline

#210 2009-03-07 22:03:39

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

Re: Post your handy self made command line utilities

Here's my version of the filetype-agnostic extractor... Dependencies are pacman, bzip2, gzip, p7zip. It also supports tar, gzip, bzip2, cpio, zip, 7zip, rar. Probably others as well..

ex() {
    for file in "$@"; do
        if [ -f "$file" ]; then
            local file_type=$(file -bizL "$file")
            case "$file_type" in
                *application/x-tar*|*application/zip*|*application/x-zip*|*application/x-cpio*)
                    bsdtar -x -f "$file" ;;
                *application/x-gzip*)
                    gunzip -d -f "$file" ;;
                *application/x-bzip*)
                    bunzip2 -f "$file" ;;
                *application/x-rar*)
                    7z x "$file" ;;
                *application/octet-stream*)
                    local file_type=$(file -bzL "$file")
                    case "$file_type" in
                        7-zip*) 7z x "$file" ;;
                        *) echo -e "Unknown filetype for '$file'\n$file_type" ;;
                    esac ;;
                *)
                    echo -e "Unknown filetype for '$file'\n$file_type" ;;
            esac
        else
            echo "'$file' is not a valid file"
        fi
    done
}

Last edited by Daenyth (2009-03-07 22:59:17)

Offline

#211 2009-03-08 13:56:32

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

Re: Post your handy self made command line utilities

mazzarelli wrote:
#!/bin/bash

CURR=$(xdotool getactivewindow)
BROWSER=$(xdotool search --onlyvisible --title 'Gran Para')
xdotool windowfocus $BROWSER && xdotool key F5
xdotool windowfocus $CURR

This will refresh the current tab in firefox, then give the focus back to the window you were in.

I assigned a global shortcut to F7, and can refresh Firefox without having to reach for the mouse or use alt+tab to change windows. Very convenient when doing web development.

Requires xdotool, and assumes the title of the window contains the string 'Gran Paradiso' in it.

thanks for that, i tied it to my F4 key, so now i can scroll  and refresh without changing windows big_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

#212 2009-03-08 17:25:24

luggi
Member
From: Berlin - Germany
Registered: 2008-04-26
Posts: 30

Re: Post your handy self made command line utilities

hi!

I use this to automatically rename and organize my music (works only for mp3s and flac...)
it's probably very ugly code tongue (I'm quite new to scripting in general)
it would be nice if someone could tell me how to improve it!

#!/bin/sh
#auto_organize - a that script renames music files according to artist, album, title and track number tags

MUSIC_DIR=/home/luggi/Musik

for i in "$@"; do 

    # check for file type
    if (ls "$i" | grep flac) 
    then
                  # extract information from flac tag
        ARTIST=$(metaflac --show-tag=ARTIST "$i" | sed -e s/ARTIST=//) 
        ALBUM=$(metaflac --show-tag=ALBUM "$i" | sed -e s/ALBUM=//)
        TITLE=$(metaflac --show-tag=TITLE "$i" | sed -e s/TITLE=//)
        TRACK_NUM=$(metaflac --show-tag=TRACKNUMBER "$i" | sed -e s/TRACKNUMBER=//)
        DISC_NUMBER=$(metaflac --show-tag=DISCNUMBER "$i" | sed -e s/DISCNUMBER=//)

        
        #check if disc number is included
        if [ -z "$DISC_NUMBER" ]
        then
            RENAMING_SCHEME="$MUSIC_DIR/$ARTIST/$ALBUM/$TRACK_NUM $TITLE.flac"
        else
            RENAMING_SCHEME="$MUSIC_DIR/$ARTIST/$ALBUM/$DISC_NUMBER - $TRACK_NUM $TITLE.flac"
        fi
                            
                            echo "$RENAMING_SCHEME"

        mkdir -p "$MUSIC_DIR/$ARTIST/$ALBUM/"
        cp -vi "$i" "$RENAMING_SCHEME"

    elif (ls "$i" | grep mp3)
    then
        # extract information from mp3 tag
        ARTIST=$(mp3info -p %a "$i")
        ALBUM=$(mp3info -p %l "$i")
        TITLE=$(mp3info -p %t "$i")
        TRACK_NUM=$(mp3info -p %02n "$i")

                            # check if disc number is included
        if [ -z "$DISC_NUMBER" ]
        then
            RENAMING_SCHEME="$MUSIC_DIR/$ARTIST/$ALBUM/$TRACK_NUM $TITLE.mp3"
        else
            RENAMING_SCHEME="$MUSIC_DIR/$ARTIST/$ALBUM/$DISC_NUMBER - $TRACK_NUM $TITLE.mp3"
        fi

                            echo "$RENAMING_SCHEME"

        mkdir -p "$MUSIC_DIR/$ARTIST/$ALBUM/"
        cp -vi "$i" "$RENAMING_SCHEME"
    fi
done

Offline

#213 2009-03-08 18:51:09

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

Re: Post your handy self made command line utilities

audiotag is handy for that

Offline

#214 2009-03-08 19:10:24

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

Re: Post your handy self made command line utilities

List the upgraded/removed/installed packages that have daemons. Just to list things so you remember act upon changes.

#!/bin/bash

# last days to be included from the logs
LOGDAYS=1
LOGFILE=/var/log/pacman.log

#### END OF CONFIG #####
########################
declare -a LOG

# lets get last 7 days from pacman.log
WEEKDATE=$(date --date=@$(days=$(date +%s) && echo $((days-(60*60*24*LOGDAYS)))) +%Y-%m-%d)

IFS='
'

echo "Parsing log file ..."
LOG=( $(sed -n '/'"^\[$WEEKDATE"'/,$p' $LOGFILE | grep -e upgraded -e installed) )

echo "These packages including daemons may have been modified in $LOGDAYS days"
echo
LINES=${#LOG[@]}
declare -i INDEX=0

while [ $INDEX -lt $LINES ];do
    unset IFS
    FOUND=FALSE
    RUNNING=FALSE
    GHOST_RUNNING=FALSE
    OUTPUT=""
    TEMPLINE=( ${LOG[$INDEX]} )
    #echo ${TEMPLINE[@]}
    
    DATE=$( echo ${TEMPLINE[0]} | sed 's#\[##')
    TIME=$( echo ${TEMPLINE[1]} | sed 's#\]##')
    ACTION=${TEMPLINE[2]}
    PACKAGE=${TEMPLINE[3]}
    VERSION_FROM=$(echo "${TEMPLINE[4]}" | sed -e 's#(##g' -e 's#)##g')
    VERSION_TO=$(echo ${TEMPLINE[6]} | sed -e 's#(##g' -e 's#)##g')
    
    let INDEX++
    
    if [[ "$ACTION" == "upgraded" ]] || [[ "$ACTION" == "installed" ]];then
        PACKAGE_DAEMON=( $(pacman -Ql $PACKAGE | grep "/etc/rc.d/.") )
        [ $? == "0" ] && FOUND=TRUE

        if [[ $ACTION == "upgraded" && $FOUND == "TRUE" ]];then
            DAEMON_STATE=$(ls -1 --color=none /var/run/daemons | grep $(basename $(echo ${PACKAGE_DAEMON[1]})))
            [ $? == "0" ] && RUNNING=TRUE
        fi

        [ "$FOUND" == "TRUE" ] && OUTPUT=$(echo $DATE $TIME $ACTION $PACKAGE)
        [ "$RUNNING" == "TRUE" ] && OUTPUT=$(echo -e "$OUTPUT\033[1m ${PACKAGE_DAEMON[1]} daemon alive\033[0m" )
        [ -n "$OUTPUT" ] && echo $OUTPUT
    fi
done

# check ghost daemons
IFS='
'
OUTPUT=""
RCD=$(ls -1 --color=none /etc/rc.d/)
RUNNING=$(ls -1 --color=none /var/run/daemons/)
for i in ${RUNNING[@]};do
    echo ${RCD[@]} | grep -q "$i"
    [ $? != "0" ] && OUTPUT=$(echo $OUTPUT $i)
done
[ -n "$OUTPUT" ] && echo "Following daemons are running without their daemon script" && echo "   $OUTPUT"

exit 0

Offline

#215 2009-03-08 20:36:13

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

Re: Post your handy self made command line utilities

rson451 wrote:

A little script I wrote because migrating my webserver gave me a headache because of some permissions issues.

A quick bash version:

#!/bin/bash
# list directory permissions along the path

if [ -n "$1" ];then
        dirpath=$1
else
        dirpath=$(pwd)
fi

IFS='/'

for part in $dirpath;do
        unset IFS
        grow="$grow""$part""/"
        ls -asld --color --time-style=long-iso $grow | cut -d ' ' -f 2,4,5,9
done

exit 0

Offline

#216 2009-03-08 21:22:56

luggi
Member
From: Berlin - Germany
Registered: 2008-04-26
Posts: 30

Re: Post your handy self made command line utilities

@ Daenyth: thanks!

Offline

#217 2009-03-09 00:26:23

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

Re: Post your handy self made command line utilities

Nice.  I started this in bash but was convinced it would be easierr to add 'features' if it was python.  Nice work.

Last edited by rson451 (2009-03-09 00:26:41)


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

Offline

#218 2009-03-10 01:51:17

dmlawrence
Member
Registered: 2008-10-01
Posts: 21

Re: Post your handy self made command line utilities

Here's a one-liner (well, almost a one-liner) that backs up my main hard drive to a backup drive, mounts the backup drive if it's not already mounted, and exits gracefully if the drive is not present.  It does not depend on udev's device naming behavior.  Note that the options for the rsync command do NOT delete files that have been removed from the main hard drive.

name=dml-drive
mnt=/mnt/wd

grep $mnt /etc/mtab || mount /dev/disk/by-label/$name $mnt && rsync -avx / $mnt

Offline

#219 2009-03-11 17:37:47

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

Re: Post your handy self made command line utilities

atq with just time and the actual job

First sudo chmod o+rx /var/spool/atd

#! /bin/bash
for file in /var/spool/atd/*; do
[ ! -f "$file" ] && echo no atd jobs && exit
echo -n $(date -d @$(awk -W non-decimal-data '{print $1*60}' <<< "0x$(cut -b22- <<< $file)") '+%a %k:%M:')" "
sed -n '/}/{n;p}' "$file"
done

Edit: Nicer checking of no files, thanks Daenyth.

Last edited by Procyon (2009-03-11 18:15:01)

Offline

#220 2009-03-11 17:52:15

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

Re: Post your handy self made command line utilities

Procyon wrote:
[ $file = /var/spool/atd/\* ] && echo no atd jobs && exit

I'd do instead

[ ! -f "$file" ] && echo "no atd jobs" && exit

Offline

#221 2009-03-11 18:02:43

thefatprecious
Member
From: Austin, TX
Registered: 2009-02-13
Posts: 98

Re: Post your handy self made command line utilities

A small script to alternatively get space usage.

#!/bin/bash

USED=`df -Pkl | awk '/^\/dev\// { used += $3/(1024*1024) } END { printf("%d GB Used\n", used)} '`

AVAIL=`df -Pkl | awk '/^\/dev\// { Available += $4/(1024*1024) } END { printf("%d GB Available\n", Available)} '`

echo "$USED space and $AVAIL space" ;

echo "Percent Used:" ;
echo "scale=1;(`echo $USED | awk '{print $1}'`/`echo $AVAIL | awk '{print $1}'` * 100)" | bc ;
176 GB Used space and 379 GB Available space
Percent Used:
40.0

which works but is there a simpler way to have done this?

EDIT: i didn't realize I was miscalcluating my percentage. Per a tip from Procyon, the percent is now the following:

echo "Percent Used:" ;
df -Pkl | awk '/^\/dev\// { used+=$3; size+=$2 } END { CONVFMT="%d";OFMT="%d"; print used/size*100"%" }'

Thanks again!

Last edited by thefatprecious (2009-03-11 18:15:43)


ILoveCandy

Offline

#222 2009-03-11 18:10:26

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

Re: Post your handy self made command line utilities

@Daenyth: Good idea. You know I find it really silly bash puts that * there.

Offline

#223 2009-03-11 18:20:20

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

Re: Post your handy self made command line utilities

You could do that all with one awk script. (Or perl, since I'm more comfortable with that...)

df -Pkl | perl -ane '
if (m|^/dev/|) { $total += $F[1]; $used += $F[2] }
}{ printf "%0.2f GB used out of %0.2f GB total\n%0.1f%% used\n", $used / 1024**2, $total / 1024**2, $used / $total * 100;'

Last edited by Daenyth (2009-03-11 18:34:50)

Offline

#224 2009-03-11 18:27:05

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

Re: Post your handy self made command line utilities

Procyon wrote:

@Daenyth: Good idea. You know I find it really silly bash puts that * there.

http://wooledge.org:8000/BashFAQ/004

Offline

#225 2009-03-11 18:42:21

thefatprecious
Member
From: Austin, TX
Registered: 2009-02-13
Posts: 98

Re: Post your handy self made command line utilities

@Daenyth: Thanks that's pretty neat. So in my case I was looking for available space as in Free space available....so I would do:

df -Pkl | perl -ane '
if (m|^/dev/|) { $total += $F[1]; $avail += $F[3]; $used += $F[2] }
}{ printf "%0.2f GB used with %0.2f GB available\n%0.1f Percent used\n", $used / 1024**2, $avail / 1024**2, $used / $total * 100;'

ILoveCandy

Offline

Board footer

Powered by FluxBB