You are not logged in.

#1051 2010-05-11 01:02:03

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

Re: Post your handy self made command line utilities

findin breaks on white space. you've got an unnecessary grep as well. If I'm understanding the function correctly, this should do better:

grep -in --color=auto "$1" $(find . ! -name '*.svn*' -print0)

Offline

#1052 2010-05-11 06:25:44

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

Re: Post your handy self made command line utilities

Have a look at ack!

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

#1053 2010-05-15 18:41:35

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

Re: Post your handy self made command line utilities

A single line C "interpreter". Inspired by greybot of #bash and candide of ##c. Adjust the template and the flags to your liking.

#!/bin/sh

CC="gcc -std=c99 -pipe -Wall -pedantic"
CFLAGS="-O2"
SRC=/tmp/tmp$$.c
OUT=/tmp/tmp$$

trap_exit() {
  [ -f "$OUT" ] && rm -f "$OUT"
  [ -f "$SRC" ] && rm -f "$SRC"
}

trap 'trap_exit' 0 TERM HUP QUIT INT

cat > "$SRC" << EOF
#include <stdio.h>
#include <stdlib.h>

int main(void) {
  $@
  return 0;
}
EOF

$CC $CFLAGS $SRC -o "$OUT" && "$OUT"

Make sure to wrap your code in single quotes so the shell doesn't abuse it:

$ bcc 'char *b,a[]="hello arch";for(b=a;*b;b++) printf("%c\n",*b);'
h
e
l
l
o

a
r
c
h

Offline

#1054 2010-05-16 03:41:34

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

Re: Post your handy self made command line utilities

i know i got this idea from someone else on this thread... anyway, thanks to them; here's my version:

#!/bin/bash
#
# pbrisbin 2010
#
# http://pbrisbin.com:8080/bin/updatehosts
#
# this script automatically writes an /etc/hosts file
# with the proper localhost line, some individual lan
# ip lines as per lanip[], and a comprehensive
# blacklist file downloaded from someonewhocares.org
#
###

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

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

message() { echo "usage: updatehosts [-v]"; exit 1; }

write_hosts_file() {
  local entry host ip

  # write my entries
  cat << EOF
#
# /etc/hosts: static lookup table for host names
#
# auto-generated by $(basename $0) on $(date -R)
#
###

#<ip-address>    <hostname.domain.org>    <hostname>
127.0.0.1    localhost.localdomain    localhost   $HOSTNAME

EOF

  # write my LAN ips
  for entry in "${lanips[@]}"; do
    host="${entry%%::*}"
    ip="${entry##*::}"

    echo -e "$ip\t$host.localdomain\t$host"

  done

  # satisfy the license
  cat << EOF

# The below is brought to you by Dan Pollock and can be found at
# http://someonewhocares.org/hosts/
#
# You are free to copy and distribute this file, as long the original 
# URL is included.
  
EOF

  # just the raw ips and minus the localhost block
  wget -q -O - "http://someonewhocares.org/hosts/hosts" | grep -v 'local\|host' | grep '^127'

  # write an EOF
  cat << EOF

# End of file
EOF
}

# must be root
[[ $(id -u) -ne 0 ]] && errorout 'you must be root'
[[ -z "$HOSTNAME" ]] && errorout 'hostname not found'
[[ "$1" = '-v' ]] && verbose=true || verbose=false

# constants
log='/home/patrick/.logs/updatehosts.log'
hosts='/etc/hosts'
temp='/tmp/hosts'

# array of 'host::ip'; will be added at top of file (after localhost)
lanips=( 
  'blue::192.168.0.5'
  'router::192.168.0.1'
  'xbox::192.168.0.6'
  'howard::192.168.0.7'
  'susan::192.168.0.8'
  'htpc::192.168.0.9'
  )

$verbose                   && logger "backing up current $hosts..."
cp "$hosts" "$hosts.bak"   || errorout 'failed backing up current hosts file'
$verbose                   && logger "writing new hosts file to $temp..."
write_hosts_file > "$temp" || errorout 'failed writing new hosts file'
$verbose                   && logger "moving $temp to $hosts..."
mv "$temp" "$hosts"        || errorout 'failed committing new hosts file'

logger 'success.'

Offline

#1055 2010-05-16 09:50:51

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

Re: Post your handy self made command line utilities

Nice script brisbin33, my network uses dhcp and some static ips,
is there anyway I could use the script, could the lanips contain a range?.

Cheers
Paul-S

Offline

#1056 2010-05-16 13:02:13

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

Re: Post your handy self made command line utilities

@brisbin

wget -q -O - "http://someonewhocares.org/hosts/hosts" | awk '!/local|host/ && /^127/'

or something like:

awk '!/local|host/ && /^127/' <(curl -Ls "http://someonewhocares.org/hosts/hosts"

Last edited by steve___ (2010-05-16 13:02:42)

Offline

#1057 2010-05-16 13:09:10

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

Re: Post your handy self made command line utilities

Paul-S wrote:

Nice script brisbin33, my network uses dhcp and some static ips,
is there anyway I could use the script, could the lanips contain a range?.

Cheers
Paul-S

I'm not too sure I understand the question.  If your dhcp server is configured properly (ie not to hand out your static IPs), then everything will work with brisbin33 script.  brisbin33 could be using a dhcp range of 192.168.0.10 to 192.168.0.254 for all we know.

Offline

#1058 2010-05-16 14:18:02

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

Re: Post your handy self made command line utilities

I just added this to my .bashrc:

function cd {
    builtin cd $@
    if [ $( pwd ) = $HOME ]
    then
        local COUNT=$( ls -p | grep -v '/' | wc -l )
        echo "$(tput setaf 1)### $COUNT FILES IN ~ ###$(tput sgr0)"
    fi
}

When changing directory into my home directory it results in this:

[mike@mercury|~/pkgs] $ cd
### 265 FILES IN ~ ###
[mike@mercury|~] $

It is truly sad that it has come to this however I just can't seem to keep my home directory clean. I am hoping this reminder will prompt me to clean it up and put all files into a subdirectory.

The idea for hooking cd came from a todo list manager I saw somewhere.

Offline

#1059 2010-05-16 14:48:13

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

Re: Post your handy self made command line utilities

@mikesd; I'm doing sort of the same thing (except ls shows a total 'size');

cd () {
  builtin cd $@
    \ls -hovA --indicator-style=file-type --color=always
    --group-directories-first --time=ctime --time-style=full-iso
}

That is;

> cd /tmp 
total 116K
drwxrwxrwt 2 root  60 ▎ .X11-unix/
drwx------ 2 scp1  80 ▎ orbit-scp1/
drwxr-xr-x 2 scp1 120 ▎ scp1/
drwxr-xr-x 3 root  60 ▎ screens/
drwx------ 2 scp1  40 ▎ vF7mTLH/
-r--r--r-- 1 root  11 ▎ .X0-lock
-rw-r--r-- 1 scp1 755 ▎ .png
-rw-r--r-- 1 scp1  87 ▎ flexad.log
-rw-rw-rw- 1 scp1   6 ▎ flexad.pid
-rw-r--r-- 1 scp1 84K ▎
fxshot_at_ce2d6b48b692321e28879d2f54842e1d9ce7431c_from_trapd00r_s_utils_-_GitHub.png
-rw-r--r-- 1 scp1 188 ▎ mpdmon-daemon.log
-rw------- 1 scp1 150 ▎ serverauth.udz3MaAkqD
-rw------- 1 root   0 ▎ sess_0pd937fgp21al0ta9qvasubvm7
-rw------- 1 root   0 ▎ sess_j61volr3svq46f285irrptobh3
-rw------- 1 scp1   0 ▎ vimperator-bbs.archlinux.org.tmp

Edit: And btw;

> ls $HOME|wc -l
48

wink

Last edited by dmz (2010-05-16 14:58:50)

Offline

#1060 2010-05-16 16:22:18

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

Re: Post your handy self made command line utilities

steve___ wrote:
Paul-S wrote:

Nice script brisbin33, my network uses dhcp and some static ips,
is there anyway I could use the script, could the lanips contain a range?.

Cheers
Paul-S

I'm not too sure I understand the question.  If your dhcp server is configured properly (ie not to hand out your static IPs), then everything will work with brisbin33 script.  brisbin33 could be using a dhcp range of 192.168.0.10 to 192.168.0.254 for all we know.

steve is right; i setup static ip's .9 and below for my local boxes, then let my router hand out .10 and up for any transient guys.  as for the script, it literally takes the array of values "foo::bar" and adds a line "bar   foo.localdomain   foo" for each; no more, no less.

thanks for that awk line too, i'll be makign that change...

Offline

#1061 2010-05-16 18:17:14

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

Re: Post your handy self made command line utilities

I wouldn't use logger as a function name, since it's the name of the cli util for interacting with syslog.

Offline

#1062 2010-05-17 04:13:52

Odysseus
Member
Registered: 2009-02-15
Posts: 141

Re: Post your handy self made command line utilities

Alright, lets see if I have anything worth sharing. Please, go ahead and criticize.

associate

#!/bin/sh

if [ $# = 1 -o $# = 2 ]
then
    if [ -e "$1" ]
    then
    TYPE=$(xdg-mime query filetype "$1" | sed 's/;.*$//')
    if [ $# = 1 ]
    then
        APP=$(xdg-mime query default $TYPE)
        if [ -z $APP ]
        then
        APP="NONE"
        fi
        echo $TYPE opens with $APP
    else
        APP=$2.desktop
        if [ -e /usr/share/applications/$APP ]
        then
        echo $TYPE now opens with $APP
        xdg-mime default $APP $TYPE
        else
        echo associate: $APP: no such application installed
        fi
    fi
    else
    echo associate: $1: no such file
    exit 1
    fi
else
    echo Usage: associate FILENAME [APPLICATION]
    echo Show or change the default APPLICATION for the mime-type of FILENAME.
    exit 1
fi

jukebox

#!/bin/sh

# Minimal music player.  
# Only plays ogg vorbis music that has some semblace of organization.

pid=$(pidof ogg123)
if [ -z $pid ]
then
    ogg123 -Zq ~/music/*/*/*
elif [ _$1 = _skip ]
then
    kill -INT $pid
elif [ _$1 = _pause ]
then
    if [ -z "$(grep \(stopped\) /proc/$pid/status)" ]
    then
    kill -STOP $pid
    else
    kill -CONT $pid
    fi
elif [ _$1 = _stop ]
then
    kill $pid
fi

freak

#!/bin/sh

# Stream data from a hard drive into your ears. 

usage () {
    echo USAGE:
    echo freak [-d device] [-s start]
    echo freak -r [-d device] [-b bytes]
    exit 1
}

#Defaults
DEVICE="/dev/sda"
START=0
BYTES=1048576
MODE="seq"

#Get options (device, starting byte, random)
while getopts 'd:s:b:rh' OPTION
do
    case $OPTION in
    d) DEVICE=$OPTARG;;
    s) START=$OPTARG;;
    b) BYTES=$OPTARG;;
    r) MODE="rand";;
    h) usage;;
    ?) usage;;
    esac
done

#Sequential Mode
if [ $MODE = seq ]
then
    dd if=$DEVICE ibs=1 skip=$START 2>/dev/null | aplay -fdat -q

#Random mode
elif [ $MODE = rand ]
then
    DEVSIZE=$(fdisk -l $DEVICE 2>/dev/null | awk  '/^Disk \/dev/ { print $5 }')
    if [ $DEVSIZE -lt $BYTES ]
    then
    echo Device smaller than random sample
    exit 1
    fi
    while true
    do
    START=$(echo "import random 
print (random.randrange($DEVSIZE-$BYTES)"/2\)*2 | python)
    echo $START
    dd if=$DEVICE ibs=1 skip=$START count=$BYTES 2>/dev/null | aplay -fdat -q
    done
fi

That last one is very serious business.


I'm the type to fling myself headlong through the magical wardrobe, and then incinerate the ornate mahogany portal behind me with a Molotov cocktail.

Offline

#1063 2010-05-23 08:37:25

bzt
Member
From: Germany
Registered: 2010-04-11
Posts: 39

Re: Post your handy self made command line utilities

Short but simple.

This one is not by me but useful anyways. This searches for a certain string in all files in the given directory.

#!/bin/sh

find "$1" -type f -exec grep -q "$2" {} \; -a -exec ls {} \;

This searches a file by name and colorizes the results.

#!/bin/sh

find "$1" -name "$2" -exec ls -1 -d --color=auto {} \;

Prints how many files are located in the subdirectories of the current directory and sorts the results.

#!/bin/sh

for f in $(ls -a); do
  if [ -d "$f" ]; then
    echo "$f $(ls "$f" | wc -l)"
  fi
done | sort -k 2 -n -r

Offline

#1064 2010-05-23 14:15:46

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

Re: Post your handy self made command line utilities

I have been using a couple of aliases to allow me to push and pop directories in separate terms for a while now. I often have two or more terminals open in the same directory eg one for editing, one for building or testing, etc.

Recently I added a cd wrapper to my .bashrc and came up with an improvement for pushing and popping directories.

function cd {
    builtin cd "$@"
    pwd | xsel -s
    # [...] unrelated code removed
}

alias pd='cd "$( xsel -so )"'

This automatically saves each directory when you cd into it. Saves having to manually push it. You can simply type pd in another term to jump to the last directory you changed to.

Offline

#1065 2010-05-23 14:26:15

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

Re: Post your handy self made command line utilities

Why not build it around push/popd and have them cache/read using a file?

Offline

#1066 2010-05-23 14:27:07

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

Re: Post your handy self made command line utilities

Nice idea mikesd - using it now.

Offline

#1067 2010-05-24 01:11:19

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

Re: Post your handy self made command line utilities

Daenyth wrote:

Why not build it around push/popd and have them cache/read using a file?

No reason. Extending pushd and popd to work globally across terminals would be a good way to go.

A file would work fine as well and may be better if you often ssh into your box. The above version breaks if you are not using X. This version is fine though.

function cd {
    builtin cd "$@"
    [ -n "$DISPLAY" ] && pwd | xsel -s
    # [...] unrelated code removed
}

alias pd='cd "$( xsel -so )"'

Last edited by mikesd (2010-05-24 01:37:09)

Offline

#1068 2010-05-27 13:53:05

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

Re: Post your handy self made command line utilities

i find this incredibly useful.

debug() {
  local script="$1"; shift

  bash -x $(which $script) "$@"
}

Offline

#1069 2010-05-27 23:18:41

ataraxia
Member
From: Pittsburgh
Registered: 2007-05-06
Posts: 1,553

Re: Post your handy self made command line utilities

I wrote this quick-n-dirty bash function to change the foreground and background colors of an xterm on the fly:

xtermcolor () 
{ 
    case $1 in 
        'fg')
            id=0
        ;;
        'bg')
            id=1
        ;;
        *)
            return 1
        ;;
    esac;
    case $2 in 
        'def')
            echo -e "\e]11${id}\a"
        ;;
        *)
            echo -e "\e]1${id};$2\a"
        ;;
    esac
}

"xtermcolor fg somecolor" will set the color.
"xtermcolor fg def" will change it back to whatever it was started with.
"xtermcolor fg \?" will output what it's currently set to.

Use "bg" instead of "fg" to work with background colors instead.

After writing/posting this, I discovered that extra/xtermcontrol does this more cleanly, plus a whole lot more.

Last edited by ataraxia (2010-05-29 19:01:52)

Offline

#1070 2010-05-29 18:20:27

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

Re: Post your handy self made command line utilities

(edit) WARNING: Might be buggy... Well i just fixed a major one: Remember $10 vs ${10} people!

(edit after a century) Another bug fixed: `ln -s foo bar` where 'bar' is a symlink pointing to a directory, will create a symlink to foo, in the directory bar points to. The '-n' option to GNU ln can fix this, while the POSIX solution is simply using rm on bar first.

#!/bin/sh
#
# edlink.sh: Edit where symbolic links point at.
#

. "$HOME"/bin/common_stuff.sh

ed="${VISUAL:-${EDITOR:-vi}}"

error(){ echo error; exit 1; }

make_tmp_files tmp || error

for link
do
    readlink "$link" >> "$tmp" || error
done

"$ed" "$tmp" || error

test $# -eq $(wc -l < "$tmp") || error

i=1
while read -r line
do
    eval '
        rm "${'$i'}"
        ln -s "$line" "${'$i'}"
    ' || error
    i=$((i+1))
done < "$tmp"

Last edited by TaylanUB (2010-06-16 17:04:00)


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

Offline

#1071 2010-05-29 23:50:26

tlvb
Member
From: Sweden
Registered: 2008-10-06
Posts: 297
Website

Re: Post your handy self made command line utilities

Perhaps not useful, and not perfect, but enabling you to access the jargon file lexicon in a fortune-like manner:

#!/usr/bin/env perl

use WWW::Mechanize;

my $base = 'http://catb.org/jargon/html/';
my $page = 'go01.html';
my $mech = WWW::Mechanize->new();

$mech->get($base . $page);
$mech->success() or die "no success\n";

for (split '</a>', $mech->content()) {
        if (/href="([A-Z]\/.+\.html)"/) {
                push @list, $1;
        }
}

$page = $list[int(rand(@list))];
$mech->get($base . $page);
$mech->success() or die "no success\n";
$mech->content() =~ /\<title\>(.+)\<\/title\>.*?\<p\>(.*)\<\/p\>/s;

print "\x1b[1m$1\x1b[0m ($base$page)\n\n";

$_ = $2;
s/\<a[^>]*\>(.*?)\<\/a\>/\x1b[1m$1\x1b[0m/g;
s/\<\/p\>/\n\n/g;
s/\<[^>]*\>//g;
s/&#821.;/'/g;
s/&#822.;/"/g;

print $_ . "\n";

Last edited by tlvb (2010-05-29 23:58:41)


I need a sorted list of all random numbers, so that I can retrieve a suitable one later with a binary search instead of having to iterate through the generation process every time.

Offline

#1072 2010-05-30 00:31:11

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

Re: Post your handy self made command line utilities

Odd... I have fortune-mod-jargon but can't find the source... Hmm, omploader time! http://omploader.org/vNGZ6Mw

Dug around a bit in svn, looks like a ton of fortune-mod packages were removed a little while after here

I think maybe some sources were broken? Let's see who might still have them installed and bacman them big_smile

Last edited by Daenyth (2010-05-30 00:37:35)

Offline

#1073 2010-05-30 00:54:58

tlvb
Member
From: Sweden
Registered: 2008-10-06
Posts: 297
Website

Re: Post your handy self made command line utilities

Hah, never thought of searching for one, actually it started out as a script with the purpose to make something like a random firefox start page
(eg alias firefox='/usr/bin/firefox $(random-jargon-urlgen)' but I went ahead with fetching and printing the entry too and not just
generating the url.

Edit: new variant below takes a string argument and displays the entry for it:

#!/usr/bin/env perl

use WWW::Mechanize;

my $base = 'http://catb.org/jargon/html/';
my $page = 'go01.html';
my $mech = WWW::Mechanize->new();

$mech->get($base . $page);
$mech->success() or die "no success\n";

if (@ARGV) {
        my $ref = join ' ', @ARGV;
        for (split '</a>', $mech->content()) {
                if (/href="([A-Z]\/.+\.html)"[^>]*\>$ref$/i) {
                        $page = $1; 
                        last;

                }   
        }   
}
else {
        for (split '</a>', $mech->content()) {
                if (/href="([A-Z]\/.+\.html)"/) {
                        push @list, $1; 
                }   
        }   
        $page = $list[int(rand(@list))];
}
$mech->get($base . $page);
$mech->success() or die "no success\n";
$mech->content() =~ /\<title\>(.+)\<\/title\>.*?\<p\>(.*)\<\/p\>/s;

print "\x1b[1m$1\x1b[0m ($base$page)\n\n";

$_ = $2; 
s/\<a[^>]*\>(.*?)\<\/a\>/\x1b[1m$1\x1b[0m/g;
s/\<\/p\>/\n\n/g;
s/\<[^>]*\>//g;
s/&#821.;/'/g;
s/&#822.;/"/g;
s/&/\&/g;

print $_ . "\n";

Now I can perhaps finally go to bed and get some rest so that I can study for my exam tomorrow...

Last edited by tlvb (2010-05-30 02:49:18)


I need a sorted list of all random numbers, so that I can retrieve a suitable one later with a binary search instead of having to iterate through the generation process every time.

Offline

#1074 2010-05-30 13:23:55

jhvid
Member
From: /dev/denmark
Registered: 2009-08-19
Posts: 52

Re: Post your handy self made command line utilities

#!/usr/bin/ruby -w
#
# colortext.rb
# Print text in colors with extra spacing...
#
# Example:
#   colortext.rb "asdf"
# gives
#   \e[31ma \e[32ms \e[33md \e[34mf \e[0m"
#

STRING = ARGV[0]
COLORS = (31..37).to_a

current_color = 0
STRING.each_char do |c|
  print "\e[#{COLORS[current_color]}m#{c} \e[0m"
  if current_color.size == current_color - 1
    current_color = 0
  else
    current_color += 1
  end
end

puts

Very useful tongue


GCS d- s-:+ a12 C++++ U++++ L+++ P--- E--- W+++ N+ o K- w--- O? M-- V? PS PE
Y- PGP? t? 5? X? R tv b+++ DI+ D- G++ e++ h! !r !y

Please ignore me... I'm pretty weird...

Offline

#1075 2010-05-30 14:11:17

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

Re: Post your handy self made command line utilities

@jhvid: Lets support 256 colors, shall we?

#!/usr/bin/perl
use strict;
my @lala = split(//, join(/ /, @ARGV));

my $i=0;
for my $zap(@lala) {
  $i++;
  print "\033[38;5;$i".'m ', $zap, " \033[0m";
}

Offline

Board footer

Powered by FluxBB