You are not logged in.

#1376 2010-11-15 22:23:38

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

Re: Post your handy self made command line utilities

diff an AUR PKGBUILD based on your local copy:

#!/bin/bash

DIFF=${DIFF:-diff}

if [[ ! -f PKGBUILD ]]; then
  echo "error: No PKGBUILD found in working directory."
  exit 1
fi >&2

eval $(grep '^pkgname=' PKGBUILD)
if [[ -z $pkgname ]]; then
  echo "error: pkgname not found in PKGBUILD"
  exit 1
fi >&2

diff ${@:--u} PKGBUILD <(curl -s "http://aur.archlinux.org/packages/$pkgname/$pkgname/PKGBUILD")

This, of course, assumes that you've accumulated a build directory full of PKGBUILDs for AUR packages you have installed. I assume I'm not the only one who does this...

Last edited by falconindy (2010-11-16 13:29:00)

Offline

#1377 2010-11-16 03:51:20

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

Re: Post your handy self made command line utilities

And here's another quick and dirty toy I whipped up with xmllint to view aur comments...

#!/bin/bash

#
# retreive aur comments for a package
#   - package name can be specified or pulled from a PKGBUILD in $PWD
#   - specify -a to show all comments
#

AURURL="http://aur.archlinux.org"
ALL='&comments=all'
printf -v CON '\e[1;34m'
printf -v COFF '\e[0m'

commfilter() {
  xmllint --html --xpath \
    '//div[@class="pgbox"]/div[@class="comment-header"]/..' - 2>/dev/null |\
    sed 's/<[^>]\+>//g;s/\t//gs/\r$//;
        /Comment by:/,/[[:alnum:]]\+/{/^$/d};
        s/^\(Comment by:.*\)$/'"$CON"'\1'"$COFF"'/'

    # line 1: strip html tags, tabs and ^M
    # line 2: strip empty lines between timestamp and body
    # line 3: add color
}

getpkgID() {
  curl -s "$AURURL/rpc.php?type=info&arg=$1" | awk '
    BEGIN  { RS=","; FS=":" }
    /type/ { if ($2 ~ /error/) exit }
    /ID/   { gsub(/\"/, "", $3); print $3; exit }'
}

[[ $1 = -a ]] && { showall=$ALL; shift; }

if ! (( $# )); then
  if [[ ! -f PKGBUILD ]]; then 
    echo "error: no PKGBUILD found and no arg provided"
    exit 1
  fi
  eval $(grep '^pkgname=' PKGBUILD)
fi

pkgname=${1:-$pkgname}

pkgID=$(getpkgID $pkgname)
[[ $pkgID ]] || { echo "error: package \`$pkgname' not found"; exit 1; }

curl -s "$AURURL/packages.php?ID=$pkgID$showall" | commfilter

Last edited by falconindy (2010-11-16 13:28:26)

Offline

#1378 2010-11-16 08:53:10

quigybo
Member
Registered: 2009-01-15
Posts: 223

Re: Post your handy self made command line utilities

@falconindy: Beautiful, I have wanted something like these two tools for a while but never got around to writing them myself. Thanks!

falconindy wrote:

diff an AUR PKGBUILD based on your local copy:

Here is a couple minor edits, first set the binary used at the top of the file (handy for those that use colordiff). I am wondering now if it should be ${DIFF:-diff} instead, does anybody set an environment variable for diff? The second was to be able to pass args to the diff command, as it is often handy to view changes eg. as --side-by-side (-y) instead of --unified (-u).

diff --git a/bin/aurdiff b/bin/aurdiff
index 0268f0d..f506215 100755
--- a/bin/aurdiff
+++ b/bin/aurdiff
@@ -1,5 +1,7 @@
 #!/bin/bash
 
+DIFF=diff
+
 if [[ ! -f PKGBUILD ]]; then
   echo "error: No PKGBUILD found in working directory."
   exit 1
@@ -11,4 +13,4 @@ if [[ -z $pkgname ]]; then
   exit 1
 fi >&2
 
-diff -u PKGBUILD <(curl -s "http://aur.archlinux.org/packages/$pkgname/$pkgname/PKGBUILD")
+$DIFF "${@:--u}" PKGBUILD <(curl -s "http://aur.archlinux.org/packages/$pkgname/$pkgname/PKGBUILD")

     

falconindy wrote:

And here's another quick and dirty toy I whipped up with xmllint to view aur comments...

This is even more minor (bordering on picky tongue), just removing carriage returns and redirecting error messages to stderr.

diff --git a/bin/aurcomments b/bin/aurcomments
index 61f2e25..1d60785 100755
--- a/bin/aurcomments
+++ b/bin/aurcomments
@@ -16,11 +16,13 @@ commfilter() {
     '//div[@class="pgbox"]/div[@class="comment-header"]/..' - 2>/dev/null |\
     sed 's/<[^>]\+>//g;s/\t//g;
         /Comment by:/,/[[:alnum:]]\+/{/^$/d};
-        s/^\(Comment by:.*\)$/'"$CON"'\1'"$COFF"'/'
+        s/^\(Comment by:.*\)$/'"$CON"'\1'"$COFF"'/;
+        s/\r$//'
 
     # line 1: strip html tags
     # line 2: strip empty lines between timestamp and body
     # line 3: add color
+    # line 4: remove carriage return
 }
 
 getpkgID() {
@@ -36,13 +38,13 @@ if ! (( $# )); then
   if [[ ! -f PKGBUILD ]]; then 
     echo "error: no PKGBUILD found and no arg provided"
     exit 1
-  fi
+  fi >&2
   eval $(grep '^pkgname=' PKGBUILD)
 fi
 
 pkgname=${1:-$pkgname}
 
 pkgID=$(getpkgID $pkgname)
-[[ $pkgID ]] || { echo "error: package \`$pkgname' not found"; exit 1; }
+[[ $pkgID ]] || { echo "error: package \`$pkgname' not found"; exit 1; } >&2
 
 curl -s "$AURURL/packages.php?ID=$pkgID$showall" | commfilter

Offline

#1379 2010-11-16 13:18:58

halhen
Member
From: Gothenburg, Sweden
Registered: 2009-04-08
Posts: 56
Website

Re: Post your handy self made command line utilities

Snippet to reuse the X terminal color settings in the (outside-of-X) virtual console. Put it in your shell init script (.bashrc/.zshrc/...).

if [ "$TERM" = "linux" ]; then
    _SEDCMD='s/.*\*color\([0-9]\{1,\}\).*#\([0-9a-fA-F]\{6\}\).*/\1 \2/p'
    for i in $(sed -n "$_SEDCMD" $HOME/.Xdefaults | \
               awk '$1 < 16 {printf "\\e]P%X%s", $1, $2}'); do
        echo -en "$i"
    done
    clear
fi

The snippet uses the color settings from .Xdefaults, so if you configure your terminal elsewhere, you'll have to edit the script accordingly.


statnot - status text manager and notification-daemon for dwm, wmii and the like
shic - SHellscript Irc Client

Offline

#1380 2010-11-18 09:46:37

AsmundEr
Member
From: Trondheim, Norway
Registered: 2010-05-07
Posts: 15

Re: Post your handy self made command line utilities

This bash one-liner came in handy today, when I wanted the wall time of a process:

#! /bin/bash
ps -eo pid,etime,args | grep $1 | grep -v "grep" | grep -v `basename $0`

Didn't find any results in these forums when I searched for it, and it's a little too cumbersome and obscure for me to remember. Hopefully it will be useful for others as well. I saved this as /usr/bin/walltime, so i can do "walltime firefox" and get what I want. (The last two greps remove the uninteresting results "00:00 grep firefox" and "00:00 walltime firefox".)

Offline

#1381 2010-11-18 10:00:18

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

AsmundEr wrote:

This bash one-liner came in handy today, when I wanted the wall time of a process:

#! /bin/bash
ps -eo pid,etime,args | grep $1 | grep -v "grep" | grep -v `basename $0`

Didn't find any results in these forums when I searched for it, and it's a little too cumbersome and obscure for me to remember. Hopefully it will be useful for others as well. I saved this as /usr/bin/walltime, so i can do "walltime firefox" and get what I want. (The last two greps remove the uninteresting results "00:00 grep firefox" and "00:00 walltime firefox".)

Try

ps -o pid,etime,args --no-header -C $1

Last edited by karol (2010-11-18 10:47:46)

Offline

#1382 2010-11-21 20:08:00

enzzzy
Member
Registered: 2010-10-09
Posts: 13

Re: Post your handy self made command line utilities

Well, my first post on the forums \°/

I was looking for a way to quickly change my volume without the use of another app. So i made this script and invoke it with some keybindings.
Maybe usefull for someone else...
Sugestions are allways welcome!

#!/bin/bash

###################################
#       Change volume script      #
#       enzzzy@gmail.com          #
###################################

if  [ $# -ne  1 ] 
then
        echo "Usage $0 arg"
        echo "up for volume up"
        echo "down for volume down"
fi

#Volume up
if [ "$1" = "up" ]
then    
        status=`amixer sget Master | grep "Left: Playback" | awk '{print $7}'`
        if [ "$status" = "[off]" ]; then
                #sound is muted > toggle and volume to 1
                amixer set Master 1 1>/dev/null
                amixer set Master toggle 1>/dev/null
        else
                #sound is NOT muted > vol = vol + 1
                volume=`amixer sget Master | grep "Left: Playback" | awk '{print $4}'`
                volume=`echo "scale=0; $volume+1" | bc`
                amixer set Master $volume 1>/dev/null
        fi
fi      
        
#Volume down
if [ $1 = "down" ]; then
        status=`amixer sget Master | grep "Left: Playback" | awk '{print $7}'`
        if [ "$status" = "[on]" ]; then
                #sound is NOT muted > vol = vol - 1
                volume=`amixer sget Master | grep "Left: Playback" | awk '{print $4}'`
                if [ $volume -gt 1 ]; then
                        volume=`echo "scale=0; $volume-1" | bc`
                        amixer set Master $volume 1>/dev/null
                else
                        amixer set Master toggle 1>/dev/null
                fi              

        fi
fi 

Last edited by enzzzy (2010-11-21 20:18:01)

Offline

#1383 2010-11-21 20:12:55

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

enzzzy wrote:

echo "down for volume up"

Tricky.

I use

[karol@black ~]$ type vol
vol is a function
vol () 
{ 
    amixer set 'Master Mono' "$10%" &>/dev/null
}

'vol 5' will set the volume to 50%.

Last edited by karol (2010-11-21 20:14:49)

Offline

#1384 2010-11-21 21:01:55

egan
Member
From: Mountain View, CA
Registered: 2009-08-17
Posts: 273

Re: Post your handy self made command line utilities

I guess I'll post my volume script. I don't use it much anymore since I figured out how to control the volume through XMonad and have it's state broadcasted to XMobar.

#!/bin/bash

##
# volume	-- control alsa mixer levels
#
# usage		-- volume [[toggle|up|down|level LEVEL]|[t|u|d|l LEVEL]]
#			-With no arguments, print volume level
#			-LEVEL is given as a percentage
#			-Default step for up/down is $volstep
#
# notes		-- complex volume control can be done with alsamixer
#
# written	-- 30 July, 2009 by Egan McComb
#
# revised	-- 15 June, 2010 by author
##

sdevice="Master"
volstep=3

usage()
{
	echo "Usage: $(basename $0) [[toggle|up|down|level LEVEL]|[t|u|d|l LEVEL]]" >&2
	echo -e "\t-With no arguments, print volume level" >&2
	echo -e "\t-LEVEL is given as a percentage" >&2
	echo -e "\t-Default step for up/down is $volstep%" >&2
}


getvolume()
{
	state=$(amixer | grep -A 4 $sdevice | awk {'print $6'} | grep -m 1 "\[on\]\|\[off\]" | sed -e "s/[][]//g;s/o/O/")
	volume=$(amixer | grep -A 6 $sdevice | awk {'print $4'} | grep -m 1 % | sed -e "s/[][]//g")
	printf "%-4s %3s\n" "$state:" $volume
	exit 0
}


chkargs()
{
	if (( ! $# ))
	then
		getvolume
	elif (( $# > 1 )) && [[ $1 != "level" ]] && [[ $1 != "l" ]]
	then
		echo "Error: Too many arguments" >&2
		usage
		exit $ERR_NARGS
	elif [[ $1 = "toggle" ]] || [[ $1 = "t" ]]
	then
		arg="$sdevice toggle"
	elif [[ $1 = "up" ]] || [[ $1 = "u" ]]
	then
		arg="$sdevice ${volstep}%+"
	elif [[ $1 = "down" ]] || [[ $1 = "d" ]]
	then
		arg="$sdevice ${volstep}%-"
	elif [[ $1 = "level" ]] || [[ $1 = "l" ]]
	then
		if [[ -z "$2" ]]
		then
			echo "Error: Too few arguments" >&2
			usage
			exit $ERR_NARGS
		elif grep -q [^[:digit:]] <<< "$2" || (( $2 > 100 ))
		then
			echo "Error: Invalid LEVEL '$2'" >&2
			usage
			exit $ERR_VARGS
		fi
		arg="$sdevice ${2}%"
	else
		echo "Error: Invalid argument '$1'" >&2
		usage
		exit $ERR_VARGS
	fi
}

##----MAIN----##
chkargs "$@"

amixer -q set $arg

exit 0

Last edited by egan (2012-01-05 23:49:44)

Offline

#1385 2010-11-22 21:47:52

3])
Member
From: Netherlands
Registered: 2009-10-12
Posts: 215

Re: Post your handy self made command line utilities

I have probably destroyed my system like this, but I like to keep my /home/userfoo nice and clean,permission wise that is.

Just to warn you-only use this in your home directory, preferably a /home/userfoo/exampledir if you are unsure about using this in your /home/userfoo/

#!/bin/bash

while [ 1 ]
do
        echo "cleansing permissions"
        find . -type f -exec chmod -v 600 {} \;

        break

done

If you are wondering why chown isn't here, its easier to run 'chown foo -R * -v', but you can add that after the done if you wish.


“There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.”-- C.A.R. Hoare

Offline

#1386 2010-11-23 16:32:34

dyscoria
Member
Registered: 2008-01-10
Posts: 1,007

Re: Post your handy self made command line utilities

makepkg in tmpfs.

Change username to your user, change TMPFSDIR to a folder owned by your user and run using sudo or su -c

Can also edit the size of the tmpfs depending on total RAM

#!/bin/bash

TMPFSDIR=/build/tmpfs
FULLDIR="$(pwd)"
PARTDIR="${FULLDIR##*/}"

# mount tmpfs
mount -t tmpfs -vo rw,nosuid,nodev,exec,noatime,size=1536M tmpfs ${TMPFSDIR} || exit 1

# starting directory
pushd ./

# copy to tmpfs
cd ../
su USERNAME -c "cp -dRv "${PARTDIR}" "${TMPFSDIR}""
cd "${TMPFSDIR}/${PARTDIR}"

# ask to run makepkg
read -e -p "Run makepkg [y/N]?: " makepkg_confirm
if [ "${makepkg_confirm}" == 'y' -o "${makepkg_confirm}" == 'Y' ]; then
    su USERNAME -c "nice -n 19 makepkg $*"
fi

# ask to unmount tmpfs
read -p "Press any key to unmount ${TMPFSDIR}..."

# return to starting directory
popd

# unmount tmpfs
umount -v ${TMPFSDIR} || exit 1

Last edited by dyscoria (2010-11-23 17:14:47)


flack 2.0.6: menu-driven BASH script to easily tag FLAC files (AUR)
knock-once 1.2: BASH script to easily create/send one-time sequences for knockd (forum/AUR)

Offline

#1387 2010-11-23 21:19:01

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

Re: Post your handy self made command line utilities

(edit: the ']' in the name breaks the forum quoting engine!)

3]) wrote:
#!/bin/bash

while [ 1 ]
do
        echo "cleansing permissions"
        find . -type f -exec chmod -v 600 {} \;

        break

done

You, sir, need a good beginners guide for the shell. No disrespect. tongue


Print the 256 colors nicely with their numbers:
Run it with 'n' as the first argument to color the numbers themselves too.

#!/bin/sh

c=$(tput cols)
i=0
while [ $i -lt 256 ]
do
    if [ "$1" = n ] # Color the numbers too
    then printf '\033[38;05;%dm%03d\033[00m \033[48;05;%dm  \033[00m' $i $i $i
    else printf '%03d \033[48;05;%dm  \033[00m' $i $i
    fi
    # The length of the resulting string is 6 (be careful if you change it)
    # Plus we'll put 2 spaces between each string
    # So this is how we decide when to put a newline:
    if [ $((8*(i+1-(c/8+c%8/6)*l)+6)) -gt $c ]
    # Remember all divisions are rounded down immediately
    # We add 1 to i because it started from 0
    then l=$((l+1)); echo
    else printf '  '
    fi
    i=$((i+1))
done

Last edited by TaylanUB (2010-11-23 21:21:43)


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

Offline

#1388 2010-11-23 21:32:03

karol
Archivist
Registered: 2009-05-06
Posts: 25,440

Re: Post your handy self made command line utilities

TaylanUB wrote:

the ']' in the name breaks the forum quoting engine!

Not if you put it in quotes: [ quote="3])"]blah[/quote ]

3]) wrote:

blah

Offline

#1389 2010-11-24 14:47:13

3])
Member
From: Netherlands
Registered: 2009-10-12
Posts: 215

Re: Post your handy self made command line utilities

TaylanUB wrote:

You, sir, need a good beginners guide for the shell. No disrespect. tongue

Not really a bash scripter, more of a pythoner,

I just changed code I found somewhere on the net.
But hey-it works, and makes sure I can't execute anything I do not wish to-even by 'accident'.

Nice color bash program you have there though.

Last edited by 3]) (2010-11-24 14:57:13)


“There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.”-- C.A.R. Hoare

Offline

#1390 2010-11-24 15:19:52

egan
Member
From: Mountain View, CA
Registered: 2009-08-17
Posts: 273

Re: Post your handy self made command line utilities

3]) wrote:
TaylanUB wrote:

You, sir, need a good beginners guide for the shell. No disrespect. tongue

Not really a bash scripter, more of a pythoner,

I just changed code I found somewhere on the net.
But hey-it works, and makes sure I can't execute anything I do not wish to-even by 'accident'.

Nice color bash program you have there though.

This suffices for me:

alias mclean='find . -type d -exec chmod 744 {} \; && find . -type f -exec chmod 644 {} \;'

Offline

#1391 2010-11-24 15:34:35

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

Re: Post your handy self made command line utilities

TaylanUB wrote:

Print the 256 colors nicely with their numbers:

I do it like this...
c256:

#!/usr/bin/perl
use strict;
use Getopt::Long;
use Data::Dumper;
use Pod::Usage;

my %colors = (); 
my $unicode = "░▒▓██▓▒░";

my %color = ();
for my $i(1..255) { # check why \033[38;5;000 is illegal
  $i = sprintf("%03d",$i);
  $color{$i} = "\033[48;5;$i" . 'm' . "\033[38;5;$i" . 'm' . "   " . "\033[0m";
}

square(8) unless(@ARGV);

our($opt_sqsize);
GetOptions(
  'col:s'   => \$opt_sqsize,
  list      => \&list,
  sq        => \&square,
  help      => sub { pod2usage(verbose => 1)},
  man       => sub { pod2usage(verbose => 3)},
);

square($opt_sqsize) if(defined($opt_sqsize));

sub square {
  my $num = shift;
  my $end = undef;
  my $atr = undef;
  for my $i(sort(keys(%color))) {
    if($i % $num==0) {
      $end = "\033[0m  \n";
      $atr = "\033[1m";
    }
    else {
      $end = "\033[0m";
      $atr = "\033[3m";
    }
    print "$atr\033[38;5;$i" . 'm' . " $i ", $color{$i},$end;
  }
  print "\n";
  exit(0);
}

sub list {
  for my $i(sort(keys(%color))) {
    print $color{$i},"\033[38;5;$i" . 'm', $unicode,"  $i  ", "\033[0m\n";
  }
  exit(0);
}

=pod

=head1 NAME

  colortest-256-ng - print various tables in 256 colors

=head1 SYNOPSIS

  c256 [-s size ] [-l | -sq]

=head1 DESCRIPTION

c256 will tell you if your terminal supports 256 colors.
It can also be used to see what color responds to what integer (0..255)

=head1 OPTIONS

  -s,   --square  square format (default)
  -l,   --list    list format
  -c,   --col     n columns

  -h    --help    help message
  -m    --man     view manpage

=head1 TRIVIA

The background notation to use is <ESC>38;5 - \033[38;5;100m

The foreground notation to use is <ESC>48;5 - \033[48;5;197m

The foreground and background colors can be changed on the fly:
  printf "\033[4;200;rgb/7a/67/ee\033\\"

=head1 AUTHOR

Written by Magnus Woldrich

=head1 COPYRIGHT

(C) Copyright 2010 Magnus Woldrich. 

License GPLv2.

=cut

and like this:
cc256:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <getopt.h>

void usage() {
  printf("Usage: cc256 [-c columns] [-t foreground text]\n\n");
  printf("  \033[1mcc256\033[0m will output a table representing up to 256 colors\n");
  printf("  which might be supported by your terminal emulator.\n");
  printf("  If a number is provided as the first argument, that'll define\n");
  printf("  the number of columns used. The default is 8.\n\n");
  printf("  rxvt-unicode supports 88 colors out of the box.\n");
  printf("  It'll support 256 colors if patched.\n");
  printf("  xterm supports 256 colors out of the box\n");
  exit(0);
}

int main(int argc, char *argv[]) {
  char *fg_char    = NULL;
  char *end        = "\033[0m";
  int columns = 16;

  int color_int, opt;

  while((opt = getopt(argc, argv, "hc:t:")) != -1) {
    switch(opt) {
      case 'c':
        columns = atoi(optarg);
        if(columns == 0) {
          usage();
          exit(0);
        }
        else {
          /* dont let the args fall though */
          break;
        }
      case 't':
        fg_char = optarg;
        break;
      case 'h':
        usage();
        break;
      default:
        fprintf(stderr, "Usage: %s [-c columns] [-t] text to print\n", "cc256");
        exit(EXIT_FAILURE);
    }
  }


  for(color_int=0;color_int<255;++color_int) {
    if(color_int % columns == 0) {
      end = "\033[0m\n";
    }
    else {
      end = "\033[0m";
    }
    if(color_int == 0) {
      continue;
    }
    if(fg_char != NULL) {
      printf("\033[48;5;%d%s %s %s", color_int, "m",fg_char, end);
    }
    else {
      printf("\033[48;5;%d%s %03d %s", color_int, "m", color_int, end);
    }
  }
  printf("\n");
  return(0);
}

also like this:
show_all_colors:

#!/usr/bin/perl
use strict;
use Term::ExtendedColor;

my $colors = get_colors();
my @sorted_colors;


# We want to sort by 001 .. 010 .. 042
for my $color(keys(%{$colors})) {
  $color =~ m/(\d+)$/;
  my $num = sprintf("%03d", $1);
  $color =~ s/(\d+)$/$num/;
  push(@sorted_colors, $color);
}

for(sort(@sorted_colors)) {
  s/([a-z]+)0+(\d+)$/$1$2/;
  print bg($_, "  x  "), "\t";
  print fg($_, $_), "\n";
}

and finally, like this:

perl -e '$\="\n";print"\e[38;5;$_"."m$_\e[0m"for(0..256)'

Offline

#1392 2010-11-24 15:37:45

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

Re: Post your handy self made command line utilities

karol wrote:
enzzzy wrote:

echo "down for volume up"

Tricky.

I use

[karol@black ~]$ type vol
vol is a function
vol () 
{ 
    amixer set 'Master Mono' "$10%" &>/dev/null
}

'vol 5' will set the volume to 50%.

I use;

alias v+='ossmix vmix0.pcm8 -- +2'
alias vv+='ossmix vmix0.pcm9 -- +2'
alias vvv+='ossmix vmix0.pcm10 -- +2'
alias vvv+='ossmix vmix0.pcm10 -- -2'

Offline

#1393 2010-11-27 05:55:31

darkpegasus333
Member
Registered: 2010-11-16
Posts: 3

Re: Post your handy self made command line utilities

This is a script to get the latest version of uTorrent's new torrent server for Linux. I haven't actually been able to test it yet since they haven't updated it yet sad

#!/bin/bash

url=$(curl www.utorrent.com/downloads/linux/ | awk '/client-beta.*linux/ {print $3}' | tr -d "',")
version=$(echo $url | sed 's/[^0-9]//g') # Don't judge me...it works.

update(){
    wget $1
    echo $2 > currentv
}

if [ -f currentv ]; then
    prevversion=$(cat currentv)
    if [ "$prevversion" -lt "$version" ]; then
        update $url $version
    elif [ "$prevversion" -eq "$version" ]; then
        echo "uTorrent server is the latest version"
    else
        echo "An error occurred"
    fi
else
    update $url $version
fi

Binary translator I wrote just for fun:

#!/usr/bin/env python
import sys, getopt

def parseopts(argv):
    if not argv:
        print("Missing options. Try 'bintrans -h' for help")
    try:
        opts, args = getopt.getopt(argv, 'hb:t:',['help','binary=','text='])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()
        elif opt in ('-b', '--binary'):
            to_bin(arg)
        elif opt in ('-t', '--text'):
            from_bin(arg)

def to_bin(string):
    for i in string:
        print(bin(ord(i)).replace('b',''), end=' ')
    print('')

def from_bin(string):
    lett = string.split()
    if len(lett) == 1:
        lett = []
        while len(string) > 0:
            lett.append(string[:8])
            string = string[8:]
    for item in lett:
        print(chr(int(item,2)),end='')
    print('')

def usage():
    print("""\
Usage: bintrans <opts> <input>
            
Options:
-b or --binary <text>:    Translates text to binary. Sentences should be wrapped in quotes 
            ('hello world') or escaped (hello\ world).
-t or --text <binary>:    Translates binary to text. Quote/escape spaces.
-h or --help:        Shows this message.
""")

if __name__ == '__main__':
    parseopts(sys.argv[1:])

Last edited by darkpegasus333 (2010-11-27 06:03:52)

Offline

#1394 2010-11-27 12:01:03

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

Re: Post your handy self made command line utilities

#!/bin/sh
#
# ~/bin/hit: It's like 'touch', but a bit more forceful.
#
# Depends on 'readlink -m' (GNU coreutils).
#
# For each argument:
#   Absolute destination of pathname ('readlink -m' output) is created, parent dirs included.
#   If the '-d' option is given, final destination will be a directory too.
#
# Will fail in obvious cases:
#   Name of parent dir points to existing (non-dir) file.
#   No permission, no place on filesystem, ...
#
# Supports '-v' for verbose.
#

dir=false
v=false
for arg
do case $arg in
-d) dir=true ;;
-v) v=true ;;
--) break
esac done

if $dir
then
    for file
    do
        $v && printf >&2 'creating dir(s): %s\n' "$file"
        mkdir -p -- "$(readlink -m "$file")"
    done
else
    for file
    do
        final=$(readlink -m -- "$file")

        $v && printf >&2 'creating dir(s): %s\n' "${final%/*}"
        mkdir -p -- "${final%/*}"

        $v && printf >&2 'creating file: %s\n' "$final"
        >> "$final"
    done
fi

Last edited by TaylanUB (2010-12-03 14:55:16)


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

Offline

#1395 2010-11-29 17:55:32

lolilolicon
Member
Registered: 2009-03-05
Posts: 1,722

Re: Post your handy self made command line utilities

I love qrencode. And the absence of qrdecode just doesn't feel right at all.

qrdecode() { zbarimg -S\*.disable -Sqrcode.enable "$1" -q | sed '1s/^[^:]\+://'; }

Or, if you prefer, this is the QR Code version:
vNmNyYg


This silver ladybug at line 28...

Offline

#1396 2010-11-30 01:03:04

sisco311
Member
From: Romania
Registered: 2008-05-23
Posts: 112

Re: Post your handy self made command line utilities

Script for switching keyboard layouts:

#!/bin/bash

# List of languages:
LANGS=(us hu ro)

# List of variants:
VARIANTS=("altgr-intl" "qwerty" "")

# Path to the directory with the flag icons:
ICONPATH="/home/sisco/.icons/flags/png"
# You can download the icons from http://www.famfamfam.com/lab/icons/flags/
# The flag icon filenames must follow the ISO 3166-1 alpha-2 country codes.

# Set it to "true" to enable notification
# NOTE: you may have to install libnotify-bin
NOTIFY="true"
# Yep, I'm using notify-osd
NOTIFYARGS="-h string:x-canonical-private-synchronous:true -h string:x-canonical
-private-icon-only: \"notify\" "

CURRENT_LANG=$(setxkbmap -print | awk -F+ '/xkb_symbols/{print substr($2,1,2)}')

i=0
while [[ $CURRENT_LANG != ${LANGS[$i]} ]] && [[ $i < $((${#LANG[@]}-2)) ]];
do
  i=$((i+1))
done

if [[ $i = $((${#LANGS[@]}-1)) ]]; then
  NEWLANG=${LANGS[0]}
  NEWVARIANT=${VARIANTS[0]}
else
  NEWLANG=${LANGS[$((i+1))]}
  NEWVARIANT=${VARIANTS[$((i+1))]}
fi

setxkbmap $NEWLANG $NEWVARIANT

echo $NEWLANG $NEWVARIANT
if [[ $NOTIFY = "true" ]]; then
  notify-send -i "$ICONPATH"/$NEWLANG.png $NOTIFYARGS
fi

don't drink unwashed fruit juice.
i never make predictions, especially about the future.

Offline

#1397 2010-12-10 17:43:43

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

Re: Post your handy self made command line utilities

This is a script for Compiz' Enhanced Zoom Desktop.

It's for when you want the convenience of "Fit zoomed area to window" but for something smaller than the entire window, like a youtube video or a game in virtualbox.

You put the mouse at the top left, call the script with 'zoombm 640 480' to see if the zoom is OK, and then call the script with 'zoombm store' to write these coordinates to a text file. It will also opens gvim, because the default values are probably wrong for name, width and height.
An entry is formed as: "Name Start-x Start-y Width Height"

When you call the script without arguments, it will ask for an entry in the bookmarks file with dmenu. It will make the item you choose the new top item so it's easier to select next time.

It uses xdotool to get mouse coordinates and to draw the zoom box.

It presumes the "Zoom Box" keybinding is "<Super>Button3"

#! /bin/bash
bmfile=~/.zoombm

[[ "$1" = store ]] && {
 {
  xdotool getmouselocation | sed 's/x:\([0-9]*\) y:\([0-9]*\) .*/Name \1 \2 640 480/'
  cat $bmfile
 } > $bmfile.new
 mv $bmfile.new $bmfile
 gvim $bmfile
 exit
}

[[ -n "$1" && -n "$2" ]] && {
 x=$1
 y=$2
} || {
 result=$(cat $bmfile | dmenu)
 read name a b x y <<< "$result"
 [[ -z "$a" ]] && exit
 xdotool mousemove $a $b
 {
  echo "$result"
  grep -v "$result" $bmfile
 } > $bmfile.new
 mv $bmfile.new $bmfile
}

xdotool keydown Super \
mousedown 3 \
mousemove_relative $x $y \
mouseup 3 \
keyup Super \
mousemove_relative -- -$x -$y

Offline

#1398 2010-12-14 09:02:15

3])
Member
From: Netherlands
Registered: 2009-10-12
Posts: 215

Re: Post your handy self made command line utilities

I got tired of opening nano to copy text within a file to the clipboard. Hence a frontend to xsel, was born.
You need xsel though (pacman -S xsel).

All you have to do to create this magical copy to clipboard function is to create an alias.

alias pcc="xsel -b <"

in your .bashrc.

Enjoy.

p=please
c=copy
   to
c=clipboard

Incredibly simple, yet useful for a few.

Last edited by 3]) (2010-12-15 13:58:46)


“There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.”-- C.A.R. Hoare

Offline

#1399 2010-12-22 14:01:38

Lucian
Member
From: Indianapolis, IN
Registered: 2010-09-07
Posts: 6

Re: Post your handy self made command line utilities

This is a pacman update script for conky.

#!/usr/bin/python

# Script Name: checkupdates.py
# Author: Lucian Adamson <lucian.adamson@yahoo.com>
# What This Script Does: Formats how the output of pacman updates in conky looks
#
# Examples:
# Say you want to output your pacman updates to conky but only want the top 5 to show
# using the colors red, blue, and green for each line and you wish to have the number of updates
# in a header, you would do this:
#
# ${execpi 900 /path/to/checkupdates.py -e 'Updates ($n):' -c 'red,blue,green' -n 5}
# OR using long options
# ${execpi 900 /path/to/checkupdates.py --header='Updates ($n):' --colors='red,blue,green' --number-of-updates=10}
#
# This function can be run from the command line and there is a -h, --help option
# /path/to/checkupdates.py --help
#
# You can use this script to just output the number of updates like this:
# /path/to/checkupdates.py -g
#
# Sample output of checkupdates.py --colors='red,white,blue' -e '$n updates'
#
#6 updates
#${color red}chromium 5.0.375.125-1$color
#${color white}libpciaccess 0.11.0-1$color
#${color blue}mutagen 1.19-1$color
#${color red}orc 0.4.6-1$color
#${color white}q4wine 0.119-1$color
#${color blue}wine 1.3.0-1$color


from sys import argv as gv
from optparse import OptionParser as op
import re

onecolor=False # Variable that will change if more than one color is given

#--------------------------- Run a shell command and retrieve output --------------------------
class Command(object):
    def __init__(self, command):
        self.command = command
    def run(self, shell=True):
        import subprocess as sp
        process = sp.Popen(self.command, shell = shell, stdout = sp.PIPE, stderr = sp.PIPE)
        self.pid = process.pid
        self.output,self.error = process.communicate()
        self.failed = process.returncode
        return self
    
    @property
    
    def returncode(self):
        return self.failed

# ------------------------ Parse command line options and arguments ------------------------
parser = op()
parser.add_option('-c', '--colors', action='store', default='orange,red', help='Supply either one or more colors in comma separated values. Example: orange,red,blue')
parser.add_option('-n', '--number-of-updates', action='store', default=10, type='int', help='The number of maximum updates to display in Conky.')
parser.add_option('-g', '--get-number', action='store_true', default=False, help='Returns the number of updates available through pacman.')
parser.add_option('-e', '--header', action='store', default='', help='Sets a header for your conky output. Replacable variables are $n for number of updates.')
(options, args) = parser.parse_args()

# --------------------------------------------- The -g flag ------------------------------------------------

theupdates = Command("pacman -Qu").run()
theupdates_ord = theupdates.output
theupdates_ord = theupdates_ord.decode('ascii')
theupdates = theupdates_ord.split("\n") # Split output of -Qu by line
numdates = len(theupdates) # Count the lines
if numdates > 0: # if there are actually updates
    try:
        theupdates.remove('') #remove the blank line at end
        numdates=len(theupdates) # recount
    except ValueError:
        pass # If error because there is no blank line, keep going
if options.get_number:
    print(numdates)
    quit()

# ------------------------------------------ Set Variables -------------------------------------------
numupdates = options.number_of_updates #Variables set by optparse
colors = options.colors
header = options.header
# ----------------------------------------- Parse the Colors -----------------------------------------

colors = colors.lower() # convert text to lowercase
if re.search(',', colors): # if more than one color
    colors = colors.split(',') # split them
    for x in range(0, len(colors), 1): # loop through and remove unnec spaces
        colors[x] = colors[x].strip(' ')
    colorlist_len = len(colors) # This counts the colors
else:
    onecolor=True

# --------------------------------------------- The Code -----------------------------------------------

pacup_split = theupdates 

i = 1
pHolder = ''
totalnow = 1
if not header=='': # If there is a header...
    header = header.replace("$n", str(numdates)) #...replace $n with num of updates
    pHolder = header + '\n' # and append if to pHolder variable for output with actual updates
    
if onecolor== True: # if there is only one color
    for each in pacup_split: # loop through
        if not totalnow > numupdates: # makes sure we only display the alloted number of updates
            pHolder = pHolder + "${color " + colors + "}" + each + "$color\n"
        else:
            pHolder = pHolder.rstrip('\n') + '...\n' #if there are more, we recognize that by adding 3 periods
            break
        totalnow += 1
    print(pHolder.rstrip('\n')) # strip off the remaining new line to conserve our conky space
    quit() #we're done so quit the script

for newout in pacup_split: # this is the code for more than one color
    if i > colorlist_len: i = 1 # if i is greater than number of colors, then reset i
    if not totalnow > numupdates:
        pHolder = pHolder + '${color ' + colors[i - 1] + '}' + newout + '$color\n'
    else:
        pHolder = pHolder.rstrip('\n') + '...\n' # we put a \n to conform to line of code above
        break
    i += 1 # increase i by one until it is reset
    totalnow += 1 # helps make sure we only display the correct number of updates

print(pHolder.rstrip('\n')) #print the updates without the trailing \n

Here is a link to a hard copy of the script: http://snotrocket.tk/scripts/checkupdates.py
Here is a screenshot of it in action: http://img694.imageshack.us/img694/6145 … 090120.png
And here is the code I use for the script in the screenshot:

${color red}UPDATES${color white}${execpi 900 /home/lucian/Scripts/checkupdates.py -e ' ${color red}($n)' --number-of-updates=5 -c white}

Offline

#1400 2010-12-25 12:40:32

Lucian
Member
From: Indianapolis, IN
Registered: 2010-09-07
Posts: 6

Re: Post your handy self made command line utilities

Previously in this thread, a user wrote a 'makescript' function to quickly create a file, place in a selected shabang and then chmod it executable. I have re-written this function because of all the possible shabangs one could use, it would be tedious to hard-code these in to a script. However, I do appreciate the idea and have made improvements.

msu is a function
msu () 
{ 
    [ $# -eq 0 ] || [ $# -lt 2 ] && echo '            Usage: msu [FILENAME] [INTERPRETER]
            FILENAME - Can either be /path/to/filename or without /path/to for cwd.
            INTERPRETER - Dont use /path/to/interpreter, just the name
                          of the interpreter.' && return 1
    shabang='#!' # I chose to hold the first part of the shabang in a single quote so i dont have to escape
    interp='' # Initialize variables
    chosen_interp="$2"
    chosen_fn="$1"
    shift
    shift #after assigning args one and two, i shift twice so I can use $* for the remaining (in case of arguments for the shabang)
    chosen_args="$*" 
    locator="$(which $chosen_interp 2> /dev/null)" # This holds the /path/to your chosen interpreter
    if [[ "$locator" != "" ]]; then
        interp="$shabang$locator" # Create and store the shabang
    else
        interp='#!/bin/bash'
    fi;
    if [ -f "$chosen_fn" ]; then #if the chosen filename exists...
        read -p "$chosen_fn is an existing file, over-write? (y/n) " action
    else
        action="y" # if not, default to yes action in the case below
    fi
    case $action in 
        y | Y)
            echo "$interp $chosen_args" > $chosen_fn && chmod +x $chosen_fn && echo "msu: success" && return 0
        ;;
        n | N)
            echo "msu: actions aborted" && return 0
        ;;
        *)
            echo "msu: $action: invalid response" && return 0
        ;;
    esac
}

Lets take a look at an example.

msu test_file python

The script will plug 'python' in to the which program therefore outputting the /path/to/python, add the shabang #!, and then output it to your selected file. If the file exists, it will ask if you wish to over-write.

Any comments/criticism welcome. smile

UPDATE: I updated the script because I know some shabangs have arguments to go with them. For example #!/usr/bin/conky -c and added comments.

msu .conkyrc conky -c

This will create a conky configuration that is executable and will automatically open a new conky session. smile

Last edited by Lucian (2010-12-25 23:39:19)

Offline

Board footer

Powered by FluxBB