You are not logged in.

#1801 2012-05-05 20:29:59

Darksoul71
Member
Registered: 2010-04-12
Posts: 319

Re: Post your handy self made command line utilities

karol wrote:

For burning CDs I use the '-dao' (disc at once) switch and I get the same md5sums when checksumming directly.

Strange...well, I mostly burn DVDs mastered from a script as ISO.  I got different checksums here.

Edit:
Strange...

The MD5 sums are really identical. Here are those from rip2ISO:
07a0a07fd8dd4a3012c31083f7314dba  /dev/sr0
07a0a07fd8dd4a3012c31083f7314dba  TORCHLIGHT.ISO

This is the output of> md5sum /dev/sr0
07a0a07fd8dd4a3012c31083f7314dba  /dev/sr0

And here is the output of >dd if=/dev/sr0 | md5sum
07a0a07fd8dd4a3012c31083f7314dba  -

I have no clue what has happened back then when I wrote the scripts. Anyway, since they are bash scripts anyone can feel free to modify the MD5 generation part smile

Thanks for pointing out, karol !

Last edited by Darksoul71 (2012-05-06 07:56:59)


My archlinux x86_64 host:
AMD E350 (2x1.6GHz) / 8GB DDR3 RAM / GeForce 9500GT (passive) / Arch running from 16GB USB Stick

Offline

#1802 2012-05-10 18:45:29

debdj
Member
Registered: 2012-01-19
Posts: 163

Re: Post your handy self made command line utilities

Here are some of my written scripts:
the first one takes in an archive name, a dir name(optional) and xtracts the archive to destination or current dir.

#!/bin/bash

clrstart="\033[1;34m"  #color codes
clrend="\033[0m"

if [ "$#" -lt 1 ]
 then
 echo -e "${clrstart}Pass a filename. Optionally a destination folder. You can also append a v for verbose output.${clrend}"
 exit 1 #not enough args
fi

if [ ! -e "$1" ]
 then
 echo -e "${clrstart}File does not exist!${clrend}"
 exit 2 #file not found
fi


if [ -z "$2" ]
then
 DESTDIR="." #set destdir to current dir
else
 if [ ! -d "$2" ]
 then
  echo -e -n "${clrstart}Destination folder doesn't exist or isnt a directory. Create? (y/n): ${clrend}"
  read response
  #echo -e "\n"
  if [ "$response" = y -o "$response" = Y ]
  then
   mkdir -p "$2"
   if [ $? -eq 0 ]
   then
    DESTDIR="$2"
   else exit 6 #Write perms error
   fi
  else
 echo -e "${clrstart}Closing.${clrend}"; exit 3 # n/wrong response
 fi
 else
 DESTDIR="$2"
 fi
fi

if [ ! -z "$3" ]
then
 if [ "$3" != "v" ]
 then
 echo -e "${clrstart}Wrong argument $3 !${clrend}"
 exit 4 #wrong arg 3
 fi
fi

filename=`basename "$1"`

#echo "${filename##*.}" debug

case "${filename##*.}" in
  tar)
     echo -e "${clrstart}Extracting $1 to $DESTDIR: (uncompressed tar)${clrend}"
     tar x${3}f "$1" -C "$DESTDIR"
     ;;
  gz)
     echo -e "${clrstart}Extracting $1 to $DESTDIR: (gip compressed tar)${clrend}"
     tar x${3}fz "$1" -C "$DESTDIR"
     ;;
  tgz)
     echo -e "${clrstart}Extracting $1 to $DESTDIR: (gip compressed tar)${clrend}"
     tar x${3}fz "$1" -C "$DESTDIR"
     ;;
  xz)
     echo -e "${clrstart}Extracting  $1 to $DESTDIR: (gip compressed tar)${clrend}"
     tar x${3}f -J "$1" -C "$DESTDIR"
     ;;
  bz2)
     echo -e "${clrstart}Extracting $1 to $DESTDIR: (bzip compressed tar)${clrend}"
     tar x${3}fj "$1" -C "$DESTDIR"
     ;;
  zip)
     echo -e "${clrstart}Extracting $1 to $DESTDIR: (zipp compressed file)${clrend}"
     unzip "$1" -d "$DESTDIR"
     ;;
  rar)
     echo -e "${clrstart}Extracting $1 to $DESTDIR: (rar compressed file)${clrend}"
     unrar x "$1" "$DESTDIR"
     ;;
  7z)
     echo -e  "${clrstart}Extracting $1 to $DESTDIR: (7zip compressed file)${clrend}"
     7za e "$1" -o"$DESTDIR"
     ;;
  *)
    echo -e "${clrstart}Unknown archieve format!"
    exit 5
    ;;
esac

exit 0

This one lists the contents of a archive file.

#!/bin/bash

if [ "$#" -lt 1 ]
 then
 echo "Pass a filename. You can specify v after filename for verbose output."
 exit 2 #filename not passed
fi

if [ ! -e "$1" ]
 then
 echo "File does not exist!"
 exit 3 #file not found
fi


if [ ! -z "$2" ]
then
 if [ "$2" = "v" ]
  then
  echo  "Verbose on." #verbose output by tar 
 else
  echo "Wrong argument!"
  exit 4  #wrong second argument
fi
fi

filename=`basename "$1"`

#echo "${filename##*.}" debug

case "${filename##*.}" in
  tar)
     echo "Displaying contents of $1: (uncompressed tar)"
     tar t${2}f "$1"
     ;;
  gz)
     echo "Displaying contents of $1: (gip compressed tar)"
     tar t${2}fz "$1"
     ;;
  tgz)
     echo "Displaying contents of $1: (gip compressed tar)"
     tar t${2}fz "$1"
     ;;
  xz)
     echo "Displaying contents of $1: (gip compressed tar)"
     tar -J "$1"
     ;;
  bz2)
     echo "Displaying contents of $1: (bzip compressed tar)"
     tar t${2}fj "$1"
     ;;
  zip)
     echo "Displaying contents of $1: (zipp compressed file)"
     unzip -l "$1"
     ;;
  rar)
     echo "Displaying contents of $1: (rar compressed file)"
     unrar l${2}t "$1"
     ;;
  7z)
     echo  "Displaying contents of $1: (7zip compressed file)"
     7za l "$1"
     ;;
  *)
    echo "Unknown archieve format!"
    exit 1
    ;;
esac

exit 0

This last one lists the total size of a directory, no. of subdirs and files.
A word of caution, this's a bit resource hungry because it recurses all the way down under the dir structure (keeping within the same partition though). You could specify not to recurse by appending 'nr'  .
Better not run it in / with recurse on.

#!/bin/bash

blustart="\033[1;34m"
whstart="\033[0;37m"
clrend="\033[0m"

which tree &>/dev/null
if [ $? -ne 0 ]
then
 echo -e "${whstart}This script needs 'tree' to run. Exiting..${clrend}"
exit 2 #tree not available
fi


recurse=""
rdir=""

if [ "$1" = 'nr' -o "$2" = "nr" ]
 then
 recurse=" -d 1" #no recurse. recurse is default - for du
 rdir=' -L 1' #set max depth for tree to 1 i.e. no recurse - for tree
fi

if [ ! -z "$1" -a "$1" != "nr" ]
 then
 if [ ! -d "$1" ]
  then
  echo -e "$1 is not a directory!"
  exit 1 #not a dir
 else
  field="$1"
 fi
else
field='.'
fi

echo -e "${whstart}Populating...${clrend}"

du -acxhl${recurse} "$field" > .dirstat # -c give total, -x same fs, -h human readable, -l count hardlinks

tsize=`tail -n 1 .dirstat | cut -f 1` #total size
titems=$(( `wc -l .dirstat | cut -d ' ' -f 1` - 2 )) #total items
tdirs=`tree -d${rdir} "$field" | tail -n 1 | cut -d ' ' -f 1`  #total no of dirs
tfiles=$(( $titems - $tdirs )) #total no of files

echo -e "${whstart}Total size:${clrend} ${blustart}$tsize${clrend}, ${whstart}Number of Directories:${clrend} ${blustart}$tdirs${clrend}, ${whstart}Number of files:${clrend} ${blustart}$tfiles${clrend}"

rm .dirstat

exit 0

Last edited by debdj (2012-05-10 18:47:57)

Offline

#1803 2012-05-12 09:41:14

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

Re: Post your handy self made command line utilities

An alternative version of the above total directory size script:

du -h --max-depth=1 "$@" | sort -k 1,1hr -k 2,2f

Or even:

#!/bin/sh
IFS="$(printf '\n\t')"
du -sk $@    \
  | sort -nr \
  | awk 'BEGIN{ pref[1]="K"; pref[2]="M"; pref[3]="G";} { total = total + $1; x = $1; y = 1; while( x > 1024 ) { x = (x + 1023)/1024; y++; } printf("%g%s\t%s\n",int(x*10)/10,pref[y],$2); } END { y = 1; while( total > 1024 ) { total = (total + 1023)/1024; y++; } printf("Total: %g%s\n",int(total*10)/10,pref[y]); }'

ff - make the output from a find command easier to read
http://devel.japh.se/utils/ff.png
mkdr - mv file.foo to foo/, mkdir it if it doesn't exist
http://devel.japh.se/utils/seen.png
seen - keep track of the episodes I've watched
http://devel.japh.se/utils/seen.png

# -- mod edit: read the Forum Etiquette and only post thumbnails http://wiki.archlinux.org/index.php/For … s_and_Code [jwr] --

Last edited by jasonwryan (2012-05-12 19:56:20)

Offline

#1804 2012-05-12 10:57:50

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

Re: Post your handy self made command line utilities

I have been meaning to do something like this and was thinking of using extended file attributes to do it. Using the sticky bit is neat.

Offline

#1805 2012-05-12 12:34:51

debdj
Member
Registered: 2012-01-19
Posts: 163

Re: Post your handy self made command line utilities

du -h --max-depth=1 "$@" | sort -k 1,1hr -k 2,2f

that just lists the contents with a reverse sort.

the second one works, though unnecessary calculations. du gives -h output.
I've to learn awk big_smile

Offline

#1806 2012-05-12 21:24:03

earsplit
Member
Registered: 2012-03-31
Posts: 187
Website

Re: Post your handy self made command line utilities

Got sick of formatting html to post stuff on my blog.  This really comes in handy.

#!/usr/bin/perl

my $filename = $ARGV[0];
my $read;
my $char;

open(FILE, $filename)
	or die "Invalid file $filename\n";

print "<pre class=\"prettyprint\">\n";
while ($read = read FILE, $char, 1)
{
	if($char eq "<") {
		print "&lt;";
	}
	elsif($char eq ">") {
		print "&gt;";
	}
	else {
		print $char;
	}
}
print "</pre>\n<p></p>";

close(FILE);

See it in action!

http://chmod755.tumblr.com


((( configs :: website )))

Offline

#1807 2012-05-13 13:18:39

jac
Member
From: /home/jac
Registered: 2009-05-19
Posts: 431
Website

Re: Post your handy self made command line utilities

@debdj, @dmz: what is that du thing supposed to do? It looks like one is equivalent to

du -hs

(but with better accuracy), and one is equivalent to

du -h --max-depth=1 | sort -hr

I've never seen the -k option used on sort before, and the field description part of the man page is sort of confusing.

Edit: oh, I see, debdj has a more complicated script dmz was trying to shorten? debdj, I have to tell you, your colorful error messages means I can't see them at all wink Not all of us have use non-white for the background color.

Last edited by jac (2012-05-13 13:22:24)

Offline

#1808 2012-05-13 15:09:19

debdj
Member
Registered: 2012-01-19
Posts: 163

Re: Post your handy self made command line utilities

jac wrote:

@debdj, @dmz: what is that du thing supposed to do? It looks like one is equivalent to
du -hs
(but with better accuracy), and one is equivalent to
du -h --max-depth=1 | sort -hr

I've never seen the -k option used on sort before, and the field description part of the man page is sort of confusing.

du is a command to list file space usage.
the -h option lists file sizes in human readable format like 1KB instead of 1024bytes and 1MB instead of 1048576 bytes.
and max-depth as it sounds, keeps listing within the current dir, although it recurses all the way down to find the total dir size. the man page is pretty straightforward.

The -k  option in sort is to sort on basis of a field. suppose you have a file like

blablabla 30/12/2011
blabla2 12/03/2012

and you want to sort on basis of the dates.
so you'll write

sort -k 2.7,11 -k 2.4,5 -k 2.1,2 

which means: our fields are delimited by <space> (default), so the second field are the dates.
1> choose field 2, sort 7th - 11th characters  ( the years)
2> choose field 2, sort 4th - 5th characters  (the months)
3> choose field 2, sort 1th - 2th characters  (the dates)

just saying sort -k 2.7 -k 2.4 -k 2.1 also works . but its better to be explicit. there are more options you can append to -k ,like -k 2.7,11nr [n numeric sort, r reverse sort]

jac wrote:

Not all of us have use non-white for the background color.

you can easily change the color codes at top of the script

blustart="\033[1;34m"
whstart="\033[0;37m"
clrend="\033[0m"

keep clrend the same. change the other codes, Here's a list of codes.

Last edited by debdj (2012-05-13 15:10:35)

Offline

#1809 2012-05-14 15:41:19

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

Re: Post your handy self made command line utilities

2ch board/thread watcher. It creates and opens html files by default in ~/2ch/ with firefox.

http://sprunge.us/fhVN

Session files are kept in ~/2ch/.
It needs to be run in a loop, e.g.:

while 2ch; do ((counter++ % 16 == 0)) && 2ch --summary; sleep 15m; done

Configuration files need to be made in ~/2ch/.

It has two modes:
./2ch --summary: Opens an html table with each board in the file "boards" in a separate column showing all the threads that have gotten replies since the last invocation of --summary mode with amount of posts, title, link to thread, link to thread with a range of the new posts (starting a bit before).
Use the file "highlight" to highlight threads that match text.

./2ch (no arguments): Opens html files for each thread that matches a line in "threads" that have new replies since the last invocation showing just those replies.
It also appends those posts to a file with all the posts of that thread.
URLs are reshaped to direct links. Links to posts become anchors in the file that has the entire thread.
Files made per thread: <thread name>.html and <thread name>.recent.html

Running one mode doesn't influence the session files of the other.

The file "blacklist" can be used to ignore threads.

Offline

#1810 2012-05-16 19:18:52

jgreen1tc
Member
From: St. Louis
Registered: 2011-05-16
Posts: 251

Re: Post your handy self made command line utilities

Just wrote my first bash script! Its a pretty simple way to echo which window manager is active (Ratpoison or Openbox). This script was needed in my case because the command 'wmctrl -m' fails in Ratpoison. But I'm pretty proud of my researching abilities right now. They really helped me piece everything I was thinking about together.

#!/bin/bash
wm=`wmctrl -m|head -n1`
if [[ "$wm" == *Openbox* ]]
then    
    echo "Openbox"
else
    echo "Ratpoison"
fi

The hardest part for me was finding out how to check the output of a command against something. I feel so accomplished now lol

Offline

#1811 2012-05-17 15:10:20

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

Re: Post your handy self made command line utilities

Update to continuous rss checker I posted ages ago, now it will work if the rss document has no newlines, opens firefox on matching links, and keeps a log of when you opened a link or if firefox wasn't running to open it.
Files: ~/.rss_log (log file)  ~/.rss_getter_terms (each link is opened and checked for a string in this file)
Needs to be run in a loop.

#! /bin/bash
# $1 = http://*.rss
#
# Put terms in ~/.rss_getter_terms, newline separated.

BROWSER=firefox
IFS=$'\n'

for article in $(curl -s "$1" | grep -o 'link>[^>]*' | sed 's/link.//;s/#.*//' | tail -n +2); do
grep -qF opened$'\t'"$article" ~/.rss_log && continue
if curl -s "$article" | grep -qf ~/.rss_getter_terms; then
	{
	if pgrep $BROWSER &>/dev/null; then
		$BROWSER "$article"
		echo -e "opened\t$article\t$(date)"
	else
		echo -e "missed\t$article\t$(date)"
	fi
	} >> ~/.rss_log
fi
sleep 2
done

Offline

#1812 2012-05-17 16:00:45

jac
Member
From: /home/jac
Registered: 2009-05-19
Posts: 431
Website

Re: Post your handy self made command line utilities

debdj wrote:

... du is a command to list file space usage...

Heheh, I appreciate the very detailed explanation. I had hoped my alternates would have given the impression I at least know some of this stuff wink

The -k explanation makes perfect sense. One was practically equivalent to one I wrote, but he explicitly forced the contents to be in alphabetical order if the same sizes occurred. He used -k to switch between human readable reverse sort and alphabetical (ignoring case).

debdj wrote:
jac wrote:

Not all of us have use non-white for the background color.

you can easily change the color codes at top of the script ... snip ...

Yes, I'm well aware. I was just giving (hopefully) helpful criticism. I was only able to diagnose the problem by opening the thing up.

Offline

#1813 2012-05-18 14:31:30

debdj
Member
Registered: 2012-01-19
Posts: 163

Re: Post your handy self made command line utilities

jac wrote:

Heheh, I appreciate the very detailed explanation. I had hoped my alternates would have given the impression I at least know some of this stuff wink

lmao
sometimes I go a little overboard.

Offline

#1814 2012-05-18 20:21:42

Roken
Member
From: South Wales, UK
Registered: 2012-01-16
Posts: 1,281

Re: Post your handy self made command line utilities

This can probably be done much more cleanly, but it works. Uses tracker and mpg123 to locate a tune in your collection (by title, artist etc) and optionally play one of the results. Syntax is:

 fmusic searchterm number

where searchterm is what you are hunting for and number (optional) will play the Xth song from the results with mpg123

#/!bin/bash
IFS="
"
TITLE=$1
PLAY=$2

tracker-search -m "$TITLE" | sed 's/\%[0-9][0-9]/ /g' | sed 's/file\:\/\/\///g' | sed 's/^ *//g' | sed 's/^/\//g'  > /tmp/foundfiles
sed -i '1,1d' /tmp/foundfiles
sed -i '$d' /tmp/foundfiles
FOUND=`wc -l /tmp/foundfiles | awk '{print $1}'`
cat /tmp/foundfiles
echo "Found $FOUND results"
if [ ! -z $2 ]; then
	if [ $2 -gt $FOUND ]; then
		echo "Cannot play - not enough results"
	else
		mpg123 "`head -n$2 /tmp/foundfiles | tail -n1`"
	fi
fi

rm /tmp/foundfiles

EDIT: Just so that you know - you can search for multi word titles/artists by enclosing within quotes. eg fmusic "Elvis Presley"
fmusic is the name I gave the script - replace with whatever you call it.

Last edited by Roken (2012-05-18 23:34:00)


Ryzen 5900X 12 core/24 thread - RTX 3090 FE 24 Gb, Asus Prime B450 Plus, 32Gb Corsair DDR4, Cooler Master N300 chassis, 5 HD (1 NvME PCI, 4SSD) + 1 x optical.
Linux user #545703

/ is the root of all problems.

Offline

#1815 2012-05-19 07:18:30

debdj
Member
Registered: 2012-01-19
Posts: 163

Re: Post your handy self made command line utilities

This is a small script that shortens urls to is.gd/xxxxxx
Input can be through stdin or clipboard. If its from stdin, output is given to stdout. additionally copied to clipboard if xclip is available.
If input is from clipboard, output is copied to clpboard and displayed through a zenity dialog if available, otherwise to stdout.

#!/bin/bash
#script to shorten urls with is.gd

[ -n "$1" ] && { echo "$1" | grep -E -q '^www|^WWW|^http://|^https://' && url="$1"; }

if [ -z "$1" ]; then
take=`xclip -o 2>/dev/null` && { $(echo "$take" | grep -E -q '^www|^WWW|^http://|^https://') && url="$take"; } \
|| { echo "no valid url specified / xclip not available" && exit 2; }
fi

#echo "$take"
#echo "$url"

#actual shortening

request=`echo "http://is.gd/create.php?format=simple&url=${url}"`
little=`curl -G "$request" 2>/dev/null`

if [ $(echo "$little" | grep -c 'Error') -gt 0 ]; then  #
 { [ `which zenity 2>/dev/null` ] && zenity --info --title='Error' --text="is.gd message: $little"; exit 3; } || echo "is.gd message: $little"; exit 3 #url error

else

if [ -n "$1" ]; then
  if [ `which xclip 2>/dev/null` ]; then { echo "$little"|xclip && echo -e "Shortnd lnk: $little \nCopied to clipboard. Use middle click to paste."; exit 0; }
  else echo "Shortened url: $little"; fi; exit 0

elif [ `which zenity 2>/dev/null` ]; then
  { zenity --info --title="Shortened link" --text="$little\n\nPress OK to copy to Clipboard." && echo -n "$little"|xclip; exit 0; }
 else { echo "$little"|xclip && echo -e "Shortnd lnk: $little \nCopied to clipboard. Use middle click to paste."; }; fi

fi

exit 0

I use openbox with lxde,  in my lxde-rc.conf ::

<keybind key="C-A-s">
   <action name="Execute">
   <command>short</command>
   </action>
  </keybind>

in the keyboard shotcuts section which makes it pretty handy. ('short' is a link to this script in my path)
you can also call it through dmenu.

But one thing I dont understand is, stuff copied to clipboard through xclip has to be pasted through middle click. Normal paste doesn't work for that, are there different clipboards then?

Last edited by debdj (2012-05-19 07:37:46)

Offline

#1816 2012-05-19 20:25:25

Cloudef
Member
Registered: 2010-10-12
Posts: 636

Re: Post your handy self made command line utilities

URXVTC, urxvt in daemon mode (needed for below script)

#!/bin/sh
# Urxvt client that launches daemon if needed
#
# needs: urxvt

# main
main() {
   urxvtc "$@"
   [[ ! $? -eq 2 ]] && return
   urxvtd -q -o -f
   urxvtc "$@"
}
main $@

URXVTQ, quake dropdown urxvt terminal
Apparently you can't have variable in bash style sequences.
So edit the 300 in animate functions to determite height.

#!/bin/bash
# Urxvt quake console
#
# needs: urxvt, xdotool

# border width * 2
BORDER=4

# offset
X=0
Y=125

# width
WIDTH=1440

# from top
animate() {
   for i in {1..300..5}; do
      xdotool windowsize $@ $((WIDTH-BORDER)) $i
   done
}

# to top
animate2() {
   for i in {300..1..5}; do
       xdotool windowsize $@ $((WIDTH-BORDER)) $i
   done
}

# spawn
spawn() {
   URXVTC -name URxvtq -geometry 1x1+$X+$Y
   wid="$(xdotool search --classname URxvtq | head -1)"
   xdotool windowfocus $wid
   animate $wid
}

# toggle
toggle() {
   local visible="$(xdotool search --onlyvisible --classname URxvtq 2>/dev/null)"
   if [ ! "$visible" ]; then
      xdotool windowmap $wid
      xdotool windowfocus $wid
      xdotool windowraise $wid
      animate $wid
   else
      animate2 $wid
      xdotool windowunmap $wid
   fi
}

# main
main() {
   local wid="$(xdotool search --classname URxvtq 2>&1 | head -1)"
   [[ "$wid" == *BadWindow* ]] && exit
   [ ! "$wid" ] && spawn || toggle
}
main $@

URXVTD, dtach with urxvt.
Single session by default, which may defeat purpose for some.
I mainly use it myself to autostart command line programs where they left off beetwen X sessions.

#!/bin/sh
# dtach a urxvt client
# only allow one urxvt session by default
#
# needs: dtach
# optional: urxvt

[ ! "$TERMINAL" ] && TERMINAL="urxvt"

# error
error() { echo "$@"; exit 1; }

# check pid
check_pid() {
   local PID="$(cat "$@")"
   kill -0 $PID &> /dev/null && error "already running" || rm "$@"
}

# attach
# $1: name of attach
# $2: socket file
# $3: pid file
attach() {
   $TERMINAL -title "$1" -name "$1" -e dtach -a "$2" &
   echo "$!" > "$3"
}

# create new session
# $1: name of session
# $2: program to run
# $3: socket file
# $4: pid file
create() {
   $TERMINAL -title "$1" -name "$1" -e dtach -c "$3" "$2" &
   echo "$1" > "$4"
}

# $1: name of dtach
# $2: program to run
main() {
   local SOCKET_DIR="/tmp/urxvtd"
   local PIDFILE="$SOCKET_DIR/$1.pid"
   local SOCKET="$SOCKET_DIR/$1.sck"
   [[ -d "$SOCKET_DIR" ]] || mkdir "$SOCKET_DIR"
   [[ -d "$SOCKET_DIR" ]] || error "no socket directory"

   # comment this line to allow multiple
   # urxvt sessions
   [[ -e "$PIDFILE" ]] && check_pid $PIDFILE

   [[ -e "$SOCKET" ]]    && attach "$1" "$SOCKET" "$PIDFILE" && return
   [[ ! -e "$PIDFILE" ]] && create "$1" "$2" "$SOCKET" "$PIDFILE" && return
}
main "$1" "$2"

Offline

#1817 2012-05-20 08:11:08

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

Re: Post your handy self made command line utilities

Noticed a couple of forum posts featuring BASH scripts that output any files not installed as part of a package. This is my Python version:

#!/usr/bin/env python3

import os
import subprocess

IGNORE = [
    '/boot',
    '/dev',
    '/home',
    '/media',
    '/mnt',
    '/proc',
    '/root',
    '/router_root_fs',
    '/run',
    '/srv',
    '/sys',
    '/tmp',
    '/usr/local',
    '/var/abs',
    '/var/cache',
    '/var/lib/oprofile',
    '/var/lib/pacman',
    '/var/lib/texmf',
    '/var/log',
    '/var/run',
    '/var/spool',
    '/var/tmp',
]

o = subprocess.getoutput('pacman -Ql')
files = {x.split()[1] for x in o.split('\n') if x[-1] != '/'}

for dirname, dirnames, filenames in os.walk('/'):
    for subdirname in dirnames[:]:
        sd = os.path.join(dirname, subdirname)
        if sd in IGNORE:
            dirnames.remove(subdirname)

    dirnames.sort()

    for filename in filenames:
        f = os.path.join(dirname, filename)
        if f not in files:
            print(f)

Had no idea how many untracked files there were in my root partition.

Offline

#1818 2012-05-21 10:17:41

grim
Member
Registered: 2012-02-15
Posts: 41

Re: Post your handy self made command line utilities

It does what it says, you get to choose from a dynamic menu containing all possible CPU Scaling governors.
I have a shortcut that runs it inside `urxvt -e'
Can be easily made into an X application by changing dialog to xdialog and sudo to gksudo
I suggest however that it should remain as a console script because that way you keep the same script for both terminal only (or ssh) sessions and X session.

#!/bin/bash
# ===  Grim's 31337 CPU Scaling Governor changer }:| === #
# Licensed under the WTFPL
# "auto" detects the number of cores and available governors and builds the
# selection menu accordingly
# Some things are hardcoded
# - Path to available governors file, because all computers have atleast
#   one cpu/core anyway and I'm assuming you will run this on Arch so the path
#   should be the same. If that's not the case, just find where your system
#   keeps the file, the path should be similar.
# - this will miserably fail without an already running CPU Scaling
#   configuration, but using this little snippet would be quite redundant
#   without it anyway.
clear
gov_list="";
cpu_count=`grep -c 'model name' /proc/cpuinfo`

for g in `cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors`
do
        gov_list="$gov_list $g $g"
done

coutput=`coutput 2>/dev/null` || coutput=/tmp/scaling$$
trap "rm -f $tf" 0 1 2 5 15
dialog  --backtitle "Set a governor for CPU scaling" \
        --menu "Set governor to:" 10 40 5 $gov_list 2> $coutput
rval=$?
selection=`cat $coutput`
case $rval in
  0)
      echo -e "\e[00;36mSwitching $cpu_count CORE/CPU(s) to the \e[00;31m$selection\e[00;36m governor\e[00m"
      for ((i=0;i<$cpu_count;i++));
      do
          sudo cpufreq-set -c $i -g $selection;
      done
      ;;
  1)
      # Chose "Cancel"
      echo -e "\e[00;31mCancelled\e[00m";;
  255)
      # Pressed Escape
      echo -e "\e[00;31mCancelled\e[00m";;
esac

Last edited by grim (2012-05-21 10:23:34)

Offline

#1819 2012-05-22 19:43:46

Roken
Member
From: South Wales, UK
Registered: 2012-01-16
Posts: 1,281

Re: Post your handy self made command line utilities

Not sure if this is the correct place for this, but I'll put it here and someone can move it if they want. I use xfce and one thing I miss about Nautilus (possibly the only thing I miss) is the audio preview when mousing over a tune. Don't get excited, I haven't done it. Instead, this is a quick and dirty package the will open a tiny window when you double click with just one button on it - "Stop" and, provided you set up the Thunar custom action will play the tune. Click "Stop" and it goes away. I did it to avoid having to open a full media player just to quickly listen to a tune. The stop button appears under the mouse, so you don't even need to move it.

To set it up, create a file at /usr/share/pythonmpg123/project2.glade (I'm not very imaginitive with some filenames wink )and paste the following into it:

<?xml version="1.0" standalone="no"?> <!--*- mode: xml -*-->
<!DOCTYPE glade-interface SYSTEM "http://glade.gnome.org/glade-2.0.dtd">

<glade-interface>

<widget class="GtkWindow" id="window1">
  <property name="width_request">83</property>
  <property name="height_request">32</property>
  <property name="visible">True</property>
  <property name="title" translatable="yes">Mpg123 Player</property>
  <property name="type">GTK_WINDOW_TOPLEVEL</property>
  <property name="window_position">GTK_WIN_POS_MOUSE</property>
  <property name="modal">False</property>
  <property name="resizable">False</property>
  <property name="destroy_with_parent">False</property>
  <property name="decorated">True</property>
  <property name="skip_taskbar_hint">False</property>
  <property name="skip_pager_hint">False</property>
  <property name="type_hint">GDK_WINDOW_TYPE_HINT_NORMAL</property>
  <property name="gravity">GDK_GRAVITY_NORTH_WEST</property>
  <property name="focus_on_map">True</property>
  <property name="urgency_hint">False</property>

  <child>
    <widget class="GtkHBox" id="hbox1">
      <property name="visible">True</property>
      <property name="homogeneous">False</property>
      <property name="spacing">0</property>

      <child>
	<widget class="GtkButton" id="button2">
	  <property name="visible">True</property>
	  <property name="can_focus">True</property>
	  <property name="label" translatable="yes">Stop</property>
	  <property name="use_underline">True</property>
	  <property name="relief">GTK_RELIEF_NORMAL</property>
	  <property name="focus_on_click">True</property>
	  <signal name="clicked" handler="on_button2_clicked" last_modification_time="Tue, 22 May 2012 18:00:48 GMT"/>
	</widget>
	<packing>
	  <property name="padding">0</property>
	  <property name="expand">True</property>
	  <property name="fill">True</property>
	</packing>
      </child>
    </widget>
  </child>
</widget>

</glade-interface>

Then the main script (which you can put where you want) - I call it mp123.py

#!/usr/bin/env python

import sys
import os
import argparse
try:
	import pygtk
	pygtk.require("2.0")
except:
	pass
try:
	import gtk
	import gtk.glade
except:
	sys.exit(1)

playing = 0
filename = ""

class PlayTune:
	def __init__(self):
		global playing
		if playing == 0:
			command = 'mpg123 "'+ns.filename+'" &'
			playing = 1
			os.system (command)
			return None
		else:
			command = "killall mpg123"
			playing = 0
			os.system (command)
			return None

		
	def run(self):
		os.system (command)
		return True
	
class PlayerWindow:
	"""This is an mpg123 player application"""

	def __init__(self):
			
		#Set the Glade file
		self.gladefile = "/usr/share/pythonmpg123/project2.glade"
		self.wTree = gtk.glade.XML(self.gladefile) 
		
		#Get the Main Window, and connect the "destroy" event
		self.window = self.wTree.get_widget("window1")
		if (self.window):
			self.window.connect("destroy", gtk.main_quit)
			
		dic = {
			"on_button2_clicked" : self.button2,
			
		}
		self.wTree.signal_autoconnect(dic)
					
	def button2(self,widget):
		playing = PlayTune()
		gtk.main_quit()


if __name__ == "__main__":
	parser = argparse.ArgumentParser(add_help=False)
	parser.add_argument('-t', dest="filename")
	ns = parser.parse_args()
	print ns.filename
	pw = PlayerWindow()
	playing = PlayTune()
	gtk.main()

To use with thunar you may need to set up a separate script to call it (I couldn't get it working directly)

playtune.sh

#!/bin/bash

IFS="
"

python2.7 /path/to/mp123.py -t "$1"

Change the path accordingly. Finally, set up a custom action in thunar with the command:

sh /path/to/playtune.sh %f

Or, right click an mp3, Open With, Custom command and enter

sh /path/to/playtune.sh

Last edited by Roken (2012-06-05 23:37:30)


Ryzen 5900X 12 core/24 thread - RTX 3090 FE 24 Gb, Asus Prime B450 Plus, 32Gb Corsair DDR4, Cooler Master N300 chassis, 5 HD (1 NvME PCI, 4SSD) + 1 x optical.
Linux user #545703

/ is the root of all problems.

Offline

#1820 2012-06-05 22:04:32

owain
Member
Registered: 2009-08-24
Posts: 251

Re: Post your handy self made command line utilities

I know there's a million solutions to this already, but here's a crude Pacman update checker, to be called by a cron job at a frequency of one's choosing:

#!/bin/bash
export DISPLAY=:0
MESSAGE="`sudo pacman -Syuw --noprogressbar --noconfirm | grep Targets | cut -d ' ' -f 3- | tr -s ' ' '\n' | head -n 20 `" # The list of packages is limited to the first 20, feel free to change this.

if [[ "$MESSAGE" != "" ]]; then
    notify-send [--icon /path/to/icon/of/your/choice] "Updates available" "$MESSAGE"
fi

Having to add 'sudo pacman -Syuw --noprogressbar --noconfirm' as a no-password entry in the sudoers file might not not be to everyone's preference, but it suits me OK.

Last edited by owain (2012-06-05 22:05:17)

Offline

#1821 2012-06-05 22:11:27

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 30,424
Website

Re: Post your handy self made command line utilities

owain wrote:

I know there's a million solutions to this already, but here's a crude Pacman update checker, to be called by a cron job at a frequency of one's choosing...

Checkout keenerd's checkupdates http://www.mail-archive.com/pacman-dev@ … 08420.html


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#1822 2012-06-05 22:30:16

owain
Member
Registered: 2009-08-24
Posts: 251

Re: Post your handy self made command line utilities

jasonwryan wrote:

Again, it's not to everyone's preference, but as I've not got the fastest connection I'd rather get the notification after the new packages are downloaded, hence using -Syuw.

Offline

#1823 2012-06-08 02:19:05

Piki
Member
From: Cyberspace
Registered: 2012-03-13
Posts: 12

Re: Post your handy self made command line utilities

This is an alternate version of my previous iptables script. Instead if answering yes or no AFTER running the script, you can edit this one to set the variables directly to enable the ports you need. This one's good for emailing to yourself or uploading to your Dropbox/Google Drive/etc. for a quick and easy way to set the same rules on all your computers, or for in case you need to reinstall.

#!/bin/bash
# To enable any of the following, set it to equal either y or yes (lower case)
# See the comments at the end of this script to see descriptions of each of the following
dns=yes
ping=no
http=yes
https=yes
http_alt=no
ntp=yes
imap=no
imaps=no
pop3=no
pop3s=no
# Some ISPs block normal smtp. If you enable this and can't use normal smtp,
# try it via smtps or smtps_alt (check the descriptions at the end of this script to see
# which ports they use)
smtp=no
smtps=no
smtps_alt=no
aim_icq=no
msn_wlm=no
irc=no
irc_ssl=no
xmpp=no
xmpp_alt=no
ssh_out=yes
ssh_in=no
torrent=no
torrent_extra=no

echo
echo "If this script fails to work correctly, make sure you are either logged in as root, or"
echo "running it via sudo. Additionally, make sure you're distros iptables command is installed."

echo
echo "Additionally, you may wish to edit this script to enable additional ports. You may do so by"
echo "changing the answers to what you need from \'no\' to \'yes\'. You may also add more ports manually."
echo "This script will now pause for 5 seconds to give you a chance to cancel and add more ports."

sleep 5

echo
echo "Clearing all existing iptables rules..."
iptables -F OUTPUT
iptables -F INPUT
iptables -F FORWARD
iptables -F -t nat
iptables -F
iptables -X -t nat
iptables -X
iptables -Z OUTPUT
iptables -Z INPUT
iptables -Z FORWARD
iptables -Z -t nat
iptables -Z

echo
echo "Drop all communication, unless explicitly allowed..."
iptables -P OUTPUT DROP
iptables -P INPUT DROP
iptables -P FORWARD DROP

echo
echo "Automtically drop invalid packets..."
iptables -A OUTPUT -p ALL -m state --state INVALID -j DROP
iptables -A INPUT -p ALL -m state --state INVALID -j DROP
iptables -A FORWARD -p ALL -m state --state INVALID -j DROP

echo
echo "Allow unlimited communications on loopback (needed for some local applications)..."
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT

if [ "$dns" == "y" -o "$dns" == "yes" ]; then
echo
echo "Allowing port 53 for DNS lookups..."
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 53 -j ACCEPT
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT -p udp -m state --state ESTABLISHED,RELATED --sport 53 -j ACCEPT
fi

if [ "$ping" == "y" -o "$ping" == "yes" ]; then
echo
echo "Allow outgoing ping requests..."
iptables -A OUTPUT -p icmp --icmp-type 8 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type 0 -m state --state ESTABLISHED,RELATED -j ACCEPT
fi

if [ "$http" == "y" -o "$http" == "yes" ]; then
echo
echo "Allowing port 80 for web browsing..."
iptables -A OUTPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 80 -j ACCEPT
fi

if [ "$https" == "y" -o "$https" == "yes" ]; then
echo
echo "Allowing port 443 for secure web browsing..."
iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 443 -j ACCEPT
fi

if [ "$http_alt" == "y" -o "$http_alt" == "yes" ]; then
echo
echo "Allowing alternate port 8080 for web browsing..."
iptables -A OUTPUT -p tcp --dport 8080 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 8080 -j ACCEPT
fi

if [ "$ntp" == "y" -o "$ntp" == "yes" ]; then
echo
echo "Allowing port 123 for NTP..."
iptables -A OUTPUT -p udp --dport 123 -j ACCEPT
iptables -A INPUT -p udp -m state --state ESTABLISHED,RELATED --sport 123 -j ACCEPT
fi

if [ "$imap" == "y" -o "$imap" == "yes" ]; then
echo
echo "Allowing port 143 for IMAP access..."
iptables -A OUTPUT -p tcp --dport 143 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 143 -j ACCEPT
fi

if [ "$imaps" == "y" -o "$imaps" == "yes" ]; then
echo
echo "Allowing port 993 for secure IMAP access..."
iptables -A OUTPUT -p tcp --dport 993 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 993 -j ACCEPT
fi

if [ "$smtp" == "y" -o "$smtp" == "yes" ]; then
echo
echo "Allowing port 25 for SMTP access..."
iptables -A OUTPUT -p tcp --dport 25 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 25 -j ACCEPT
fi

if [ "$smtps" == "y" -o "$smtps" == "yes" ]; then
echo
echo "Allowing port 587 for secure SMTP access..."
iptables -A OUTPUT -p tcp --dport 587 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 587 -j ACCEPT
fi

if [ "$smtps_alt" == "y" -o "$smtps_alt" == "yes" ]; then
echo
echo "Allowing alternate port 465 for (secure) SMTP access..."
iptables -A OUTPUT -p tcp --dport 465 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 465 -j ACCEPT
fi

if [ "$aim_icq" == "y" -o "$aim_icq" == "yes" ]; then
echo
echo "Allowing port 5190 for AIM and ICQ access..."
iptables -A OUTPUT -p tcp --dport 5190 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 5190 -j ACCEPT
iptables -A OUTPUT -p udp --dport 5190 -j ACCEPT
iptables -A INPUT -p udp -m state --state ESTABLISHED,RELATED --sport 5190 -j ACCEPT
fi

if [ "$irc" == "y" -o "$irc" == "yes" ]; then
echo
echo "Allowing port 1863 for MSN/Windows Live Messnger access..."
iptables -A OUTPUT -p tcp --dport 1863 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 1863
fi

if [ "$irc" == "y" -o "$irc" == "yes" ]; then
echo
echo "Allowing port 6667 for IRC access..."
iptables -A OUTPUT -p tcp --dport 6667 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 6667
fi

if [ "$irc_ssl" == "y" -o "$irc_ssl" == "yes" ]; then
echo
echo "Allowing port 6697 for secure IRC access..."
iptables -A OUTPUT -p tcp --dport 6697 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 6697
fi

if [ "$xmpp" == "y" -o "$xmpp" == "yes" ]; then
echo
echo "Allowing port 5222 for Jabber/XMPP access..."
iptables -A OUTPUT -p tcp --dport 5222 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 5222 -j ACCEPT
fi

if [ "$xmpp_alt" == "y" -o "$xmpp_alt" == "yes" ]; then
echo
echo "Allowing alternative port 5223 for Jabber/XMPP access..."
iptables -A OUTPUT -p tcp --dport 5223 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 5223 -j ACCEPT
fi

if [ "$ssh" == "y" -o "$ssh" == "yes" ]; then
echo
echo "Allowing port 22 for outgoing ssh access..."
iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 22 -j ACCEPT
fi

if [ "$ssh" == "y" -o "$ssh" == "yes" ]; then
echo
echo "Allowing port 22 for incoming ssh access..."
iptables -A OUTPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
fi

if [ "$torrent" == "y" -o "$torrent" == "yes" ]; then
echo
echo "Allowing ports 6881 through 6887 for BitTorrent..."
iptables -A OUTPUT -p tcp --dport 6881:6887 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 6881:6887 -j ACCEPT
iptables -A OUTPUT -p udp --dport 6881:6887 -j ACCEPT
iptables -A INPUT -p udp -m state --state ESTABLISHED,RELATED --sport 6881:6887 -j ACCEPT
fi

if [ "$torrent_extra" == "y" -o "$torrent_extra" == "yes" ]; then
echo
echo "Allowing extra ports 6888 through 6999 for BitTorrent access..."
iptables -A OUTPUT -p tcp --dport 6888:6999 -j ACCEPT
iptables -A INPUT -p tcp -m state --state ESTABLISHED,RELATED --sport 6888:6999 -j ACCEPT
iptables -A OUTPUT -p udp --dport 6888:6999 -j ACCEPT
iptables -A INPUT -p udp -m state --state ESTABLISHED,RELATED --sport 6888:6999 -j ACCEPT
fi

echo
echo
echo "DONE!"

echo
echo
echo "If it didn't work, double check that you are logged in as root, or using sudo."
echo "Also make sure iptables is installed. Some distros don't install it by default."

echo
echo
echo "Just a reminder that if you need more ports, you can edit this script in your"
echo "favorite text editor to add them, using the other lines as an example."
echo "Alternatively, you may manually run the iptables commands."


# dns:
    # look up remote servers when you type in a domain (e.g. www.example.com)
    # port 53, TCP and UDP
# ping:
    # no port, ICMP
# http:
    # normal web browsing
    # port 80, TCP
# https:
    # secure web browsing
    # port 443, TCP
# http_alt:
    # alternate browsing port, most sites don't use it
    # 8080
# ntp:
    # Network Time Protocol (sync your computer's clock)
    # port 123, UDP
# imap:
    # check your mail on another server
    # port 143, TCP
# imaps:
    # secure checking of your mail on another server
    # port 993, TCP
# pop3:
    # download your mail from another server
    # port 110, TCP
# pop3s:
    # securely download your mail from another server
    # port 995, TCP
# smtp:
    # send mail via another server, this one is sometimes blocked by ISPs
    # port 25, TCP
# smtps:
    # securely send mail via another server
    # port 587, TCP
# smtps_alt:
    # securely send mail via another server
    # port 465, TCP
# aim_icq:
    # AOL Instant Messenger and/or ICQ ("I seek you") chat
    # port 5190, TCP and UDP
# msn_wlm:
    # MSN/Windows Live Messenger
    # port 1863, TCP (also needs http and https enabled)
# irc:
    # Internet Relay Chat (low-bandwidth chat room service)
    # 6667, TCP
# irc_ssl:
    # more secure (maybe) version of IRC
    # 6697
# xmpp:
    # chat protocol, sometimes called Jabber, used by GTalk
    # port 5222, TCP
# xmpp_alt:
    # XMPP/Jabber through a different port, this one is rarely used
    # 5223, TCP
# ssh_out:
    # connect securely to a "shell" (command line) on another computer
    # port 22, TCP
# ssh_in:
    # allow others to connect securely to this computer's "shell" (command line)
    # port 22, TCP
# torrent:
    # BitTorrent (peer-to-peer file sharing)
    # ports 6881-6887, TCP and UDP
# torrent_extra:
    # sometimes used as extra ports for BitTorrent
    # ports 6888-6999, TCP and UDP

--
Piki
"Many people have died for their beliefs. The real courage is in living and suffering for what you believe in." Brom, character in 'Eragon' by Christopher Paolini

Offline

#1824 2012-06-08 12:35:22

bloom
Member
Registered: 2010-08-18
Posts: 749
Website

Re: Post your handy self made command line utilities

I couldn't play APE files correctly with ncmpcpp, so I made an APE to FLAC converter which applies APE metadata to the FLAC output.

#! /bin/dash

green_echo() {
    if [ -t 1 ] ; then
        printf "\033[1;32m%s\033[0m\n" "$@"
    else
        echo "$@"
    fi
}

get_tag() {
    tag=$1
    file=$2
    mediainfo "--Inform=General;%$tag%" "$file"
}

set_tag() {
    key=$1
    value=$2
    file=$3
    [ -n "$value" ] && metaflac --set-tag=$key="$value" "$file"
}

convert_tags() {
    apefile=$1
    flacfile=$2
    artist=$(get_tag "Artist" "$apefile")
    albper=$(get_tag "Album/Performer" "$apefile")
    performer=$(get_tag "Performer" "$apefile")
    composer=$(get_tag "Composer" "$apefile")
    album=$(get_tag "Album" "$apefile")
    title=$(get_tag "Title" "$apefile")
    year=$(get_tag "Recorded_Date" "$apefile")
    genre=$(get_tag "Genre" "$apefile")
    tracknum=$(get_tag "Track/Position" "$apefile")
    discnum=$(get_tag "Part" "$apefile")
    comment=$(get_tag "Comment" "$apefile")
    set_tag ARTIST "$artist" "$flacfile"
    set_tag ALBUMARTIST "$albper" "$flacfile"
    set_tag PERFORMER "$performer" "$flacfile"
    set_tag COMPOSER "$composer" "$flacfile"
    set_tag ALBUM "$album" "$flacfile"
    set_tag TITLE "$title" "$flacfile"
    set_tag DATE "$year" "$flacfile"
    set_tag GENRE "$genre" "$flacfile"
    set_tag TRACKNUMBER "$tracknum" "$flacfile"
    set_tag DISCNUMBER "$discnum" "$flacfile"
    set_tag COMMENT "$comment" "$flacfile"
}

while [ $# -gt 0 ] ; do
    apefile=$1
    flacfile="${apefile%.*}.flac"
    wavfile="${apefile%.*}.wav"
    green_echo "$apefile"
    echo "APE --> WAV"
    mac "$apefile" "$wavfile" -d
    echo "WAV --> FLAC"
    flac --best -f -o "$flacfile" "$wavfile"
    convert_tags "$apefile" "$flacfile"
    shift
done

Usage:

ape2flac *.ape

gh · da · ds

Offline

#1825 2012-06-09 16:02:09

ArchLinux
Member
Registered: 2012-06-09
Posts: 15

Re: Post your handy self made command line utilities

I wrote this small program to update the dwm status bar. It works well, although I'm not fully satisfied with the way of retrieving the volume level.

dstatus.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

static char *gettime(const char *format)
{
	static char timestr[60];
	time_t rawtime;
	struct tm *timeinfo;

	time(&rawtime);
	timeinfo = localtime(&rawtime);

	strftime(timestr, sizeof(timestr), format, timeinfo);

	return timestr;
}

static char *getvol()
{
	static char volstr[60];
	FILE *output;
	char *tmp, *start, *end;
	int len;
	
	output = popen("amixer get Master | grep 'Left:'", "r");
	if (output == NULL)
		return NULL;

	if (fgets(volstr, sizeof(volstr), output) == NULL) {
		pclose(output);
		return NULL;
	}
	pclose(output);

	tmp = memchr(volstr, '\n', sizeof(volstr));
	if (tmp != NULL)
		*tmp = 0;

	if (strstr(volstr, "off") == NULL) {
		len = strlen(volstr);
		start = memchr(volstr, '[', len) + 1;
		end = memchr(volstr, ']', len);
		*end = 0;
		memmove(volstr, start, ++end - start);
	} else {
		strcpy(volstr, "Mute");
	}

	return volstr;
}

static void updatestatus()
{
	char buf[150];

	snprintf(buf, sizeof(buf), "xsetroot -name \"%s | Vol %s\"",
			gettime("%A %d %B %H:%M"), getvol());
	system(buf);
}

static void usage()
{
	fprintf(stderr, "usage: dstatus [volup|voldown|volmute|voltoggle]\n");
	exit(EXIT_FAILURE);
}

int main(int argc, char *argv[])
{
	if (argc > 2) {
		usage();
	} else if (argc == 2) {
		if (!strcmp(argv[1], "volup"))
			system("amixer set Master 2+ unmute > /dev/null");
		else if (!strcmp(argv[1], "voldown"))
			system("amixer set Master 2- unmute > /dev/null");
		else if (!strcmp(argv[1], "volmute"))
			system("amixer set Master mute > /dev/null");
		else if (!strcmp(argv[1], "voltoggle"))
			system("amixer set Master toggle > /dev/null");
		else
			usage();
	}
	updatestatus();

	return 0;
}

Offline

Board footer

Powered by FluxBB