You are not logged in.

#1001 2010-04-22 21:18:18

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

Re: Post your handy self made command line utilities

Me too!

#!/bin/bash
#
# check_ip.sh - check if external ip address has changed, notify via email if
# it has
#
# CREATED: 2009-08-10 12:23
# MODIFIED: 2009-12-29 12:44
#

IP=$HOME/tmp/ip/current_external_ip
TEMP=$HOME/tmp/ip/temp_ip
EMAIL_LIST=$(< $HOME/.email)
LOG=$HOME/tmp/ip/log
IP_SERVICE="www.whatismyip.com/automation/n09230945.asp"·

function save_and_mail {
    cp $TEMP $IP
    log "$HOSTNAME is now at $(< $IP); Email sent to $EMAIL_LIST"
    echo "$HOSTNAME is now at $(< $IP)" | mail -s $(< $IP) $EMAIL_LIST
}

function get_ip {
    wget -q $IP_SERVICE -O $TEMP
    [ "$(file -b $TEMP)" == empty ]
    return $?
}

function log {
    echo -n $(date) >> $LOG
    echo " - $1" >> $LOG
}

while true; do·
    get_ip
    [ $? -eq 1 ] && break
    log "$IP_SERVICE returned a zero byte file"
    sleep 30s
done

chmod 600 $TEMP

if [ -f $IP ]; then
    diff $TEMP $IP &> /dev/null || save_and_mail
else
    save_and_mail
fi

However, I'm not sure why I did some of the things I did there.

Last edited by rson451 (2010-04-22 21:19:20)


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

Offline

#1002 2010-04-23 01:58:21

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

Re: Post your handy self made command line utilities

@brisbin

This might eliminate the dependency of lynx

new="$(lynx -dump "$ip_url")"

with

new="$(curl -Ls "$ip_url")"

and what about

old="$(cat "$ipfile")"

with

old="$(< "$ipfile")"

Offline

#1003 2010-04-23 05:36:29

Kitty
Member
From: The Burning Desert
Registered: 2008-01-11
Posts: 88

Re: Post your handy self made command line utilities

Now that I don't have home internet, I'm using a lot of random access points. This keeps prying eyes away.

#!/bin/bash

## socks-proxy.sh
# Open a SSH tunnel to a server for a secure proxy connection.
# Set SOCKS proxy to $PORT on localhost.

# Pretty status messages
USECOLOR='yes'
. /etc/rc.d/functions

# User Defaults:
PORT=8080
SSH_USER='username'
SERVER='your.server.com'

# Default Process ID file
#PID_FILE="/tmp/tunnel-${SSH_USER}.pid"

# If user is specified on cmd line:
if [ -n "$1" ]
    then
    SSH_USER=$1
fi

# Main
PID=$(pgrep -f "${SSH_USER}@${SERVER}")

if [[ -n $PID ]]; then
    stat_busy "Shutting down the tunnel"
    kill $PID && stat_done || stat_fail
else
    stat_busy "Opening the tunnel"
    ssh -qfND ${PORT} ${SSH_USER}@${SERVER} && stat_done || stat_fail
fi

Last edited by Kitty (2010-04-23 05:37:44)


/etc/rc.d/ is where daemons reside. Beware.

Offline

#1004 2010-04-23 10:00:26

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

Re: Post your handy self made command line utilities

Kitty wrote:

Now that I don't have home internet, I'm using a lot of random access points. This keeps prying eyes away.

#!/bin/bash

## socks-proxy.sh
# Open a SSH tunnel to a server for a secure proxy connection.
# Set SOCKS proxy to $PORT on localhost.

# Pretty status messages
USECOLOR='yes'
. /etc/rc.d/functions

# User Defaults:
PORT=8080
SSH_USER='username'
SERVER='your.server.com'

# Default Process ID file
#PID_FILE="/tmp/tunnel-${SSH_USER}.pid"

# If user is specified on cmd line:
if [ -n "$1" ]
    then
    SSH_USER=$1
fi

# Main
PID=$(pgrep -f "${SSH_USER}@${SERVER}")

if [[ -n $PID ]]; then
    stat_busy "Shutting down the tunnel"
    kill $PID && stat_done || stat_fail
else
    stat_busy "Opening the tunnel"
    ssh -qfND ${PORT} ${SSH_USER}@${SERVER} && stat_done || stat_fail
fi

thats pretty usefull, i been setting up my tunel manualy every time i need it .


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

#1005 2010-04-23 16:12:29

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

Re: Post your handy self made command line utilities

steve___ wrote:

@brisbin

This might eliminate the dependency of lynx

new="$(lynx -dump "$ip_url")"

with

new="$(curl -Ls "$ip_url")"

and what about

old="$(cat "$ipfile")"

with

old="$(< "$ipfile")"

yeah, not sure why lynx is there, i think i'll change it to wget -q -O - since the page is plaintext and wget is in [base].

since posting, i actually changed that last line to

read old < $ipfile

not sure if read < or $(< ) is less efficient, but i'm not that concerned ;P.

thanks.

Last edited by brisbin33 (2010-04-23 16:14:37)

Offline

#1006 2010-04-23 16:13:38

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

Re: Post your handy self made command line utilities

< is probably better than $(< ) as the $() will spawn a new process -- exec() has overhead.

Offline

#1007 2010-04-23 16:14:54

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

Re: Post your handy self made command line utilities

Daenyth wrote:

< is probably better than $(< ) as the $() will spawn a new process -- exec() has overhead.

that was my thinking.

Offline

#1008 2010-04-24 11:49:14

Paul-S
Member
From: Wales
Registered: 2008-02-04
Posts: 353

Re: Post your handy self made command line utilities

Hi all, I use podget on a desktop and laptop and I was looking for a script that will check a network share for an updated podgetrc
and replace the local one. Just wondering if someone has something they use that I could modify smile

Cheers
Paul-S

Offline

#1009 2010-04-24 12:04:58

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

Re: Post your handy self made command line utilities

Paul-S wrote:

Hi all, I use podget on a desktop and laptop and I was looking for a script that will check a network share for an updated podgetrc
and replace the local one. Just wondering if someone has something they use that I could modify smile

Cheers
Paul-S

Something like;

#!/usr/bin/perl
use strict;
use Linux::Inotify2;
use Data::Dumper;


my $inotify = Linux::Inotify2->new;
my $local  = "local/file";
my $remote = "remote/file";

$inotify->watch($remote, IN_MODIFY) or die;


while(1) {#my @events = $inotify->read) {
  print "Following started watch on $remote\n";
  my @events = $inotify->read;
  unless(@events > 0) {
    print "Read error: $!\n";
    last;
  }
  
  foreach my $event(@events) {
    if($event->mask eq 'IN_MODIFY') {
      move($remote, $local) or die "Cant move $remote => $local: $!";
    }
  }
}

Offline

#1010 2010-04-24 13:55:15

AskApache
Member
Registered: 2009-10-18
Posts: 16
Website

Re: Post your handy self made command line utilities

Here are really handy funcs I use all the time, http://www.askapache.com/linux-unix/bas … shell.html

PL ()
{
    builtin printf "\n%$(($COLUMNS - 5)).s\n" | sed -u "s/ /${1:--}/g"
}
aa_crontab ()
{
    [[ $EUID -eq 0 ]] && echo "NOROOT" && return;
    local i GG;
    for i in `getent passwd|cut -d ":" -f1`;
    do
        GG=$(sudo crontab -u $i -l 2>$N6 | tr -s '\n\000');
        [[ ${#GG} -gt 3 ]] && sleep 1 && echo -e "`tput smso` $i \n${L}`tput rmso`\n${GG}" && PL;
    done;
    sleep 4;
    /bin/ls $LS_OPTIONS -aLls1ch --color=always /etc/cron.{hourly,daily,weekly,monthly,d} | sed '/^total/d; /\ drwxr-xr-x/d'
}
aa_env ()
{
    local i T2=\${!${1}*};
    for i in `eval echo "${T2}"`;
    do
        echo -e "$i: ${!i}";
    done
}
aa_grep_color ()
{
    export GREP_COLOR=`echo -ne "\E[1;3$(aa_random_under 6)"`
}
aa_random_under ()
{
    echo -en $(( $RANDOM % ${1:-$RANDOM} + 1 ))
}
aa_safe_aliases ()
{
    [[ "`builtin type -t cp`" == "alias" || "${1:-on}" != "off" ]] && pm "Turning Safe Aliases On - with $FUNCNAME" && alias chmod='command chmod -c --preserve-root' && alias mkdir='command mkdir -pv' && alias rm='command rm -v' && alias cp='command cp -v' && alias mv='command mv -v' && alias ln='command ln --backup=nil' && return;
    local AN;
    pm "Turning Safe Aliases OFF - with $FUNCNAME";
    for AN in "chmod" "mkdir" "rm" "cp" "mv" "ln";
    do
        [[ "`type -t $AN`" == "alias" ]] && unalias $AN;
    done
}
aa_try_for_path ()
{
    PATH=/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games;
    [[ "$EUID" == "0" ]] && PATH=/sbin:/usr/sbin:/usr/local/sbin:$PATH;
    [[ -d /opt/s ]] && PATH=$PATH:/opt/s;
    local GP=$HOME/bin:$HOME/sbin:$HOME/libexec;
    local P=$PATH;
    P=${P}:/etc:/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/usr/bin/mh:/usr/libexec;
    P=${P}:/usr/X11R6/bin:/usr/libexec:/etc/X11:/etc/X11/xinit;
    P=${P}:/usr/local/php5/bin;
    for p in ${P//:/ };
    do
        [[ -d "${p}" && -x "${p}" ]] && GP=${GP}:$p;
    done;
    export PATH=$( echo -en "${GP//:/\\n}" | sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; h; P' | tr "\n" ':' ).
}
aarm ()
{
    local t=$( date +$HOME/.backups/.trash/%m-%d );
    [[ ! -d "$t" ]] && mkdir -pv "$t";
    command mv "$@" $t || {
        mkdir -pv $t/$$ && command mv "$@" $t/$$
    };
    pd
}
acr ()
{
    kill -28 $$;
    local T=`find /usr/share/terminfo -name "$1" -type f -printf '%f'`;
    [[ -z "$T" ]] && {
        echo "BAD TERMINAL SPECIFIED! $1" && return 2
    };
    export TERM=$1;
    tset -cw $TERM;
    echo -e "clear\nis1\nis2\ninit\ninitc\nrs1\nrs2\nreset\ncnorm\nrmso\nclear\nsgr0" | tput -T $TERM -S;
    true
}
ahave ()
{
    unset -v ahave;
    command command type $1 >&$N6 && ahave="yes" || return 1
}
btn ()
{
    echo -e "${R}`tput setab ${2:-2};tput setaf ${3:-0}` ${1:-DONE} ${R}"
}
cont ()
{
    local a;
    echo -en "${R} ${CUROFF}\n\n`tput rev`[ ${1:-Press any key to continue} ]${R}\n\n";
    read -t 500000 -n 1 a;
    echo -en "${CURON}"
}
ctype ()
{
    local C=$( ( builtin type -P $1 2>$N6 | sed 1q) || { echo -n "/bin/false" && echo "[`date`]$FUNCNAME FAILED WITH ARGS= $*" >> ~/.bash_errors && return 1; }; );
    [[ -x "$C" && x"$C" != "x" ]] || {
        echo "[`date`]$FUNCNAME FAILED WITH ARGS= $@" >> ~/.bash_errors && return 1
    };
    echo -n $C
}
du1 ()
{
    $NICE find . -mindepth 1 -maxdepth 1 -type d -print0 | xargs -P1 -0 -IFF sh -c '( echo `command du -sb "FF"` `command du -sh "FF"` | sed -e "s%^\([0-9]*\)\ \([^ ]*\)\ \([^ ]*\).*$%\1 \3 \2%g" )' | sort -n | cut -d ' ' -f2,3 | command grep --color=always '^[0-9\.]*[GMK]' | tr ' ' "\t"
}
du2 ()
{
    $NICE find . -mount -maxdepth 1 -mindepth 1 -type f | tr ' ' "\n" | xargs -P1 -IFF sh -c 'sed -e "s%^\([0-9]*\)\ \([^ ]*\)\ \([^ ]*\).*$%\1 \3 \2%g" <<< $( echo "`( du -sb FF && du -sh FF ) | tr -s [\t\n ]`" )' | sort -n | tail -n 20 | awk '{print $2,$3}' | tr ' ' "\t"
}
du3 ()
{
    $NICE find -O3 . -mount -maxdepth 1 -mindepth 1 -type d | xargs -I'FF' sh -c 'sed -e "s%^\([0-9]*\)\ \([^ ]*\) \([^ ]*\).*$%\1 \3 \2%" <<< $( echo "`( du -sb FF && du -sh FF ) | tr -s [\t\n]`" )' | sort -n | tail -n 20 | awk '{
  print $2,$3 }' | tr ' ' "\t"
}
ex ()
{
    [[ $# -eq 0 ]] && echo -e "$0: missing operand\nTry \`$0 --help' for more information." 1>&2 && return 2;
    until [[ -z "$1" ]]; do
        if [[ -f "$1" ]]; then
            pm "Extracting $1 ...";
            case $1 in
                *.tar.bz2)
                    tar xjf $1
                ;;
                *.tar.gz)
                    tar xzf $1
                ;;
                *.tar)
                    tar xf $1
                ;;
                *.tbz2)
                    tar xjf $1
                ;;
                *.tgz)
                    tar xzf $1
                ;;
                *.bz2)
                    bunzip2 $1
                ;;
                *.rar)
                    unrar x $1
                ;;
                *.gz)
                    gunzip $1
                ;;
                *.zip)
                    unzip $1
                ;;
                *.Z)
                    uncompress $1
                ;;
                *.7z)
                    7z x $1
                ;;
                *)
                    pm "Don't know how to extract '$1'" && file -s "$1"
                ;;
            esac;
        else
            pm "'$1' is not a valid file" && file -s "$1";
        fi;
        shift;
    done
}
grepc ()
{
    [[ $# -eq 0 ]] && echo -e "$0: missing operand\nTry \`$0 --help' for more information." 1>&2 && return 2;
    aa_grep_color && command grep --color=always "$@"
}
grepr ()
{
    local DIR=`pwd`;
    [[ $# -eq 0 ]] && echo -e "$0: missing operand\nUSAGE:\n $FUNCNAME [dir] [query]\n $FUNCNAME [query] (for current dir)" 1>&2 && return 2;
    [[ "$#" == "1" ]] && DIR=`pwd`;
    [[ ! -d "$DIR" ]] && echo -e "$0: $1 not a dir!  \n $FUNCNAME [dir] [query]\n $FUNCNAME [query] (for current dir)" 1>&2;
    $NICE find $DIR -mount ! -empty -type f 2> $N6 | sed '/ ASCII\|text /!d' | xargs -I'F87' -P0 grep "$@" 'F98'
}
hc ()
{
    local B C=`tput sgr0` B=`tput setaf 0;tput setab ${2:-6}`;
    [[ $# -eq 1 ]] && exec sed "s/\($*\)/$B\1$C/gI" || sed "s/\(${1}\)/$B\1$C/gI"
}
l ()
{
    command ls -UapFt -w $((${COLUMNS:-80} - 20 )) --color=tty "$@"
}
la ()
{
    command du * | awk '{print $2,$1}' | sort -n | tr ' ' "\t"
}
lin ()
{
    echo -en "$R";
    local D1 D2 D3 D L2 L3 L4 C1;
    C1=$(( ${COLUMNS:-`tput cols`} - 4 ));
    (( $C1 % 2 )) || (( C1-- ));
    export L=`builtin printf "%-${C1}s\n"|tr ' ' '_'`;
    L2=`echo -en $L|tr '_' ' '`;
    D2=$(( ${C1} - ${#2} - 2 ));
    D3=$(( ${D2} / 2 ));
    [[ $D3 -lt 2 ]] && D3=2;
    case ${1:-1} in
        0)
            echo -e "\n ${L}$R"
        ;;
        1)
            echo -e "|${L2}$R|$R"
        ;;
        2)
            L3="|${L2:0:${D3}}${2}";
            L4=$(( ${C1} - ${#L3} ));
            [[ $L4 -lt 2 ]] && L4=2;
            echo -e "${L3}${L2:0:${L4}}|"
        ;;
        3)
            echo -e " ${L} $R\n\n"
        ;;
    esac
}
ll ()
{
    command ls -UlapFr -w $((${COLUMNS:-80} - 20 )) --color=always "$@"
}
lll ()
{
    $NICE find ${1:-`pwd`} -maxdepth 1 -printf '%#8k %#5m %11M %#10u:%-10g %-5U:%-5G %p %f [ %Y %F ]\n'
}
locate1 ()
{
    [[ $# -eq 0 ]] && echo -e "$0: missing operand\nTry \`$0 --help' for more information." 1>&2 && return 2;
    command locate "$@" | xargs -IFF stat -c %s\ %a\ %A\ \ A\ %x\ \ M\ %y\ \ C\ %z\ \ %N 'FF'
}
locate2 ()
{
    [[ $# -eq 0 ]] && echo -e "$0: missing operand\nTry \`$0 --help' for more information." 1>&2 && return 2;
    command locate "$@" | sed -e "s%^${HOME}/*%%g" | tr \\012\\015 \\0 | xargs -0 -IFF ls -lABls1c --color=auto "~/FF" | column -t
}
nobb ()
{
    [[ $# -eq 0 ]] && exec sed -e 's/^[ \000\t]*//;s/[ \000\t]*$//; /[^ \t\000]\{1,\}/!d'
}
pd ()
{
    echo -e "${R}\n`tput setab 2;tput setaf 0` ${1:-DONE} ${R}\n"
}
pm ()
{
    [[ $# -eq 0 ]] && echo -e "$0: missing operand\nTry \`$FUNCNAME --help' for more information." 1>&2 && return 2;
    local I=${1:-3};
    echo -en "$R\n";
    case ${2:-1} in
        0)
            echo -en "`tput setaf 6`-- ${R}"
        ;;
        1)
            echo -e "`tput setaf 2`>>> ${R}$I${R}"
        ;;
        2)
            echo -en "`tput setaf 4` > ${R}$I${R}"
        ;;
        3)
            echo -e "`tput setaf 4` :: ${R}$I${R}"
        ;;
    esac
}
ps ()
{
    [[ -z "$1" ]] && command ps -Hacl -F S -A f | hc ".*$$PID.*" | hc ".*$$.*" && return;
    command ps "$@"
}
psh ()
{
    command ps wwo pid,user,group,size,sz,vsize,rss,pmem,pcpu,time,wchan,sched,stat,flags,comm,args k -vsz -C ${1:-httpd}
}
psu ()
{
    command ps -Hcl -F S f -u ${1:-$USER}
}
rmb ()
{
    [[ "$#" -lt "1" ]] && echo "Usage: $FUNCNAME dirnametoremove" 1>&2 && return 2;
    set -x;
    aarm "$@" || ( ( command rm -rf "$@" > $N6 && pd "$FUNCNAME removed $@" ) & );
    set +x
}
sleeper ()
{
    [[ "$#" -lt "1" ]] && echo "Usage: $FUNCNAME <process id>" 1>&2 && return 2;
    echo -en "\n${2:-.}";
    while `command ps -p $1 &>$N6`; do
        echo -n "${2:-.}" && sleep ${3:-1};
    done;
    echo
}
stat1 ()
{
    $NICE find ${1:-`pwd`} -print0 | xargs -0 -I'F87' stat -c %a\ %A\ \ A\ %x\ \ M\ %y\ \ C\ %z\ \ %N ${D} 'F87'
}
stat2 ()
{
    $NICE find ${1:-`pwd`} -depth -print0 | xargs -0 -I'F87' stat -c %a\ %A\ \ [A:%x\ M:%y\ C:%z]\ \ %N 'F87' | tr -s ' ' | column -t
}
tarp ()
{
    GZIP=--fast;
    PWD=`pwd`;
    F=$(date +$HOME/.backups/%m-%d-%g-%R-`sed -u 's/\//#/g' <<< $PWD`.tar.bz2);
    pm "Creating archive $F of $PWD";
    tar --ignore-failed-read -czPf $F $PWD;
    /bin/ls $LS_OPTIONS -l --color=tty $F;
    pm $F
}
tree ()
{
    ahave tree && command tree -Csuflapig "$@" || command ls -FR "$@"
}

Offline

#1011 2010-04-25 16:44:16

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: Post your handy self made command line utilities

Find any git repos with uncommitted changes. Get rid of the grep pipe if you want it to report repos with untracked files as well. I'm not much of a stickler for .gitignores so I threw this in.

#!/bin/bash

REPOPATH=$HOME

while read repo; do
  cd ${repo}/..
  [[ $(git status -s | grep -v "^??" | wc -l) -gt 0 ]] && echo "${repo//.git}"
done < <(find $REPOPATH -type d -name '.git')

Last edited by falconindy (2010-04-25 17:34:34)

Offline

#1012 2010-04-25 17:16:01

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

Re: Post your handy self made command line utilities

-name '.git' would probably be faster than regex

Offline

#1013 2010-04-25 17:34:22

falconindy
Developer
From: New York, USA
Registered: 2009-10-22
Posts: 4,111
Website

Re: Post your handy self made command line utilities

Er, right... For some reason I was thinking that using -name '.git' would return the subdirectories under .git as well.

Offline

#1014 2010-04-26 07:24:42

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

Re: Post your handy self made command line utilities

restart all daemons:

#!/bin/bash
# restart all daemons that are defined in /etc/rc.conf
source /etc/rc.conf
if [ ${#DAEMONS[@]} -gt 0 ]; then
    for (( i = ${#DAEMONS[@]} -1; i >=0; i-- ))    do
        "/etc/rc.d/${DAEMONS[i]#@}" restart
    done 
fi

Last edited by rwd (2010-04-27 06:46:37)

Offline

#1015 2010-04-28 03:51:57

Orm
Member
Registered: 2009-08-10
Posts: 24

Re: Post your handy self made command line utilities

Haven't really made any command line utilities, but I have a few useful aliases in my .bashrc

alias quakelive='LD_PRELOAD=/usr/lib/libpng12.so /usr/bin/firefox http://www.quakelive.com'
alias tf2='cd ~/.wine/drive_c/Program\ Files/Steam; WINEDEBUG=-all wine steam.exe -applaunch 440 -nointro -dxlevel 81 -width 1440 -height 900;'
#always fun to use/abuse this when I'm tunneled and my parents/brother are home. they have no idea what's going on. =p
alias speak='espeak -a 200 \!^'

Clever tagline here.

Offline

#1016 2010-04-29 14:13:12

starfreakclone
Member
Registered: 2010-01-06
Posts: 9

Re: Post your handy self made command line utilities

Here is a simple program that counts the amount of time a user has been logged into the system.

# Initialize some vars
curTime=`date +%s`
min=
hour=
user=
formatOps=
format=

# Purpose: Simple help function when a user gets lost
function help() {
   cat << EOF
Usage $0 [OPTION]... [USER]...
See how long a user has been logged in
   -F FORMAT, --format=FORMAT
                          Indicate output format if
                          no format is indicated then
                          the %W format is used
   -h, --help             Show quick help info
   -u, --user             Target user

   FORMAT can follow the forms:
     %W   Show time in words (e.g., 1 hour 23 minutes)
     %k   Show time in clock format (e.g., 01:23)
     %M   Show time in minutes (e.g., 73 minutes)
     %S   Show time in seconds (e.g., 4380 seconds)
     %d   Add date to the format (e.g., 01:23 Thu Feb 4 MST 2010)
EOF
}

# Purpose: The die function is designed for exiting the program if an error
#          occurred on input or some other failure
function die(){
   if [ -n "$1" ]
   then
      echo $1
   fi
   exit 1
}

# Purpose: unique will determine if the user specified is logged in more than
#         once on the system
function unique() {
   if [ ! $(who | grep -w $user | awk -F" " '{ print $1 }' | uniq -u) ]
   then
      return 1
   else
      return 0
   fi
}

# Purpose: This function will parse the format arguments and format the time
#         output as per argument
function formatTime() {
   if [ -z $formatOps ]
   then
      formatOps="%W"
   elif [ $formatOps = "%d" ]
   then
      formatOps="%W%d"
   fi
   if [ -z `grep % <<<"$formatOps"` ]
   then
      die "$0: missing \`%' operand"
   fi
   for op in $(awk -F% '{ for (i=2;i <= NF;i++) {printf("%s\n", $i);} }'<<<"$formatOps")
   do
      case $op in
         W)
            if [ $1 -eq 0 ]
            then
               if [ $2 -gt 1 ]
               then
                  format="$format $2 minutes "
               else
                  format="$format $2 minute "
               fi
            elif [ $1 -eq 1 ]
            then
               if [ $2 -eq 0 ]
               then
                  format="$format $1 hour "
               elif [ $2 -eq 1 ]
               then
                  format="$format $1 hour $2 minute "
               else
                  format="$format $1 hour $2 minutes "
               fi
            else
               if [ $2 -eq 0 ]
               then
                  format="$format $1 hours "
               elif [ $2 -eq 1 ]
               then
                  format="$format $1 hours $2 minute "
               else
                  format="$format $1 hours $2 minutes "
               fi
            fi
            ;;
         k)
            if [ $1 -lt 10 ]
            then
               if [ $2 -lt 10 ]
               then
                  format="$format 0$1:0$2 "
               else
                  format="$format 0$1:$2 "
               fi
            else
               if [ $2 -lt 10 ]
               then
                  format="$format $1:0$2 "
               else
                  format="$format $1:$2 "
               fi
            fi
            ;;
         M)
            totalMin=$(($1*60+$2))
            if [ $totalMin -eq 1 ]
            then
               format="$format $totalMin minute "
            else
               format="$format $totalMin minutes "
            fi
            ;;
         S)
            totalSec=$((60*($1*60+$2)))
            format="$format $totalSec seconds "
            ;;
         d)
            format="$format $(date "+%a %b %d %Z %Y") "
            ;;
         *)
            die "$0: invalid option $op"
            ;;
         esac
   done
   echo "$format"
   return 0
}

# Purpose: If the user is logged in multiple times this function will handle
#         printing the how long each has been on and their TTY location
function findTimeNotUniq() {
   for i in $(who | grep -w $user | awk -F" " '{ print $2":"$3":"$4 }')
   do
      pts=$(cut -d: -f1 <<<"$i")
      loginTime=$(cut -d: -f2<<<"$i")
      loginTime=""$loginTime" $(cut -d: -f3,4<<<"$i")"
      loginTime=$(date -d "$loginTime" +%s)
      dt=$((curTime-loginTime))
      min=$(((dt/60)%60))
      hour=$((dt/3600))
      format="on $pts "
      formatTime $hour $min
   done
   return 0
}

# Purpose: Since the user is logged in only once we only need how long he/she
#          has been logged in for
function findTimeUniq() {
   loginTime=$(who | grep -w $user | awk -F" " '{ print $3,$4 }')
   loginTime=$(date -d "$loginTime" +%s)
   dt=$((curTime-loginTime))
   min=$(((dt/60)%60))
   hour=$((dt/3600))
   formatTime $hour $min
   return 0
}

# Purpose: Starts the whole shebang, equivalent to a main() function
function initialize() {
   if [ -z $user ]
   then
      user=$USER
   fi
   unique
   if [ $? -gt 0 ]
   then
      findTimeNotUniq
   else
      findTimeUniq
   fi
   exit 0
}

# Parse some arguments
while [ $1 ]
do
   case "$1" in
      -*) true ;
         case "$1" in
            "-h"|"--help")
               help
               die
               ;;
            "-u"|"--user")
               if [[ $2 == -* ]]
               then
                  die "$0: $1 $2 improper argument syntax"
               elif [ -z $2 ]
               then
                  die "$0: cannot recognize input"
               fi
               user=$2
               if [ ! `users | grep -ow $user | head -n1` ]
               then
                  die "$0: \`$user' does not exist"
               fi
               shift 2
               ;;
            "-F")
               if [[ $2 == -* ]]
               then
                  die "$0: $1 $2 improper argument syntax"
               elif [ -z $2 ]
               then
                  die "$0: cannot recognize input"
               fi
               formatOps=$2
               shift 2
               ;;
            --format=*)
               formatOps=$(cut -d= -f2<<<"$1")
               shift 1
               ;;
            -*)
               help
               die "$0: $1 invalid argument"
               ;;
         esac
      ;;
      *) true ;
         help
         die "$0: $1 improper syntax"
   esac
done

initialize

Offline

#1017 2010-04-29 14:34:39

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

Re: Post your handy self made command line utilities

Doesn't `last` do that?

Offline

#1018 2010-04-29 14:43:19

starfreakclone
Member
Registered: 2010-01-06
Posts: 9

Re: Post your handy self made command line utilities

Daenyth wrote:

Doesn't `last` do that?

I know, its been done, but I wanted it formatted a bit differently I suppose...

Offline

#1019 2010-04-29 14:56:32

Kitty
Member
From: The Burning Desert
Registered: 2008-01-11
Posts: 88

Re: Post your handy self made command line utilities

Here's a little script that makes setting up script files a bit easier. Nice for when you're doing exercises from a programming book, and keep making little files for each concept.

#!/usr/bin/env bash

##
# Script to setup script frameworks
#

makeit()
{
    echo -n "Filename: "
    read myFile
    echo -n "Summary: "
    read mySum

    cat > $myFile <<-EOF
    #!/usr/bin/env $1
    
    ##
    # File: $myFile -- $(date)
    # $mySum
    
    
EOF
    chmod ug+x $myFile
    exec vim $myFile
}

case $1 in
    py) 
    makeit "python"
    ;;
    bash)
    makeit "bash"
    ;;
    sh)
    makeit "sh"
    ;;
    *)
    echo "Specify script type."
    ;;
esac

/etc/rc.d/ is where daemons reside. Beware.

Offline

#1020 2010-04-29 15:00:10

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

Re: Post your handy self made command line utilities

Have it take filename from $1 and make file based on the extension. bash/sh should be /bin/bash /bin/sh, not /usr/bin/env. There's a -p option to read for the prompt too.

Offline

#1021 2010-04-29 15:09:47

Kitty
Member
From: The Burning Desert
Registered: 2008-01-11
Posts: 88

Re: Post your handy self made command line utilities

#!/usr/bin/env bash does seem to work ok for my shell scripts. But I see your point as it's non-standard, and un-portable. But it was made to automate making the throwaway practice scripts.

Thanks for the tip on read.


/etc/rc.d/ is where daemons reside. Beware.

Offline

#1022 2010-04-29 15:16:51

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

Re: Post your handy self made command line utilities

-p isn't sh-compatible, but since you're using bash it doesn't matter smile

Offline

#1023 2010-05-02 02:03:14

Sara
Member
From: USA
Registered: 2009-07-09
Posts: 219
Website

Re: Post your handy self made command line utilities

I've modified the script I posted earlier. The script asks how long it'll be in a nice graphical window, and then flashes an alert in the top left corner of the screen when the time is up (for me, that means it temporarily overlays my xmobar, and as it has the same background color as my xmobar, and same font, it's pretty nifty).

#!/bin/bash
scriptdir="/home/sara/.scripts"
timelength=`zenity --entry --text "How long?" --entry-text "Time (in minutes)" --title "Starting uTimer"`
utimer -t ${timelength}m > $scriptdir/.timer
seconds=$(($timelength * 60))
time=`cat $scriptdir/.timer | grep '${seconds}'`

if [ -n $time ]; then
 (echo 'Time is up!') | dzen2 -p 5 -x 1 -y 0 -w 250 -h 10 -fn "kroeger 05_55-6:medium" -fg red -bg white
fi

Last edited by Sara (2010-06-13 10:57:57)


Registed Linux User 483618

Offline

#1024 2010-05-03 15:14:34

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

Re: Post your handy self made command line utilities

This script allows one to use mplayer to play youtube videos.  I saw this script in perl posted on the boards somewhere.  Here it is in bash:

$ SCRIPTNAME "http://youtube_url"  ## usage
$ mpyt.sh "http://www.youtube.com/watch?v=XgDh1S0nUV0"  ## example
#!/bin/bash

saveIFS=$IFS
IFS=$'\n'
declare -a ids=( $(curl -Ls "$1" | awk -F'"' 'BEGIN {RS = ","} /"t":|"video_id":/ {print $4}') )
IFS=$saveIFS

t=${ids[0]}
video_id=${ids[1]}

mplayer -cache 256 "http://www.youtube.com/get_video?video_id=${video_id}&t=${t}"

Last edited by steve___ (2010-05-03 15:20:42)

Offline

#1025 2010-05-03 16:37:12

TaylanUB
Member
Registered: 2009-09-16
Posts: 150

Re: Post your handy self made command line utilities

So a few days back at /b/, someone was asking for a screen recording program, and for trolling purposes i wrote a few lines of POSIX sh that would loop `scrot`, and said to make a video of it with mencoder.

What's fun is that the idea had nothing wrong in theory; and guess what ... this script works:

(The following is a quickly written draft with dirty code.)
(The functions sourced from "common_stuff.sh" have descriptive enough names, i don't feel the need to explain.)

#!/bin/sh
#
# screenrec.sh: POSIX sh based screen recorder that relies on scrot and mencoder.
#               You also need bc, and your `sleep` must support floats.
#

. "$HOME"/.scripts/common_stuff.sh

rtfm(){ echo rtfm; exit 1; }

test $# -ge 2 || rtfm

file="$1"; shift
time="$1"; shift
test "$1" && { fps="$1"; shift; } || fps=10

test $# -eq 0 || rtfm

test_ints "$time" "$fps" || rtfm
test $time -gt 0 && test $fps -gt 0 || rtfm

imgcount=$(($time*$fps))
sleep=$(echo "scale=9; 1/$fps" | bc)

make_tmp_dirs imgdir || exit 2

for i in $(seq -w 1 $imgcount)
do
    scrot "$imgdir"/$i.jpg
    sleep $sleep
done

mencoder mf://"$imgdir"/* -mf fps=$fps -o "$file".avi -ovc lavc -lavcopts vcodec=mpeg4 > /dev/null 2>&1

rm -f "$imgdir"/*

The system gets choppy like watching a 2 FPS movie while recording is on, due to the small freeze you get when invoking scrot.
The time option is quite off, and FPS is really broken, i think both because of the above mentioned issue.

I'll work on something that detects the really passed time.
Perhaps achieving FPS higher than about 2 is not possible without a screenshotter that causes no freezes, but at least i should be able to record movies with proper timing...

Last edited by TaylanUB (2010-05-03 16:40:11)


``Common sense is nothing more than a deposit of prejudices laid down by the mind before you reach eighteen.''
~ Albert Einstein

Offline

Board footer

Powered by FluxBB