You are not logged in.

#51 2008-10-18 15:37:40

lefallen
Member
From: Melbourne, Australia
Registered: 2006-07-06
Posts: 36
Website

Re: Post your handy self made command line utilities

phrakture wrote:
Allan wrote:

Kill gnome-screensaver before starting mplayer

Just an FYI. xscreensaver has a -disable command that disables the screensaver for some time. You can use that with mplayer's "heartbeat-cmd" setting - might be cleaner to do it that way

Just another FYI, mplayer has a -stop-xscreensaver option too tongue  That's all I use.


JABBER: lefallen -A-T- jabber.quadronyx.com.au
E-MAIL: archlinuxforums -A-T- quadronyx.org
BLOG: http://www.quadronyx.com.au/blogs/fallen
~o~

Offline

#52 2008-10-20 02:02:13

fflarex
Member
Registered: 2007-09-15
Posts: 466

Re: Post your handy self made command line utilities

This one is just an alias, nothing too hard about it, but I think it's rather unique. Or at least, I've never heard of anyone else doing this:

alias ls='ls --color=auto $( if [ -f .hidden ]; then cat .hidden | xargs -I {} echo -n --hide="{}"\ ; fi; )'

What this will do is hide any files listed in a file named .hidden in the current directory when you run ls (one file per line). You can still see them when you do 'ls -a', just like other hidden files. I did this to simulate nautilus's behavior (and maybe kde's?), but then I realized that it does not work if you are listing a directory other than the current directory. Plus there will be issues with extra files getting hidden if you try to list multiple directories. If anyone can suggest a way around this without completely rewriting ls, please do. But it works well enough for me.

It lets you hide annoying directories that don't start with a dot (like Desktop). Although there is probably a better way to do this if you don't care about using the .hidden files that nautilus uses.

Last edited by fflarex (2008-10-20 02:14:35)

Offline

#53 2008-10-20 02:25:34

fflarex
Member
Registered: 2007-09-15
Posts: 466

Re: Post your handy self made command line utilities

Here's another one of mine. I use this one at least 10x a day (plus I use it in other scripts of mine), and it's the first script I've ever written and considered suitable for other people (as in, the code is fairly clean, it can handle stupid user input, has a help message, is pretty flexible, and is not heavily dependent on my individual setup).

I got some help making this in another thread, but I have significantly expanded on the code that I was given (plus I converted it from perl to bash).

#!/bin/bash
# 
# ~/bin/mpd-on-change - Waits for MPD's status to change (usually the end of a
#                       song), and optionally executes an action afterwards.

# Print a help message
function usage {
    echo "
mpd-on-change  -  Waits for MPD's status to change (usually the end of a song),
                  and optionally executes an action afterwards.

Usage: mpd-on-change [[-i | --interval] seconds] [[-n | --songs] songs] \\
                     [[-a | --action] command.. ]

Options:
  -a, --action    Execute some action after song(s) finish. Anything after this
                  option is taken to be a command.
  -i, --interval  Set the time between checking the current song. May be in any
                  format supported by sleep. Default is 2.
  -n, --songs     Set the number of songs to wait for. Default is 1.
  -h, --help      Display this help message and exit.

Note  that stopping a song, or starting one when MPD is stopped,  will signal a
change as if the song had finished.  This script requires that mpc be installed
and MPD be running.
"
}

# What to do in case of incorrect usage
function error_exit {
    usage
    exit 1
}

# Makes sure mpc is installed and mpd is running
if [ `mpc | wc -l` -eq 0 ]; then
    error_exit
fi

# $number is the number of songs to complete before finishing up
# $interval is the length of time between checking the current song
# $action is what is executed after the songs play

number=1
interval=2
action=:

# Detect command line arguments
while [ "$1" != "" ]; do
    case $1 in
        -a | --action )     shift
                            action=$*
                            break
                            ;;
        -i | --interval )   shift
                            interval=$1
                            ;;
        -n | --songs )      shift
                            number=$1
                            ;;
        -h | --help )       usage
                            exit
                            ;;
        * )                 error_exit
    esac
    shift
done

# Tests that $number is a non-negative integer
test $number -ge -1 2> /dev/null || error_exit

# Tests to see if $interval is valid input for sleep
# Note that this adds an extra sleep command, which usually won't matter
sleep $interval 2> /dev/null || error_exit


# $song keeps track of which song needs to finish
# $cur_song is the currently playing song

song=`mpc | head -n 1`
cur_song=$song

# $count keeps track of how many songs have finished playing
# This is the meat of the program, which periodically checks the current song
count=0
until [ $count -eq $number ]; do
    while [ "$cur_song" = "$song" ]; do
        sleep $interval
        cur_song=`mpc | head -n 1`
    done
    count=$((count + 1))
    song=`mpc | head -n 1`
done

# Action to be executed at the end, default does nothing
$action

It won't work if you play the same song twice in a row, and I may or may not fix that sometime. It would make the script more complex, but it has already grown larger than I originally expected, so we'll see.

Last edited by fflarex (2008-10-20 02:37:45)

Offline

#54 2008-10-20 15:27:33

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

Re: Post your handy self made command line utilities

Here is a dmenu launcher that will keep a history.

I have posted this before in another thread, but I can't remember where. Yesterday I made an improvement of using "setsid setsid program" because with just one the launcher will remain as a process for some reason.

Before using, it expects ~/.dddmenu to exist, so: touch ~/.dddmenu, and optionally put some programs in there.

Tip for dmenu vertical patch:
Substitute newentry=$(dmenu -i -p ":" < ~/.dddmenu)
With: newentry=$(dmenu -i -l 5 -rs -ni -xs -p ":" < ~/.dddmenu)

#!/bin/dash
newentry=$(dmenu -i -p ":" < ~/.dddmenu)
[ -z "$newentry" ] && exit
[ -z "$( (cat ~/.dddmenu; echo "$newentry") | sort | uniq -d)" ] && echo "$newentry" >> ~/.dddmenu

eval setsid setsid $newentry
exit 0

Offline

#55 2008-10-22 15:51:48

wimac
Member
From: Michigan, USA
Registered: 2008-06-06
Posts: 20
Website

Re: Post your handy self made command line utilities

Here is my backup script archives and saves to local disk and server with log.


#!/bin/bash
# $Id: wjm_backup  06-25-2008 09:30AM v.08.177.0930 wimac Exp $
# backup homefiles to server and local drive
# Last modified: 10-22-2008  11:44AM wimac
# by William J. MacLeod (wimac1@gmail.com)

#remote server host and dir.
REPO_HOST="user@server.com"
REPO_DIR="/home/remoteserver/backup "

# The backups should probably be stored in /var somplace:
REPOSITORY=/var/tmp
TIMESTAMP=$(date '+%m%d%Y-%H%M')
HOSTNAME=$(hostname)
ERRMSGS=/home/wimac/logs/backup-etc.$$
FILE="$REPOSITORY/$HOSTNAME-config-backup-$TIMESTAMP.tgz"
PROG=${0##*/}

# Files that need to be backed up.
DOT_FILES="
/home/wimac/.aliasrc
/home/wimac/.zshrc
/home/wimac/.bashrunrc
/home/wimac/.vimrc
/home/wimac/.gvimrc
/home/wimac/.mpdconf
/home/wimac/.Xresources
/home/wimac/.adesklets
/home/wimac/.bashrc
/home/wimac/.blackboxrc
/home/wimac/.pypanelrc
/home/wimac/.ratpoisonrc
/home/wimac/.screenrc
/home/wimac/.screenrc-galt
/home/wimac/.signature
/home/wimac/.zfunc
/home/wimac/.zlogout
/home/wimac/.zlogin
/home/wimac/.zshrc
/home/wimac/.muttrc
/home/wimac/.xinitrc
/home/wimac/.xenv
/home/wimac/.mozilla/firefox/ik15goe6.default/bookmarks.html
/home/wimac/.config
/home/wimac/pkglist
"
#Dirs that need to be backed up.
DIRS="
/etc
/home/wimac/.config
/home/wimac/.AbiSuite
/home/wimac/.vim
/home/wimac/.sipie
/home/wimac/.zim
/home/wimac/bin
/home/wimac/Notes
/home/wimac/Desktop/Documents
/home/mary/Desktop/Documents
"
usage()
{  echo "This script creates a backup of config files via tar in $REPOSITORY."
   echo "Usage: $PROG [OPTIONS]"
   echo '  Options:'
   echo '    -v, --verbose   displays some feedback (dots) during backup'
   echo '    -h, --help      displays this message'
   echo '    -V, --version   display program version and author info'
   echo
}

# create archive
archive() {
echo creating archive $FILE
tar -czvp --force-local -f $FILE $DOT_FILES $DIRS 2> $ERRMSGS 
}

backup() {
echo sending $FILE to $REPO_HOST:$REPO_DIR
scp $FILE $REPO_HOST:$REPO_DIR
}
encrypt() {
echo encrypting $FILE
gpg -e --symmetric $FILE
}
# Command line argument processing:
while [ $# -gt 0 ]
do
   case "$1" in
      -h|--help)     usage; exit 0; ;;
      -V|--version)  echo -n "$PROG version $VERSION "
                     echo 'Written by William J. MacLeod <wimac1@gmail.com>'
             exit 0; ;;
      *)             usage; exit 1; ;;
   esac
   shift
done

trap "rm -f $ERRMSGS" EXIT

archive
backup

# Log any error messages produced:
if [ -s "$ERRMSGS" ]
then logger -p user.error -t $PROG "$(cat $ERRMSGS)"
else logger -t $PROG "Completed backup of config files"
fi

exit 0

Comments welcome...


.wimac

//screenshots//configs//

Offline

#56 2008-10-22 15:58:05

Xyne
Moderator/TU
Registered: 2008-08-03
Posts: 5,633
Website

Re: Post your handy self made command line utilities

Pass this the path to fstab as an argument. It will arrange the data in the fstab file in proper columns for greater legibility. As an added safety measure, it will print the original file and the reformated file to STDOUT so that you can inspect and compare it before overwriting the old one.

#! /usr/bin/perl
use warnings;
use strict;

my $fstabFile = shift;
my $fstabOld;
my $fstab;
my @fstabLines;
push @fstabLines, ['# <file system>', '<dir>', '<type>', '<options>', '<dump>', '<pass>'];
my @lengths = map {length($_)} @{$fstabLines[0]};
my $longestLine;

open(my $fh, '<'. $fstabFile) or die "Unable to open $fstabFile: $!\n";
while(defined(my $line =<$fh>))
{
    $fstabOld .= $line;
    $longestLine = (length($line) > $longestLine) ? length($line) : $longestLine;
    if ($line =~ m/^#/ and $line !~ m/<file system>/)
    {
        $fstab .= $line;
    }
    elsif ($line =~ m/^#/ and $line =~ m/<file system>/)
    {
        next;
    }
    else
    {
        $line =~ s/ +/ /g;
        my @fields = split ' ',$line;
        push @fstabLines, \@fields;
        for (my $i; $i < scalar @fields; $i += 1)
        {
            if (length($fields[$i]) > $lengths[$i])
            {
                $lengths[$i] = length($fields[$i]);
            }
        }
    }

}
close $fh;

my $printfStr = join '', map( {'%-'.($_+1).'s';} @lengths);

foreach my $line (@fstabLines)
{
    my @line = @{$line};
    $line = sprintf($printfStr, @line)."\n";
    $fstab .= $line;
    $longestLine = (length($line) > $longestLine) ? length($line) : $longestLine;
}

my $separator = ('-' x $longestLine)."\n";

print "\n",$separator, "ORIGINAL FILE\n", $separator, $fstabOld, $separator, "REFORMATTED FILE\n", $separator, $fstab, $separator;

print "Overwrite old file with new one? (y/n) ";
my $ans = <>;
chomp $ans;
if ($ans eq 'y')
{
    open(my $fh, '>', $fstabFile) or die "Unable to open $fstabFile: $!\n";
    print $fh $fstab;
    close $fh;
}
else
{
    print "Exiting without saving...\n";
    exit;
}

Offline

#57 2008-10-22 17:14:52

lilsirecho
Veteran
Registered: 2003-10-24
Posts: 5,000

Re: Post your handy self made command line utilities

Operating in faunos system with raid0 array containing .pkg.tar.gz directories.

System normally loads Bon Echo in firefox.


To enable Gran Paradiso (in 2.6.24 kernel system of faunos), the appropriate commands are provided in /root/home file named firefox3.  This file has the following:

...............mount -t ext3 /dev/md1 /mnt/md ; pacman -Rd gail ; pacman -Uf /mnt/md/upgrade/firefox1/*......................

The removal of ..gail.. is necessary to prevent conflict with gtk2.  The mount command mounts the raid0 array and the pacman -Uf loads firefox-3.0.2-1 from the raid array. 

In root terminal, this file is entered as a bookmark as follows:

..............................command  /home/guest/firefox3......

The three operations are then performed to install firefox3 in ram.

This arrangement is saved and is performed as user desires.

Upon reboot, the system returns to Bon Echo(session save not enabled).

EDIT: The raid array umount could be appended to the /home/guest/firefox3 file to unmount the /dev/md1.
The raid0 firefox1 folder contains all depends for firefox-3.0.2-1.
Other options in the bookmarks include FEH, WINE,VLC, and a mount command for raid0.  More such options will be added to permit a reduction in the boot size of faunos, such as OPERA,AVIDEMUX,CINELERRA,CODEINE,STELLARIUM, and OPENOFFICE among many others.
This arrangement using the command option in bookmarks was necessary because the entry of the  necessary several operations exceeded the size limits for the bookmark entries.

Last edited by lilsirecho (2008-10-22 20:50:24)


Sign of the times: Navajo blanket..made in China
Hard work does not kill people but why risk it: Charlie Mccarthy
A man is not complete until he is married..then..he is finished.
When ALL is lost, what can be found? Even bytes get lonely for a little bit!     X-ray confirms Iam spineless!

Offline

#58 2008-10-25 18:07:27

icetonic
Member
From: Germany
Registered: 2008-10-21
Posts: 103

Re: Post your handy self made command line utilities

WLAN reconnect if for some reason it gets disconnected and all stats seem normal (tests connection with ping to router)

#!/bin/bash
#iCETonic's wlanrecon.sh - Reconnects if can't ping router (execute as root!)
#Usage: wlanrecon.sh CHECKINTERVAL PROFILE &
while [ 1 = 1 ]; do                #Infinite loop
    sleep $1                    #Wait
    ping -c 1 dsldevice.lan
    if [ "$?" = "2" ]; then        #If ping gave back an error
        sudo netcfg -d $2        #Disconnect
        sudo netcfg $2            #Connect
    fi
done

My good-night-MPD-script

#!/bin/bash
#iCETonic's mpdshutdown.sh - Shutdown PC after MPD stops playing

#Info-Warning
echo "System is going to halt after MPD has finished playing! ^C to abort"

#Check loop
while [ "$(mpc playlist | head -c 1)" != ">" ] && [ "$(mpc | wc -l)" != "1" ]
    do
        sleep 10
    done

#Finished -> Shutdown
sudo shutdown -h now

Last edited by icetonic (2008-10-25 18:08:02)

Offline

#59 2008-11-07 15:19:01

muflax
Member
From: Germany
Registered: 2008-07-21
Posts: 58

Re: Post your handy self made command line utilities

Just did something cool with bash, so I decided to share it with  you. They are just aliases for your .bashrc, but there is no recent thread for them, so yeah. (And I really have to convert to zsh soon...) I improved readability on some for this thread.

Extended mplayer functionality

#those are written for mplayer, but work with other players as well, of course
#send video to specific screen with a small hack against lag on one (I only use mplayer in the other aliases for simplicity)
alias lmplayer="DISPLAY=:0.1 mplayer"
alias rmplayer="DISPLAY=:0.0 mplayer -delay -0.05"

#increase volume
alias maf="mplayer -af volume=15"

#playlist functionality
#usage: sm() format start end; so to play a section of my ケ
ロロ collection, I'd enter "sm %03d 17 36", which matches *017* to *034*
#.last is used to save the last played file, so you can use something like "sm %03d `cat .last` 100" to continue where you left off
#Oh, and to abort, in case you didn't know this, you can enter ^Z to pause the process and "kill %" to terminate it.
function sm() { LIST=`seq "$2" "$3"`; for x in `printf "$1 " $LIST`; do echo -n "$x" > .last; cowsay -f small "now playing: $x"; mplayer *"$x"*; done; }

Offline

#60 2008-11-08 22:35:17

Cene
Member
From: Laukaa, Finland
Registered: 2008-11-06
Posts: 16
Website

Re: Post your handy self made command line utilities

I don't really know which scripts I've written anyone else could find useful or are "small enough", but here goes one I just wrote today to make the monitoring of my web server logs a bit easier.

It requires lighttpd to be logging with the default log format. It acts a lot like `tail -f logfile`, but filters out information you don't usually need but is still good to have just in case, and colors the output for better readability.

#!/usr/bin/env perl
use strict;
use warnings;
use File::Tail;
use Term::ANSIColor qw(:constants);

use constant FILE   =>  "/var/log/lighttpd/access.log";
our @accepted = (200, 201, 202, 203, 204, 205, 206, 301, 304);

sub main {
  my $ref=tie *FH,"File::Tail",(name=>FILE, maxinterval=>1);
  while(<FH>) {
    my $a = 0;
    my($ip,$date,$what,$status,$len,$ref) =
      $_ =~ /([^ ]+) .+? - \[([^\]]+)\] "([^"]+)" (\d+) (\d+) "([^"]+)".+/;
    print STDOUT
      (BOLD, BLUE,
      $ip,
      RESET, WHITE,
      " ",
      YELLOW,
      $date." ",
      WHITE,
      "\"",
      BOLD,BLUE,
      $what,
      RESET, WHITE,
      "\" ");
    for(@accepted) {
      if($status == $_) {
        $a = 1;
        last;
      }
    }
    print STDOUT
      (($a)?
        GREEN : (BOLD,RED),
      $status,
      RESET,YELLOW,
      " " .$len,
#      WHITE,
#      " " . $ref,
      RESET,
    "\n");
  }
}

main();

Output looks like this (the censored part being the IP where the request came from):
lighttpd.png

Offline

#61 2008-11-09 01:24:27

Cilyan
Member
From: Toulouse (FR)
Registered: 2006-08-27
Posts: 93
Website

Re: Post your handy self made command line utilities

I have a little script to use in my openbox menu. It is coupled with an entry in /etc/sudoers of course.

#!/bin/sh

if [ `id -ur` != 0 ]; then
    echo "You must have root privilege."
    exit 1
fi

while getopts g:p:m:M: arg
do
    case "$arg" in
        g)
            /usr/bin/cpufreq-set -g "$OPTARG";;
        m)
            /usr/bin/cpufreq-set -d "$OPTARG";;
        M)
            /usr/bin/cpufreq-set -u "$OPTARG";;
        p)
            case "$OPTARG" in
                suspend)
                    /usr/sbin/pm-suspend;;
                halt)
                    /sbin/halt;;
                reboot)
                    /sbin/reboot;;
                *)
                    echo "$0 -p (suspend|halt|reboot)";;
            esac;;
        *)
            echo "Usage:"
            echo "$0 [-p (suspend|halt|reboot)] [-g governor] [-m freq] [-M freq]"
            echo "For gevernor or freq, see help about cpufreq-set -g and cpufreq-set -d -u";;
    esac
done

This script is very handy when dealing with networks you don't trust (public ones, ...). But I'm afraid comments are in french...

#!/bin/bash
# Connection script for unsafe networks

TMPFILE="/tmp/safe_connect.params"
CRITICAL_DAEMONS="sshd samba httpd mysqld avahi-daemon avahi-dnsconfd cups portmap"

#######################################################################
# Colors
COL_NO="\033[0m"
COL_GREEN="\033[1;32m"
COL_RED="\033[1;31m"
COL_YELLOW="\033[1;33m"
FONT_BOLD="\033[1m"

#######################################################################
# Beautifying functions
msg()
{
    echo -e "${COL_GREEN}==> ${COL_NO}${FONT_BOLD}$1${COL_NO}"
}

warning()
{
    echo -e "${COL_YELLOW}==> ${COL_NO}${FONT_BOLD}$1${COL_NO}"
}

error()
{
    echo -e "${COL_RED}==> ${COL_NO}${FONT_BOLD}$1${COL_NO}"
}

note()
{
    echo -e "$1"
}

#######################################################################
# Utility functions
deactivate_daemon()
{
    if [ -x /etc/rc.d/$1 ] ; then
        if ! /etc/rc.d/$1 stop | grep FAIL > /dev/null ; then
            note "Daemon ${FONT_BOLD}$1${COL_NO} ${COL_GREEN}arrêté${COL_NO}"
            return 0
        fi
    fi
    return 1
}

activate_daemon()
{
    if [ -x /etc/rc.d/$1 ] ; then
        if ! /etc/rc.d/$1 stop | grep FAIL > /dev/null ; then
            note "Daemon ${FONT_BOLD}$1${COL_NO} ${COL_GREEN}démarré${COL_NO}"
            return 1
        fi
        note "Le démarrage de ${FONT_BOLD}$1${COL_NO} a ${COL_RED}échoué${COL_NO}"
    fi
    return 0
}

deactivate_daemons()
{
    VALID_DAEMONS=""
    for daemon in $@; do
        deactivate_daemon $daemon && (VALID_DAEMONS=${VALID_DAEMONS}" "${daemon})
    done
    echo "VALID_DAEMONS=\"${VALID_DAEMONS}\"" >> $TMPFILE
}

activate_daemons()
{
    for daemon in $@; do
        activate_daemon $daemon
    done
}

prepare_connection()
{
    if [ $care_daemons -eq 1 ]; then
        msg "Arrêt des démons potentiellement dangereux"
        deactivate_daemons $CRITICAL_DAEMONS
    fi
    
    if [ $stop_ifaces -eq 1 ]; then
        msg "Arrêt des autres interfaces"
        killall wpa_supplicant > /dev/null
        killall dhcpcd > /dev/null
        for iface in `ifconfig -s -a | awk '{print $1}' | grep -v Iface | grep -v lo`; do
            if [ $iface != "lo" ] ; then
                ifconfig $iface down &> /dev/null && ( \
                    note "Interface ${FONT_BOLD}$iface${COL_NO} ${COL_GREEN}arrêtée${COL_NO}"; \
                    ) || ( \
                    note "Interface ${FONT_BOLD}$iface${COL_NO} ${COL_RED}non arrêtée${COL_NO}"; \
                    )
            fi
        done
    fi
    
    if [ $change_mac -eq 1 ]; then
        msg "Modification de l'adresse MAC"
        if [ -z $MAC ] ; then
            MAC=`mactool -go`
        fi
        CONST=`mactool -f $MAC`
        ifconfig $wifi_iface up hw ether $MAC &> /dev/null && ( \
            note "Adresse MAC changée en $MAC"; \
            note "Associated $CONST"; \
            ) || ( \
            error "Impossible de changer l'adresse MAC. Essayez manuellement et "; \
            error "relancez le script avec l'option -DIM"; \
            note "Adresse MAC suggérée : $MAC"; \
            note "Associated $CONST"; \
            return 1;
            )
    fi
}

configure_network()
{
    msg "Utilisation d'un réseau préconfiguré"
    case "$1" in
        mynet)
            NET="MyNet"
            KEY="00:11:22:33:44:55"
            CHANNEL="11"
            note "Réseau ${FONT_BOLD}$NET${COL_NO} ${COL_GREEN}chargé${COL_NO}"
            return 0;;
        *)
            error "Réseau inconnu"
            error "Réseaux connus : mynet"
            return 1;;
    esac
}

loop_dhcpcd()
{
    msg "Configuration de l'Internet"
    killall dhcpcd &> /dev/null
    dhcpcd eth1 &> /dev/null
    leasedfrom=`cat /var/lib/dhcpcd/dhcpcd-eth1.info | grep -E "^LEASEDFROM" | sed -r "s/LEASEDFROM=//"`
    let i=0
    while [ $leasedfrom = "'0'" ] && [ $i -le 6 ]; do
        note "etat : ${COL_YELLOW}Pas de réponse${COL_NO}. Nouvel essai"
        killall dhcpcd
        dhcpcd eth1 &> /dev/null
        leasedfrom=leasedfrom=`cat /var/lib/dhcpcd/dhcpcd-eth1.info | grep -E "^LEASEDFROM" | sed -r "s/LEASEDFROM=//"`
        let i++
    done
    if [ $leasedfrom = "'0'" ]; then
        error "Impossible de configurer l'internet"
        return 1
    fi
    note "etat : ${COL_GREEN}connecté${COL_NO}."
    msg "Connexion réussie"
    return 0
}

join_network()
{
    msg "Configuration des paramètres réseau"
    iwconfig $wifi_iface mode managed essid "${NET}" channel $CHANNEL key $KEY && (\
            note "Configuration pour ${FONT_BOLD}$NET${COL_NO} ${COL_GREEN}reussie${COL_NO}" \
        ) || ( \
            error "Impossible de se connecter avec les paramètres :"; \
            note "Réseau : $NET"; \
            note "Canal : $CHANNEL"; \
            note "Key : $KEY"; \
            return 1; \
        )
    return 0;
}

connect()
{
    echo "#!/bin/bash" > $TMPFILE
    prepare_connection || return 1
    if [ $load_network -eq 1 ]; then
        if [ $conf_net -eq 1 ]; then
            configure_network $NETID || return 1
        fi
        join_network $NET $KEY $CHANNEL || return 1
    fi
    if [ $no_dhcpcd -ne 1 ] ; then
        loop_dhcpcd || return 1
    fi
}

disconnect()
{
    msg "Désactivation du dhcpcd"
    killall dhcpcd
    msg "Désassociation du réseau"
    iwconfig $wifi_iface essid off
    iwconfig $wifi_iface mode monitor > /dev/null || ( \
            warning "L'interface ne supporte pas le mode monitor"; \
            warning "Vous devrez vous assurer vous-même que vous n'êtes plus associé"; \
        ) && ( \
            note "Desassociation complète ${COL_GREEN}reussie${COL_NO}"; \
        )
    msg "Arrêt de l'interface"
    ifconfig $wifi_iface down || ( \
        error "Impossible d'arrêter l'interface. Droits insuffisants ?"; \
        return 1; )
    msg "Redémarrage des démons"
    # Don't work ?!
    if [ -e $TMPFILE ]; then
        . $TMPFILE
        activate_daemons $VALID_DAEMONS
        rm $TMPFILE
    else
        warning "$TMPFILE n'existe pas. Impossible de recharger les démons."
        warning "Vous devrez le faire à la main."
    fi
    return 0
}

print_help()
{
    msg "Aide"
    note "Usage : $0 [options] interface"
    note "Version : $VERSION"
    msg "Options disponibles : "
    note "-c             Connexion (par défaut)"
    note "-d             Déconnexion"
    note "-D             Ne pas arrêter les démons"
    note "-I             Ne pas s'occuper des autres interfaces"
    note "-M             Ne pas changer l'adresse MAC"
    note "-m MAC         Utiliser cette adresse MAC"
    note "-n Réseau      Utiliser le réseau prédéfini"
    note "-r Network     Utiliser ce réseau (avec -k et -c). Incompatible avec -n"
    note "-k key         Clef WEP à utiliser (peut être 'off'). Incompatible avec -n"
    note "-C channel     Canal à utiliser. Incompatible avec -n"
    note "-H             Ne pas lancer dhcpcd"
    note "-f firmware    Recharger le pilote indiqué (Peut résoudre les problèmes"
    note "               de changement de MAC)"
    note "-s demon       Recharge également le démon associé au firmware (ipw3945)."
    note "               Ne s'utilise qu'avec -f"
    note "-h             Affiche cette aide"
}

#######################################################################
# Command line parsing

let connect=1
let care_daemons=1
let stop_ifaces=1
let change_mac=1
let load_network=0
let conf_net=0
let no_dhcpcd=0
let reload_firmware=0
let special_reload=0
MAC=""
VERSION="0.1"

while getopts cdDIMm:n:r:k:C:Hf:s:h arg
do
    case "$arg" in
        c)
            let connect=1;;
        d)
            let connect=0;;
        D)
            let care_daemons=0;;
        I)
            let stop_ifaces=0;;
        M)
            let change_mac=0;;
        m)
            let custom_mac=1
            MAC=$OPTARG;;
        n)
            let load_network=1
            let conf_net=1
            NETID=$OPTARG;;
        r)
            let load_network=1
            let conf_net=0
            NET=$OPTARG;;
        k)
            let load_network=1
            let conf_net=0
            KEY=$OPTARG;;
        C)
            let load_network=1
            let conf_net=0
            CHANNEL=$OPTARG;;
        H)
            let no_dhcpcd=1;;
        f)
            let reload_firmware=1
            FIRMWARE=$OPTARG;;
        s)
            let special_reload=1
            DRIVER=$OPTARG;;
        h)
            print_help
            exit 0;;
        *)
            print_help
            exit 0;;
    esac
done

shift $(($OPTIND - 1))
if [ $# -lt 1 ]; then
    error "You must specify an interface"
    print_help
    exit 1
fi

wifi_iface=$1

if [ `id -ur` != 0 ]; then
    warning "You will probably need root privileges !"
fi

if [ $reload_firmware -eq 0 ] && [ $special_reload -eq 1 ] ; then
    error "you need to use the -f option with -s"
    exit 1
fi

if [ $reload_firmware -eq 1 ]; then
    msg "Rechargement du firmware"
    if [ $special_reload -eq 1 ] ; then 
        /etc/rc.d/$DRIVER stop
    fi
    rmmod $FIRMWARE
    modprobe $FIRMWARE
    if [ $special_reload -eq 1 ] ; then 
        /etc/rc.d/$DRIVER start
    fi
fi

if [ $connect -eq 1 ]; then
    connect || exit 1
else
    disconnect || exit 1
fi

It is coupled with mactool, a C code that generates a "known" random MAC address but the code is quite big to post it here (it includes all the known prefixes). If you're interested, I will put the code on a server.

Last edited by Cilyan (2008-11-09 01:29:11)

Offline

#62 2008-11-09 03:54:54

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

Re: Post your handy self made command line utilities

I have this aliased, it's quite handy for showing network usage. I could probably rework the greps, but it's fine.

netstat -tapn | sed '1 d' | sort -r +6 | grep -v 'TIME_WAIT' | grep -v 'FIN_WAIT' | grep -v 'LISTEN' | grep -v 'CLOSING' | grep -v 'LAST_ACK'

Offline

#63 2008-11-11 17:53:36

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

Re: Post your handy self made command line utilities

In the current directory, show recently changed files (last 24h) and sort it descendingly:

alias recent='find -maxdepth 1 -mtime -1 -printf "%Tk:%TM - %f\n" | sort -rn'

EDIT wait I made a mistake, it doesn't sort right, I just updated this myself without thorough testing. Stand by

EDIT2: above will sort yesterday's 23:00 above today's 19:00 e.g.
This should be better, but it's using unix time

alias recent='find -maxdepth 1 -mtime -1 -printf "%T@ - %f\n" | sed "s/\.0*//" | sort -rn'

Last edited by Procyon (2008-11-11 18:35:42)

Offline

#64 2008-11-11 18:00:03

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

Re: Post your handy self made command line utilities

Nifty! I use this for that:

alias lst="ls -hFtl --color=auto | grep $(date +%Y-%m-%d)"

Offline

#65 2008-11-11 18:39:35

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

Re: Post your handy self made command line utilities

@Daenyth: that's a good one. Much nicer.

Offline

#66 2008-11-11 18:57:07

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

Re: Post your handy self made command line utilities

The problem with mine compared to yours is that mine only gets items from midnight to midnight, so people up late might find it less useful.

Offline

#67 2008-11-11 21:10:21

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

Re: Post your handy self made command line utilities

OK one more try, since I was adding stuff to the end anyway, but now I use cut, which is much lighter: (NB added "-type f")

alias recent='find -maxdepth 1 -type f -mtime -1 -printf "%T@-%Tk:%TM - %f\n" | sort -rn | cut -d- -f2-'

Last edited by Procyon (2008-11-11 21:11:09)

Offline

#68 2008-11-12 13:03:03

joqueza
Member
Registered: 2008-08-16
Posts: 58

Re: Post your handy self made command line utilities

just a stupid way to randomly choose one wallpaper at time (just put this in cron):

#!/bin/bash
dir_wall=$HOME/themes/wallpapers
dir=( $(ls $dir_wall |sort) )
dir_var=${#dir[*]}

feh --bg-scale $dir_wall/${dir[$RANDOM%dir_var]}

forgot to mention the entry in autostart.sh:

while :; do ./wall.sh ; sleep 300; done &

this way this infinite loop will change every 5 minutes the wallpaper

Last edited by joqueza (2008-11-12 19:31:11)

Offline

#69 2008-11-12 20:38:30

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

Re: Post your handy self made command line utilities

here's one i got/tweaked from another thread here

#!/bin/bash
# convert filenames to lowercase
# and replace characters recursively
# usage sh renamerecursive.sh [directory]
#####################################

if [ -z $1 ];then 
    echo Give target directory; 
    exit 0;
fi

find "$1" -depth -name '*' | while read file ; do
     directory=$(dirname "$file")
     oldfilename=$(basename "$file")
     newfilename=$(echo "$oldfilename" | tr 'A-Z' 'a-z' | tr ' ' '_' | sed s/_-_/_/g)
     #newfilename=$(echo "$oldfilename" | sed s/_-_/_/g)
     #newfilename=$(echo "$oldfilename" | tr 'A-Z' 'a-z')
     #newfilename=$(echo "$oldfilename" | tr ' ' '_')
     if [ "$oldfilename" != "$newfilename" ]; then
          mv -i "$directory/$oldfilename" "$directory/$newfilename"
          echo ""$directory/$oldfilename" ---> "$directory/$newfilename""
     fi
done
exit 0

recursively renames files/directories to remove spaces and/or convert upper to lowercase and/or switch _-_ with just _. 

came in handy when i realized my entire music directory (leftover from windows in full album/artist/title structure) was full of spaces, made it a bitch to work with files from the command line.  now i use it constantly. 

i'd like to add a piece to prevent from operating on dot-files, but i haven't gotten around to it.

Last edited by brisbin33 (2008-11-12 20:41:42)

Offline

#70 2008-11-12 22:29:00

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

Re: Post your handy self made command line utilities

For wallpaper stuff I use:

#!/bin/bash

###
# Coded by Daenyth
#
# Set your wallpaper to a random file in the specified folder.
# Note that the only files that should be in the 
#   wallpaper folder are ones that will work as wallpapers
###

wallpaperdir="${HOME}/wallpaper/16x10"
setpaper="/usr/bin/fbsetbg -a"
finder="/usr/bin/find" 
simulate=0

###
# -r to search subdirectories too
# -p to search only pwd
# -d to specify the base directory
###
while getopts d:rps flags 
do
        case "$flags" in
                d)      wallpaperdir="$OPTARG";;
                r)      findargs="";;
                p)      findargs="-maxdepth 1";;
                s)      simulate=1 ;;
                [?])    echo >&2 "Usage: $(basename $0) [-r|p] [-d wallpaperdir]"
                        exit 1;;
        esac
done

# Lights, camera, ACTION!
paper="$($finder "$wallpaperdir" -type f $findargs | LC_ALL=C sort -R | head -n 1)"
echo "$paper"
[ $simulate -eq 0 ] && $setpaper "$paper"
#!/bin/bash
# w and h are for your resolution, eg. w=1024 h=768.
w=1440
h=900
# How many to get, can be 1-10
papers=1

# Site seems to block wget. Nothing special about this UA, I just pulled it off google
#ua='Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)'
ua='Look behind you, a three-headed monkey!'

lynx -source "http://interfacelift.com/wallpaper/index.php?sort=random&w=$w&h=$h" \
| gawk '/>download</ { url=gensub(/.*href="(\/.+jpg)".*/, "http://interfacelift.com" "\\1", "g"); print url }' \
| head -n $papers \
| xargs wget --user-agent="$ua"

Last edited by Daenyth (2008-11-12 22:30:09)

Offline

#71 2008-11-13 01:13:56

shazeal
Member
From: New Zealand
Registered: 2007-06-05
Posts: 339

Re: Post your handy self made command line utilities

This was my first ever bash script, learned to hate bash alot, I still use this to backup my own computer but all the servers I run use python stuff now. Once I get them cleaned up Ill post em smile

It makes sure any external mounts are actually mounted, runs some straight forward tars/copys. Then builds a backup list of the files in your home dir excluding any dirs which contain a file called .nobackup.
It stores the backup date in a file and deletes the 2nd to last backup, moves the last backup. Im sure it could be better but I got really fed up with how restrictive bash can be.

#!/bin/bash
BK_DATE=$( date +%Y%m%d )
NICE='nice -n 19'
BK_MNT=/mnt/share
BK_DEST=/mnt/share/backup
BK_SKIP_FILE=".nobackup"
BK_SCRIPT_FILE=$HOME/.backuplist

mount $BK_MNT

# ETC FULL Backup
$NICE sudo tar czpf /tmp/${HOSTNAME}-etc-${BK_DATE}.tar.gz /etc
cp /tmp/${HOSTNAME}-etc-${BK_DATE}.tar.gz $BK_DEST

cd $HOME

rm ${BK_SCRIPT_FILE}.last
mv $BK_SCRIPT_FILE ${BK_SCRIPT_FILE}.last
touch $BK_SCRIPT_FILE

#### CUSTOM PRE BACKUP COMMANDS
cp -R astore/* .astore.backup/
 
# HOME Documents
for i in $( ls -A ); do
    if [ -e "$i" ]; then
      if [ -d "$i" ]; then
      if [ ! -e "${i}"/${BK_SKIP_FILE} ]; then
        echo "${i}" >> $BK_SCRIPT_FILE
      fi
    else
      echo "${i}" >> $BK_SCRIPT_FILE
    fi
  fi
done

$NICE tar czpf /tmp/${HOSTNAME}-home-${BK_DATE}.tar.gz -T $BK_SCRIPT_FILE
cp /tmp/${HOSTNAME}-home-${BK_DATE}.tar.gz $BK_DEST

. $BK_DEST/${HOSTNAME}.backup

if [ -e $BK_DEST/${HOSTNAME}-home-${LAST_BK_DATE}.tar.gz ]; then
  rm $BK_DEST/${HOSTNAME}-home-OLD.tar.gz
  mv $BK_DEST/${HOSTNAME}-home-${LAST_BK_DATE}.tar.gz $BK_DEST/${HOSTNAME}-home-OLD.tar.gz 
fi

echo "LAST_BK_DATE=${BK_DATE}" > ${BK_DEST}/${HOSTNAME}.backup

Offline

#72 2008-11-13 01:43:46

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

Re: Post your handy self made command line utilities

˙˙˙ǝƃɐnƃuɐʃ uƃıǝɹoɟ ǝɯos s,ʇı ʇɐɥʇ ʞuıɥʇ ǝʃdoǝԀ ˙sǝɯıʇǝɯos ɥʇıʍ ʎɐʃd oʇ unɟ ǝq uɐɔ ǝuo sıɥ⊥

#!/usr/bin/perl
use Text::UpsideDown;
use feature 'say';
no warnings;
say upside_down( "@ARGV" );

Last edited by Daenyth (2008-11-13 01:45:21)

Offline

#73 2008-11-13 01:56:47

shazeal
Member
From: New Zealand
Registered: 2007-06-05
Posts: 339

Re: Post your handy self made command line utilities

Need a package build for that one I dont have the required libraries wink

Offline

#74 2008-11-13 02:12:22

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

Re: Post your handy self made command line utilities

It's in AUR.

Offline

#75 2008-11-14 13:10:27

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

Re: Post your handy self made command line utilities

Here's one I whipped up for someone else. It finds the album after the currently playing one and skips to it.

#!/bin/bash
album="$(mpc --format %album% | head -n 1)"
if [ -z "$album" ]; then
        next_trackno=$(mpc playlist --format %album% | grep -A200 '^>' | grep -m1 -v -E '^( |>)[0-9]+\) *$' | cut -d')' -f1)
else
        next_trackno=$(mpc playlist --format %album% | grep -A200 '^>' | grep -m1 -v -F "$album" | cut -d')' -f1)
fi
if [ -z "$next_trackno" ]; then
        mpc next
else
        mpc play $next_trackno
fi

Last edited by Daenyth (2008-11-14 13:37:58)

Offline

Board footer

Powered by FluxBB