You are not logged in.

#926 2010-03-21 03:25:41

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

Re: Post your handy self made command line utilities

GraveyardPC wrote:

Something fun, a terminal screensaver based on pipes:...

That is cool.  Very clever.


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

Offline

#927 2010-03-21 03:28:09

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

Re: Post your handy self made command line utilities

Basic internet connection script.  I've been using LXDE NeworkManager-like net connector and it isn't always reliable so I just typed this up.  I know it may seem simple but I remember when I first started Linux and got lost in a networking nightmare (it was wireless at the time and the card was barely supported yet smile):

#!/bin/bash
# Connect to the internet

nic="eth1"
dhcp="dhcpcd"
dhcpid="/var/run/${dhcp}-${nic}.pid"
dhcproc="$(ps aux | grep -v grep | grep dhcpcd)"

ifconfig $nic up
if [ -n $dhcproc ]; then
  if [ -f $dhcpid ]; then
      ${dhcp} -k
  else
    pkill ${dhcp}
  fi
  echo "Quit previous dhcpcd instance"
fi

echo "Connecting..."
${dhcp} ${nic} &> /dev/null
if [ -n $dhcproc ]; then
  echo "Connected.  Test..."
  ping -c1 yahoo.com | grep --color=always "packets transmitted"
else
  echo "DHCP client timed out"
fi

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

Offline

#928 2010-03-21 03:41:14

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

Re: Post your handy self made command line utilities

Why not just use netcfg?

Offline

#929 2010-03-21 11:06:14

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

Re: Post your handy self made command line utilities

i have this which i run on boot, i use it to open a ssh tunnel when im not using my own wifi so i can use foxproxy to encrypt my browsing.

#!/bin/bash
if iwconfig | grep "Home network ssid" ; then 
echo At home
else 
ssh ipaddress -D 9999 -N 
fi

Last edited by markp1989 (2010-03-21 11:06:56)


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

#930 2010-03-21 13:02:06

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

Re: Post your handy self made command line utilities

I'd grep for your router's MAC instead of ssid

Offline

#931 2010-03-21 22:01:39

firecat53
Member
From: Lake Stevens, WA, USA
Registered: 2007-05-14
Posts: 1,542
Website

Re: Post your handy self made command line utilities

Little .bashrc function to print out status for all active btpd torrents in a little more readable and useful fashion (to me, at least smile ) I'm sure there's ways to do this much more efficiently!!

function bt {
        num=$((`btcli list|wc -l`-1))
        x=0
        btcli stat "$x"|awk '{printf "%-15s%-15s%-15s%-15s%-15s%-15s\n",$5,$4,$3,$2,$1,$6}'
        while [ "$x" -lt "$num" ]; do
                btcli stat "$x"|grep -v 'RT'|awk '{printf "%-15s%-15s%-15s%-15s%-15s%-15s\n",$5,$4,$3,$2,$1,$6}'
                x=$(($x+1))
        done
}

Scott

Edit: I still need to figure out how to add the name in for each line (from btcli list)

Last edited by firecat53 (2010-03-21 22:09:00)

Offline

#932 2010-03-22 04:50:32

Reasons
Member
From: Washington
Registered: 2007-11-04
Posts: 572

Re: Post your handy self made command line utilities

Wrote a perl script so that you can use your exported google calendar with calcurse and have the correct times.

#!/usr/bin/perl -w
#################################
### A Simple regex program to ###
### change from one timezone  ###
### to another with ics files ###
###                           ###
###         Shawn Dyjak       ###
###     dyjaks@gmail.com      ###
#################################

use Time::Local;
$infile = $ARGV[0];
$outfile = $ARGV[1];
if (!$infile || !$outfile) {
    print "Welcome to tz_convert. You must specify files to use!\n";
    print "Usage : perl tz_convert <read file> <output file>\n";
    exit;
}
open(INFILE, "+<$infile") or die $!;
my @lines = <INFILE>;
$count = 0;
foreach (@lines) {
    if ($_ =~ /DTSTART:(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/) {
        my ($year, $mon, $day, $hour, $min) =
            $_ =~ /(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/;
        my $time = timegm(0, $min, $hour, $day, $mon- 1, $year - 1900);
        (undef, $min, $hour, $day, $mon, $year) = localtime($time);
        my $local_date = sprintf "%d%02d%02dT%02d%02d00Z\n", $year + 1900, $mon + 1, $day, $hour, $min;
        $lines[$count] = "DTSTART:$local_date";
    } elsif ($_ =~ /DTEND:(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/) {
        my ($year, $mon, $day, $hour, $min) =
            $_ =~ /(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})/;
        my $time = timegm(0, $min, $hour, $day, $mon- 1, $year - 1900);
        (undef, $min, $hour, $day, $mon, $year) = localtime($time);
        my $local_date = sprintf "%d%02d%02dT%02d%02d00Z\n", $year + 1900, $mon + 1, $day, $hour, $min;
        $lines[$count] = "DTEND:$local_date";
    }
    $count++;
}
close(INFILE);
open(INFILE, ">$outfile") or die $!;
$count = 0;
    foreach (@lines) {
        print INFILE "$lines[$count]";
        $count++;
    }
close(INFILE);

Offline

#933 2010-03-23 10:54:37

Ogion
Member
From: Germany
Registered: 2007-12-11
Posts: 367

Re: Post your handy self made command line utilities

I wrote a little perl script that lets me use shortcut names that will be translated to an url given to mplayer. Intended as "radio.pl radiostation". Previously i did this by having aliases, but since i want to learn a bit scripting (and perl) i thought i'd make it in this form. (Which is, btw, my first actual perl script and one of my first scripts at all, so there are probably lots of things that could be done better wink ).
If someone wants to use it, just change the hash entries of stationnames and urls.

#!/usr/bin/perl
# radio.pl
# give "list" or a stationname as cli argument
# without argument enter interactive inputting a stationname
use strict;
use warnings;

my %stations = (
'barcelonajazz' => 'http://www.live365.com/play/jmestres',
'dradio' => 'http://dradio.ic.llnwd.net/stream/dradio_dlf_m_a.ogg',
'bbcworld' => 'mms://a973.l3944038972.c39440.g.lm.akamaistream.net/D/973/39440/v0001/reflector:38972',
);
my @stationnames = keys %stations;
#my @links = values %stations; # not needed yet but might be useful
my $cliarg;
if ( defined $ARGV[0] ) {
    my $cliarg = $ARGV[0];
    if ( $cliarg eq "list" ) {
        print "@stationnames\n";
        exit 0;
    }
    if ( grep { $_ eq $cliarg } @stationnames ) {
        system("/usr/bin/mplayer $stations{$cliarg}");
    } else    {
        print "Please provide a valid radio station name commandline argument. (use \"list\" as argument to see a list of names)\n"; 
        exit 1;
    }
} else {
    my $selection;
    print "Enter the name of the radio station.", "\n";
    $selection = <STDIN>;
    chomp($selection);
    if ( grep { $_ eq $selection } @stationnames ) {
        system("/usr/bin/mplayer $stations{$selection}");
    } else    {
        print "Please provide a valid radio station name. (use \"list\" as argument to see a list of names)\n"; 
        exit 1;
    }
}

Ogion


(my-dotfiles)
"People willing to trade their freedom for temporary security deserve neither and will lose both." - Benjamin Franklin
"Enlightenment is man's leaving his self-caused immaturity." - Immanuel Kant

Offline

#934 2010-03-23 12:07:36

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

Re: Post your handy self made command line utilities

So did I, a looong time ago. Also my first perl script. tongue

#!/usr/bin/perl
use strict;
# radio 
use Getopt::Std;

my $file = "$ENV{HOME}/.rapio/channels";
my $station;
# -dumpstream, -dumpaudio might be useful
my $external = "mplayer -really-quiet -cache 100 -slave". 
               " -input file=/home/scp1/.mplayer/fifo";
our($opt_s);
getopts('s:');

my %radiostations = ();
open(STATIONS, $file) or die "Could not open $file: $!\n";
while(<STATIONS>) {
  chomp;
  my ($key,$value) = split /\s+/;
  $radiostations{$key} .= exists $radiostations{$key} ? "$value" : $value;
}
close($file);

if($opt_s) {
  $station = $radiostations{$opt_s};
  system("$external $station ");
}

else {
  &help;
}

sub help {
  print "Usage: $0 -s <channel>\n\n";
  printf("%17s %5s\n", "Channel", "URL");
  foreach my $key(sort(keys(%radiostations))) {
    printf("%17s %s\n", $key, $radiostations{$key});
  }
  exit 0;
}

Last edited by dmz (2010-03-23 14:09:15)

Offline

#935 2010-03-23 13:33:46

Ogion
Member
From: Germany
Registered: 2007-12-11
Posts: 367

Re: Post your handy self made command line utilities

Heh, nice. I'll be sure to study your script (as that's how i learn this kinda thing the best) wink

Ogion


(my-dotfiles)
"People willing to trade their freedom for temporary security deserve neither and will lose both." - Benjamin Franklin
"Enlightenment is man's leaving his self-caused immaturity." - Immanuel Kant

Offline

#936 2010-03-23 14:28:33

Sirupsen
Member
From: Denmark
Registered: 2009-11-14
Posts: 26
Website

Re: Post your handy self made command line utilities

I got sort of tired of having a million terminal windows open at the same time, so I found this handy script:

#! /bin/bash
WINTITLE="sakura" # Name of the window (or part of it)
PROGRAMNAME="sakura -e fish" # Name of the program, so it can be opened if there's no window currently

# Lists all windows, if there's one containing $WINTITLE it'll return 1, and bring the current instance of the program to the front.
if [ `wmctrl -l | grep -c "$WINTITLE"` != 0 ]
  then
    wmctrl -a "$WINTITLE"
# Else, it'll launch a new ins"tance
else
  $PROGRAMNAME &
fi

# We're good!
exit 0

Offline

#937 2010-03-23 14:50:04

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

Re: Post your handy self made command line utilities

Ogion wrote:

I wrote a little perl script that lets me use shortcut names that will be translated to an url given to mplayer.

Hmm...

#!/bin/bash

declare -A radios
radios[alias1]="http://url.one"
radios[alias2]="http://url.two"

if [[ $1 == list ]]; then
    echo "Stations: ${!radios[@]}"
    exit
fi

if [[ -n ${radios[$1]} ]]; then
    mplayer ${radios[$1]}
else
    echo "No known station by that name"
fi

--Just another bash hacker,

Last edited by Daenyth (2010-03-23 14:56:11)

Offline

#938 2010-03-24 00:25:09

supulton
Member
Registered: 2008-12-31
Posts: 58

Re: Post your handy self made command line utilities

GraveyardPC wrote:

Something fun, a terminal screensaver based on pipes:

#!/bin/bash
declare -i  f=75 s=13 r=2000 t=0 c=1 n=0 l=0
declare -ir w=$(tput cols) h=$(tput lines)
declare -i  x=$((w/2)) y=$((h/2))
declare -ar v=(    [00]="\x83" [01]="\x8f" [03]="\x93"
        [10]="\x9b" [11]="\x81" [12]="\x93"
        [21]="\x97" [22]="\x83" [23]="\x9b"
        [30]="\x97" [32]="\x8f" [33]="\x81" )

OPTIND=1
while getopts "f:s:r:h" arg; do
    case $arg in
    f)    ((f=($OPTARG>19 && $OPTARG<101)?$OPTARG:$f));;
    s)    ((s=($OPTARG>4  && $OPTARG<16 )?$OPTARG:$s));;
    r)    ((r=($OPTARG>0)?$OPTARG:$r));;
    h)    echo -e "Usage: pipes [OPTION]..."
        echo -e "Animated pipes terminal screensaver.\n"
        echo -e "  -f [20-100]\tframerate (D=75)."
        echo -e "  -s [5-15]\tprobability of a straight fitting (D=13)."
        echo -e "  -r LIMIT\treset after x characters (D=2000)."
        echo -e "  -h\t\thelp (this screen).\n"
        exit 0;;
    esac
done

tput smcup
tput reset
tput civis
while ! read -t0.0$((1000/$f)) -n1; do
    # New position:
    (($l%2))    && ((x+=($l==1)?1:-1))
    ((!($l%2))) && ((y+=($l==2)?1:-1))

    # Loop on edges (change color on loop):
    ((c=($x>$w || $x<0 || $y>$h || $y<0)?($RANDOM%7-1):$c))
    ((x=($x>$w)?0:(($x<0)?$w:$x)))
    ((y=($y>$h)?0:(($y<0)?$h:$y)))

    # New random direction:
    ((n=$RANDOM%$s-1))
    ((n=($n>1||$n==0)?$l:$l+$n))
    ((n=($n<0)?3:$n%4))

    # Print:
    tput cup $y $x
    echo -ne "\033[1;3${c}m\xe2\x94${v[$l$n]}"
    (($t>$r)) && tput reset && tput civis && t=0 || ((t++))
    l=$n
done
tput rmcup

Here's a shot of it working:
http://dl.dropbox.com/u/519931/pipes.jpg

That is awesome.

Offline

#939 2010-03-24 00:47:04

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Post your handy self made command line utilities

supulton wrote:

That is awesome.

Thanks. I've been doing some ascii-animation stuff lately, so here's something else too. It's the python implementation of this fire animation from Thiemo Mättig.

#!/usr/bin/python
import curses, random

screen    = curses.initscr()
width    = screen.getmaxyx()[1]
height    = screen.getmaxyx()[0]
size    = width*height
char    = [" ", ".", ":", "^", "*", "x", "s", "S", "#", "$"]
b    = []

curses.curs_set(0)
curses.start_color()
curses.init_pair(1,0,0)
curses.init_pair(2,1,0)
curses.init_pair(3,3,0)
curses.init_pair(4,4,0)
screen.clear
for i in range(size+width+1): b.append(0)

while 1:
    for i in range(int(width/9)): b[int((random.random()*width)+width*(height-1))]=65
    for i in range(size):
        b[i]=(b[i]+b[i+1]+b[i+width]+b[i+width+1])/4
        color=(4 if b[i]>15 else (3 if b[i]>9 else (2 if b[i]>4 else 1)))
        if(i<size-1):    screen.addstr(    int(i/width),
                        i%width,
                        char[(9 if b[i]>9 else b[i])],
                        curses.color_pair(color) | curses.A_BOLD )

    screen.refresh()
    screen.timeout(30)
    if (screen.getch()!=-1): break

curses.endwin()

Edit: I've added color.

Last edited by GraveyardPC (2010-03-24 05:39:38)

Offline

#940 2010-03-24 07:22:02

tawan
Member
Registered: 2010-03-02
Posts: 290
Website

Re: Post your handy self made command line utilities

GraveyardPC wrote:

Thanks. I've been doing some ascii-animation stuff lately

haha i thought pipes was good, the fire is great big_smile

I'd add it to conky but that may be silly..

Offline

#941 2010-03-25 18:43:21

Hiato
Member
Registered: 2009-01-21
Posts: 76

Re: Post your handy self made command line utilities

@Daenyth: surely these, if not most of all the scripts are wiki worthy?

Offline

#942 2010-03-25 18:49:18

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

Re: Post your handy self made command line utilities

Hiato wrote:

@Daenyth: surely these, if not most of all the scripts are wiki worthy?

See here for some previous discussion along those lines.

Offline

#943 2010-03-25 20:35:23

skanky
Member
From: WAIS
Registered: 2009-10-23
Posts: 1,847

Re: Post your handy self made command line utilities

How to set an environment variable with multiple items, from a file:

load_from_file() {
    echo "$(awk '/^.+$/{printf('$2')}' $1)"
}

You can use the swk command and insert the formatting,if that makes it easier. But using the function enables some other generic stuff like checking that the file exists, searching for a filename, etc.

Here's a couple of example uses:

LIBETC_TMP="$(load_from_file $XDG_CONFIG_HOME/libetc/data '":"$0":/home/skanky/"$0')"
if [[ -n $LIBETC_TMP ]]; then 
    export LIBETC_DATA=${LIBETC_TMP:1}
fi

# CDPath - list of dirs to search for rel paths
export CDPATH="$(load_from_file $XDG_CONFIG_HOME/bash/cdpaths '":"$0')"

Note, the quoting has to be done carefully - which is why it might be easier to use a the awk comand directly.
This will create ":" delimted entries and the first one will add two versions, one relative and one based in my home dir.
It's probably possibvle to use tr but I found awk the easiest way to skip empty lines.

Fnally the check for LIBETC_DATA is due to an apparent bug with libetc-experimental. Once that's fixed, I'll probably move the "export VAR=" into the function.


"...one cannot be angry when one looks at a penguin."  - John Ruskin
"Life in general is a bit shit, and so too is the internet. And that's all there is." - scepticisle

Offline

#944 2010-03-26 20:50:36

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

Re: Post your handy self made command line utilities

i have this in a cronjob.  after becoming familiar with --propupd and using rkhunter.conf to suppress warnings and false positives, i find it quite useful as a quick sanity check once a week or something.

#!/bin/bash

logger() { echo "$(date +'[ %d %b %Y %H:%M ]') :: $*" | tee -a "$log"; }

errorout() { logger "ERROR: $*"; exit 1; }

send_to_log() {
  local IFS=$'\n'

  while read -r; do
    logger "$REPLY"
  done
}

mail_log() { su -c "echo see attached | mutt -s \"Root Kit Check\" -a \"$log\" -- you@gmail.com" you; }

# must be root
[ $(id -u) -ne 0 ] && errorout 'you must be root'

# location of log
log='/home/you/.logs/rootkitcheck.log'

logger ' --- starting new check --- '
/usr/bin/rkhunter --versioncheck --nocolors                   | send_to_log
/usr/bin/rkhunter --update --nocolors                         | send_to_log
/usr/bin/rkhunter --cronjob --nocolors --report-warnings-only | send_to_log

# set perms on log
chown you:you "$log"

# mail the log?
#mail_log

obviously change the "you" parts as needed. 

yes, i know, i don't really need the send_to_log stuff, but i was playing with it in other scripts at the time.

Offline

#945 2010-03-27 22:37:23

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

Re: Post your handy self made command line utilities

#!/bin/bash
### Word-Based Text-to-Speech ###
# Version 0.2 by Scott Garrett  #
# Wintervenom [(at)] gmail.com  #
#################################
count_dir="/home/wintervenom/Music/Samples/FLAC/Recorded/Scott/TTS Samples"

phrase="$@"
phrase="${phrase//./ }"
phrase="${phrase//,/ }"
phrase="${phrase//-/ }"
phrase="${phrase//\(/ }"
phrase="${phrase//\)/ }"
phrase="${phrase//\[/ }"
phrase="${phrase//\]/ }"
phrase="${phrase//\{/ }"
phrase="${phrase//\}/ }"
phrase="${phrase//</ }"
phrase="${phrase//>/ }"
phrase="${phrase//:/ }"
phrase="${phrase//\// slash }"
phrase="${phrase//\\/ backslash }"
phrase="${phrase//+/ plus }"
phrase="${phrase//&/ and }"
phrase="${phrase//_/ underscore }"
phrase="${phrase//%/ percent }"
phrase="${phrase//\*/ asterisk }"
phrase=`echo "$phrase" | tr '[:upper:]' '[:lower:]'`

process () {
until [ -z "$1" ]; do
  word="$1"

  if ! [[ "$word" =~ ^[0-9]+$ ]]; then
    [ -f "$count_dir/`echo "$word" | tr '[:upper:]' '[:lower:]'`.flac" ] &&
      flac123 "$count_dir/`echo "$word" | tr '[:upper:]' '[:lower:]'`.flac" &> /dev/null
    shift
    continue
  fi

  while [ "${word:0:1}" = '0' ]; do
    word=${word:1}
  done

  if ((${#word} == 5)); then
    if ((${word:0:2} > 20)); then
      flac123 "$count_dir/${word:0:1}0.flac" &> /dev/null
      flac123 "$count_dir/${word:1:1}.flac" &> /dev/null
    else
      flac123 "$count_dir/${word:0:2}.flac" &> /dev/null
    fi
    flac123 "$count_dir/1000.flac" &> /dev/null
    word=${word:2}
  fi

  if ((${#word} == 4)); then
    ((${word:0:1} != 0)) && flac123 "$count_dir/${word:0:1}.flac" &> /dev/null
    flac123 "$count_dir/1000.flac" &> /dev/null
    word=${word:1}
  fi

  if ((${#word} == 3)); then
    [ -f "$count_dir/${word:0:1}.flac" ] && {
      ((${word:0:1} != 0)) && {
        flac123 "$count_dir/${word:0:1}.flac" &> /dev/null
        flac123 "$count_dir/100.flac" &> /dev/null
      }
    }
    word=${word:1}
  fi
 
  if ((word > 20)); then
    flac123 "$count_dir/${word:0:1}0.flac" &> /dev/null
    ((${word:1:1} != 0)) && flac123 "$count_dir/${word:1:1}.flac" &> /dev/null
  else
    ((word != 0)) && flac123 "$count_dir/$((word)).flac" &> /dev/null
  fi
  shift
done
}
if mpc | grep -qE 'playing'; then
  mpd_playing=1
  mpc toggle
fi
process $phrase
[ $mpd_playing ] && mpc play
#!/bin/bash
ac_adapter_dev=AC
lid_dev=LID0
speak='/home/wintervenom/bin/scott'
flag_ac_on="/dev/shm/flag_acpi_ac_online"
flag_ac_off="/dev/shm/flag_acpi_ac_offline"


case "$1" in
  button/power)
    case "$2" in
      PWRF)
        $speak suspending machine
        pm-suspend
      ;;
    esac
  ;;
  button/sleep)
    case "$2" in
      SLPB)
        $speak suspending machine
        pm-suspend
      ;;
    esac
  ;;
  button/lid)
    if grep -qF open "/proc/acpi/button/lid/$lid_dev/state"; then
      $speak lid opened
      xset -display :0 dpms force on
    else
      $speak lid closed
      xset -display :0 dpms force off
    fi
  ;;
  ac_adapter|battery)
    if grep -qF 'on-line' "/proc/acpi/ac_adapter/$ac_adapter_dev/state"; then
      xset -display :0 dpms 0 0 7200
      echo max_performance > "/sys/class/scsi_host/host0/link_power_management_policy"
      cat "/sys/class/backlight/acpi_video0/max_brightness" > "/sys/class/backlight/acpi_video0/brightness"
      if [ ! -f $flag_ac_on ]; then
        $speak adapter connected
        touch $flag_ac_on
        rm $flag_ac_off
      fi
    else
      xset -display :0 dpms 0 0 300
      echo min_power > "/sys/class/scsi_host/host0/link_power_management_policy"
      echo 0 > "/sys/class/backlight/acpi_video0/brightness"
      if [ ! -f $flag_ac_off ]; then
        $speak adapter disconnected
        touch $flag_ac_off
        rm $flag_ac_on
      fi
    fi
  ;;
esac
#!/bin/dash
### Battery Monitor Daemon #####
# Version 0.1 by Scott Garrett #
# Wintervenom [(at)] gmail.com #
################################

###############
### Globals ###
###############

# AC adapter device (in /proc/acpi/ac_adapter).
ac_adapter_dev=AC

# Battery device (in /proc/acpi/battery).
battery_dev=BAT0

# Lid button device (in /proc/acpi/button/lid).
lid_dev=LID0

percentage_low=10
percentage_critical=5

percentage_low_action='beep -f3000 -nf1000'
percentage_critical_action='sudo pm-suspend'

last_display_percentage=0

# Title of this program, so we don't have to keep typing this
# out in the notification bubbles, 'cause we're lazy.  :P
title='Battery Monitor Daemon'

#################
### Functions ###
#################
battery () {
  # Does the battery device exist?
  if [ -d /proc/acpi/battery/$battery_dev ]; then
    # Grab the information we need about power devices.
    ac_adapter=`awk '/^state: / { print $2 }' /proc/acpi/ac_adapter/$ac_adapter_dev/state`
    full_capacity=`awk '/^last full / { print $4 }' /proc/acpi/battery/$battery_dev/info`
    current_capacity=`awk '/^remaining / { print $3 }' /proc/acpi/battery/$battery_dev/state`
    percentage=$(((current_capacity * 100) / full_capacity))
    lid_button=`awk '/^state: / { print $2 }' /proc/acpi/button/lid/$lid_dev/state`
    
    #echo "$percentage%, AC $ac_adapter"
    # Pop up a display about how much battery power remains every five
    # percent...
    [ $((percentage % 5)) -eq 0 ] && {
      # ...only if the percentage has really changed...
      [ $last_display_percentage -ne $percentage ] && {
        notify-send "$title" "Battery at $percentage%.  AC $ac_adapter."
        scott battery at $percentage percent
        # ...so we won't annoy the user with this more than one time.
        last_display_percentage=$percentage
      }
    }
   
    # 
    if [ "$ac_adapter" != 'on-line' ]; then
      if [ $percentage -lt $percentage_low -a -z $flag_low ]; then
        # Notify the user...
        notify-send "$title" "Battery low.
Battery is at $percentage%.  AC $ac_adapter."
        # ...set a flag so that we know we've taken action...
        flag_low=1
        beep -f2000 -r5
        scott battery low
        # ...run the low action.
        $percentage_low_action
      elif [ $percentage -lt $percentage_critical -a -z $flag_critical ]; then
        notify-send "$title" "Battery critical.  Suspending the machine...
Battery is at $percentagek%.  AC $ac_adapter."
        flag_critical=1
        beep -f1000 -d50 -l50 -r5
        scott battery critical puase suspending machine
        $percentage_critical_action
      fi
    else
      # Unset flags if the AC adapter has been plugged in.
      [ $flag_critical ] && unset flag_critical
      [ $flag_low ] && unset flag_low
    fi
    
    # Now, let's check to see if the AC adapter has been messed with
    # since last check.
    [ "$ac_adapter" != "$ac_adapter_laststate" -a "$lid_button" = 'open' ] && {
      # If it was plugged in since last time...
      if [ "$ac_adapter" = 'on-line' ]; then
        # ...tell the user about it...
        notify-send "$title" "AC adapter has been plugged in.
Battery is at $percentage%.  AC $ac_adapter."
        # ...turn up the display panel backlight...
        xbacklight -steps 1 -set 100
        # ...tell X to wait longer before putting the display to sleep.
        xset dpms 0 0 7200
      else
        notify-send "$title" "AC adapter has been removed.
Battery is at $percentage%.  AC $ac_adapter."
        xbacklight -steps 1 -set 0
        xset dpms 0 0 300
      fi
      # Remember what happened with the AC adapter.
      ac_adapter_laststate="$ac_adapter"
    }
  else
    #echo 'N/A'
    notify-send "$title" 'No battery detected.'
  fi
}

############
### Main ###
############
battery
[ "$1" = '-d' ] && {
  shift
  while :; do
    sleep 15
    battery
  done
}#!/bin/dash
### Battery Monitor Daemon #####
# Version 0.1 by Scott Garrett #
# Wintervenom [(at)] gmail.com #
################################

###############
### Globals ###
###############

# AC adapter device (in /proc/acpi/ac_adapter).
ac_adapter_dev=AC

# Battery device (in /proc/acpi/battery).
battery_dev=BAT0

# Lid button device (in /proc/acpi/button/lid).
lid_dev=LID0

percentage_low=10
percentage_critical=5

percentage_low_action='beep -f3000 -nf1000'
percentage_critical_action='sudo pm-suspend'

last_display_percentage=0

# Title of this program, so we don't have to keep typing this
# out in the notification bubbles, 'cause we're lazy.  :P
title='Battery Monitor Daemon'

#################
### Functions ###
#################
battery () {
  # Does the battery device exist?
  if [ -d /proc/acpi/battery/$battery_dev ]; then
    # Grab the information we need about power devices.
    ac_adapter=`awk '/^state: / { print $2 }' /proc/acpi/ac_adapter/$ac_adapter_dev/state`
    full_capacity=`awk '/^last full / { print $4 }' /proc/acpi/battery/$battery_dev/info`
    current_capacity=`awk '/^remaining / { print $3 }' /proc/acpi/battery/$battery_dev/state`
    percentage=$(((current_capacity * 100) / full_capacity))
    lid_button=`awk '/^state: / { print $2 }' /proc/acpi/button/lid/$lid_dev/state`
    
    #echo "$percentage%, AC $ac_adapter"
    # Pop up a display about how much battery power remains every five
    # percent...
    [ $((percentage % 5)) -eq 0 ] && {
      # ...only if the percentage has really changed...
      [ $last_display_percentage -ne $percentage ] && {
        notify-send "$title" "Battery at $percentage%.  AC $ac_adapter."
        scott battery at $percentage percent
        # ...so we won't annoy the user with this more than one time.
        last_display_percentage=$percentage
      }
    }
   
    # 
    if [ "$ac_adapter" != 'on-line' ]; then
      if [ $percentage -lt $percentage_low -a -z $flag_low ]; then
        # Notify the user...
        notify-send "$title" "Battery low.
Battery is at $percentage%.  AC $ac_adapter."
        # ...set a flag so that we know we've taken action...
        flag_low=1
        beep -f2000 -r5
        scott battery low
        # ...run the low action.
        $percentage_low_action
      elif [ $percentage -lt $percentage_critical -a -z $flag_critical ]; then
        notify-send "$title" "Battery critical.  Suspending the machine...
Battery is at $percentagek%.  AC $ac_adapter."
        flag_critical=1
        beep -f1000 -d50 -l50 -r5
        scott battery critical puase suspending machine
        $percentage_critical_action
      fi
    else
      # Unset flags if the AC adapter has been plugged in.
      [ $flag_critical ] && unset flag_critical
      [ $flag_low ] && unset flag_low
    fi
    
    # Now, let's check to see if the AC adapter has been messed with
    # since last check.
    [ "$ac_adapter" != "$ac_adapter_laststate" -a "$lid_button" = 'open' ] && {
      # If it was plugged in since last time...
      if [ "$ac_adapter" = 'on-line' ]; then
        # ...tell the user about it...
        notify-send "$title" "AC adapter has been plugged in.
Battery is at $percentage%.  AC $ac_adapter."
        # ...turn up the display panel backlight...
        xbacklight -steps 1 -set 100
        # ...tell X to wait longer before putting the display to sleep.
        xset dpms 0 0 7200
      else
        notify-send "$title" "AC adapter has been removed.
Battery is at $percentage%.  AC $ac_adapter."
        xbacklight -steps 1 -set 0
        xset dpms 0 0 300
      fi
      # Remember what happened with the AC adapter.
      ac_adapter_laststate="$ac_adapter"
    }
  else
    #echo 'N/A'
    notify-send "$title" 'No battery detected.'
  fi
}

############
### Main ###
############
battery
[ "$1" = '-d' ] && {
  shift
  while :; do
    sleep 15
    battery
  done
}

Last edited by Wintervenom (2010-03-27 22:40:32)

Offline

#946 2010-03-27 23:39:59

kmason
Member
From: Tempe, Arizona, USA
Registered: 2010-03-23
Posts: 256
Website

Re: Post your handy self made command line utilities

#!/bin/bash
## Undertaker, the note taking program that's under 5kb! ##
## By Kevin Mason (http://bloodstar.net) ##

## Replace with the directory you placed the script in.
SCRIPTDIR="/home/username/undertaker"
## Replace with your editor of choice.
EDITOR=vim

searchnotes(){
echo "Please choose a class from which to search its notes."

select class in $SCRIPTDIR/classes/*
do
    if [ $class ]
        then
            break;
        else
            echo "Not a valid class, please choose the # next to the class."
    fi
done

echo "Please enter a search pattern."
read pat
grep -i $pat $class
repeat
}

writenotes(){
echo "Please choose a class to write notes for."

select class in $SCRIPTDIR/classes/*
do
    if [ $class ]
        then
            break;
        else 
            echo "Not a valid class, please choose the # next to the class."
    fi
done
echo >> $class
date >> $class
echo >> $class
$EDITOR $class
echo "_____________________________________________________" >> $class
echo >> $class
repeat
}

newclass(){
echo "Please enter the class name."
read name
echo "Please enter the file name."
read fname
while [ -f $SCRIPTDIR/classes/$fname ]
    do
        echo "Filename exists.  Please try again."
        read fname
    done
echo $name > $SCRIPTDIR/classes/$fname
echo "Now what would you like to do?"
repeat
}

intro(){
echo "Welcome to Undertaker, the note taking program that's under 5kb!"
echo "What would you like to do today?"

select action in "New Class" "Write Notes" "Search Notes" "Exit"
do
            case $action in
                "New Class") newclass;break;;
                "Write Notes") writenotes;break;;
                "Search Notes") searchnotes;break;;
        "Exit") break;;
                *) echo "Not a valid action, please choose the # next to the action.";;
            esac
done
}

repeat(){
select action in "New Class" "Write Notes" "Search Notes" "Exit"
do
            case $action in
                "New Class") newclass;break;;
                "Write Notes") writenotes;break;;
                "Search Notes") searchnotes;break;;
        "Exit") break;;
                *) echo "Not a valid action, please choose the # next to the action.";;
            esac
done
}

if [ -d $SCRIPTDIR/classes ]
    then
        intro
    else
        mkdir $SCRIPTDIR/classes
        intro
fi

Last edited by kmason (2010-03-27 23:56:20)

Offline

#947 2010-03-28 02:44:33

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

Re: Post your handy self made command line utilities

Daenyth wrote:

Why not just use netcfg?

Pretty much just an exercise to me.  I discover when I write them down, I remember them better smile.


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

Offline

#948 2010-03-28 21:03:10

gazj
Member
From: /home/gazj -> /uk/cambs
Registered: 2007-02-09
Posts: 681
Website

Re: Post your handy self made command line utilities

Daenyth wrote:
Hiato wrote:

@Daenyth: surely these, if not most of all the scripts are wiki worthy?

See here for some previous discussion along those lines.

Started

http://wiki.archlinux.org/index.php/AUS … er_scripts

A long long way to go yet tho.  Please proof read guys.

Offline

#949 2010-03-28 23:31:09

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

Re: Post your handy self made command line utilities

That's not really what I had in mind. If we'd do that, just use script wiki. I don't think it's a very maintainable or useful solution honestly.

Offline

#950 2010-03-29 00:16:19

gazj
Member
From: /home/gazj -> /uk/cambs
Registered: 2007-02-09
Posts: 681
Website

Re: Post your handy self made command line utilities

Daenyth wrote:

That's not really what I had in mind. If we'd do that, just use script wiki. I don't think it's a very maintainable or useful solution honestly.

I hear you.  I'll have a rethink

Offline

Board footer

Powered by FluxBB