You are not logged in.

#1826 2012-06-09 16:30:14

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

Re: Post your handy self made command line utilities

@ArchLinux
Here is status bar I wrote for Pandora, it gets the volume level directly from alsa, so you might be interested.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <alsa/asoundlib.h>

#define whitespace() printf(" ")
#define eol()        printf("\n")
#define VOL_FG  "#04C656"
#define VOL_BG  "#363636"
#define TIME_FG "#44DDFF"

#define BAT_ROOT     "/sys/class/power_supply/bq27500-0"
#define BAT_CHARGE   "capacity"
#define BAT_STATE    "status"

#define BAT_CHARGING "#FEA63C"
#define BAT_GOOD     VOL_FG
#define BAT_AVEG     TIME_FG
#define BAT_BAD      "#FF6600"
#define BAT_BG       VOL_BG

#define batcmp(x,y) memcmp(x, y, strlen(y))

#define SLEEP_INTERVAL 1000 /* ms */

snd_mixer_t* alsainit(const char *card)
{
   snd_mixer_t *handle;
   snd_mixer_open(&handle, 0);
   snd_mixer_attach(handle, card);
   snd_mixer_selem_register(handle, NULL, NULL);
   snd_mixer_load(handle);
   return handle;
}

void alsaclose(snd_mixer_t *handle)
{
   snd_mixer_close(handle);
}

snd_mixer_elem_t* alsamixer(snd_mixer_t *handle, const char *mixer)
{
   snd_mixer_selem_id_t *sid;
   snd_mixer_selem_id_alloca(&sid);
   snd_mixer_selem_id_set_index(sid, 0);
   snd_mixer_selem_id_set_name(sid, mixer);
   return snd_mixer_find_selem(handle, sid);
}

int getvolume(snd_mixer_elem_t *mixer)
{
   long volume, min, max;
   int percent;
   snd_mixer_selem_get_playback_volume_range(mixer, &min, &max);
   snd_mixer_selem_get_playback_volume(mixer, SND_MIXER_SCHN_MONO, &volume);
   return volume>min?volume<max?(volume*100)/max:100:0;
}

void die(const char *errstr, ...) {
   va_list ap;
   va_start(ap, errstr); vfprintf(stderr, errstr, ap); va_end(ap);
   exit(EXIT_FAILURE);
}

int batterystate(char *buffer)
{
   FILE *f;
   if (!(f = fopen(BAT_ROOT"/"BAT_STATE, "r")))
      return 0;
   fgets(buffer, 12, f); fclose(f);
   return 1;
}

int batterycharge(int *charge)
{
   FILE *f; char buffer[5]; *charge = 0;
   if (!(f = fopen(BAT_ROOT"/"BAT_CHARGE, "r")))
      return 0;
   fgets(buffer, 4, f);
   *charge = strtol(buffer, (char **) NULL, 10);
   fclose(f);
   return 1;
}

void gdbar(char *buffer, int perc, char *fg, char *bg, int w, int h)
{
   int fill, unfill;
   fill   = (perc*w)/100;
   unfill = w - fill;
   snprintf(buffer, 255, "^fg(%s)^r(%dx%d)^fg(%s)^r(%dx%d)^fg()", fg, fill, h, bg, unfill, h);
}

void printvolume(snd_mixer_elem_t *mixer) {
   char buffer[256]; int volume;
   volume = getvolume(mixer);
   gdbar(buffer, volume, VOL_FG, VOL_BG, 35, 9);
   printf("VOL %s %3d%%", buffer, volume);
}

void printbattery() {
   char state[13], buffer[256], *color; int charge;
   if (!batterystate(state) || !batterycharge(&charge)) {
      printf("ERROR");
      return;
   }
   if (!batcmp(state, "Charging"))  color = BAT_CHARGING;
   else if (charge > 65)            color = BAT_GOOD;
   else if (charge > 25)            color = BAT_AVEG;
   else                             color = BAT_BAD;
   gdbar(buffer, charge, color, BAT_BG, 35, 9);
   printf("%s %s %3d%%", !batcmp(state, "Charging")?"CHR":"BAT", buffer, charge);
}

void printdate() {
   char buffer[51]; time_t rawtime; struct tm *timeinfo;
   time(&rawtime);
   timeinfo = localtime(&rawtime);
   strftime(buffer, 50, "^fg()%a %d/%m ^fg("TIME_FG")%H:%M", timeinfo);
   printf(buffer);
}

int main(int argc, char **argv)
{
   snd_mixer_t *alsa; snd_mixer_elem_t *mixer;

   /* init alsa */
   if (!(alsa = alsainit("default")))
      die("Could not init ALSA (%s)\n", "default");
   /* get mixer */
   if (!(mixer = alsamixer(alsa, "Master")))
      die("Could not get mixer (%s)\n", "Master");

   /* statusbar itself (pipe to dzen) */
   while (1) {
      printvolume(mixer);
      whitespace();
      printbattery();
      whitespace();
      printdate();
      whitespace();
      eol();
      fflush(stdout);
      snd_mixer_wait(alsa, SLEEP_INTERVAL);
      snd_mixer_handle_events(alsa);
   }

   /* close alsa */
   alsaclose(alsa);
   return EXIT_SUCCESS;
}

It blocks for 1 second to wait alsa events, the plus side of this over regular bash script is that it has less overhead and the volume change effect is instant.

Last edited by Cloudef (2012-06-09 16:34:13)

Offline

#1827 2012-06-09 17:07:13

Stebalien
Member
Registered: 2010-04-27
Posts: 1,227
Website

Re: Post your handy self made command line utilities

Yet another todo manager.

#!/bin/bash
FILE=~/Documents/todo.txt
CMD=${1:-ls}

shift
case $CMD in
    l|ls) [[ -e $FILE ]] && awk -v pat="$*" 'BEGIN {IGNORECASE=1}; $0 ~ pat { printf("% 2d. %s\n", NR, $0) }' $FILE ;;
    r|rm) sed "$(printf '%sd;' $@)" -i "$FILE" ;;
    a|add)
        if [[ $# -eq 0 ]]; then
            while read line; do
                echo "$line" >> $FILE
            done
        else
            echo "$*" >> $FILE
        fi
        ;;
    h|help)
        echo "Usage: $0 ls [pattern] | rm NUM [NUM...] | add [TEXT]
Commands:
 l,ls  - list todos (default)
 r,rm  - remove a space separated list of todos
 a,add - add the remaining arguments as a todo or a list of todos from stdin"
    ;;
    *)
        echo "$0: invalid command -- '$CMD'"
        echo "Try '$0 help' for more information."
        ;;
esac

Steven [ web : git ]
GPG:  327B 20CE 21EA 68CF A7748675 7C92 3221 5899 410C
Do not email: honeypot@stebalien.com

Offline

#1828 2012-06-09 19:32:53

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

Re: Post your handy self made command line utilities

@Cloudef: Thanks! I will take a look at it as soon as I've time. Before I wrote the program, I knew the possibility to directly call the alsa functions, but I thought it would be too much work for such a simple task.

But with your program, if it blocks for one second, it may be a problem in my case, because I've made dwm to increase/decrease volume level (by executing 'dstatus volup/voldown') when I scroll up/down on the status bar.

Offline

#1829 2012-06-09 19:54:46

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

Re: Post your handy self made command line utilities

ArchLinux wrote:

But with your program, if it blocks for one second, it may be a problem in my case, because I've made dwm to increase/decrease volume level (by executing 'dstatus volup/voldown') when I scroll up/down on the status bar.

The blocking time is configurable, also it stops blocking instantly when alsa event is received as well.

Offline

#1830 2012-06-09 20:05:28

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

Re: Post your handy self made command line utilities

Okay, good to know. I will take a closer look next week.

Offline

#1831 2012-06-10 20:20:47

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

Re: Post your handy self made command line utilities

a script to create .mount and .automount (unit)files for local fs and install them.
usefull if you have a number of partitions to automount.
http://pastebin.ca/2160093

Offline

#1832 2012-06-11 16:35:04

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

Re: Post your handy self made command line utilities

@Cloudef: I've just changed my program with parts of your code, and I've added a few lines to make it show whether or not the volume is muted. Although there is no visible change, I like the new version better. Thanks for sharing your code!

Offline

#1833 2012-06-12 11:19:44

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

Re: Post your handy self made command line utilities

I wanted a way to find all the wallpaper images I have saved to various directories in my file system so I wrote this:

https://github.com/mfs/mfs-utils/blob/m … ind-images

It recursively searches a given directory and prints out the filenames of images greater than a certain size (800 x 600 by default).

PIL doesn't seem quite ready for Python 3 so this application parses the image headers itself.

Offline

#1834 2012-06-13 13:16:08

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

Re: Post your handy self made command line utilities

Script to find and play music files. This one's inspired by the mpg123 script by Roken, but its more flexible.
It uses find, results are all files containing you search word. They are presented as a numbered list and you can choose multiple files for playback or choose to research. A sane playlist is also printed.

#!/bin/bash

trap "echo && exit 0" SIGINT

export mlibrary='/media/Entertainment/songs/'

pretty_print () {
local count=1
echo -e "\nPLAYLIST"
echo "-------------------------------------------------------------------"
for pl in "$@"; do
echo -e "$count . $pl"
count=$((count+1))
done
echo -e "\nKeycontrols:: s:pause, f:next, b:prev, ',':rewind '.':fast forward, q:quit\n"

}

play_tracks() {

IFS=" "
fplay=($1)

for i in ${fplay[@]}; do
[ $i -gt ${#sfiles[@]} ] && { echo "Wrong input." && exit 1; }
playfiles+=("${sfiles[$(($i-1))]}")
done

pretty_print "${playfiles[@]##*/}"
mpg123 -C "${playfiles[@]}"
exit 0

}

find_tracks() {

read -p "Track name: " track

IFS='
'
sfiles=(`find ${mlibrary} -depth -iname "*$track*"`)

if [ ${#sfiles[@]} -ne 0 ]; then
 echo
 for t in `seq 1 ${#sfiles[@]}`; do
  index=$(( $t-1 ))
  echo "$t==> ${sfiles[$index]##*/}"
 done
 echo
 read -p "Enter track no/s.(space separated; r to research) :" play
else
 read -p "No matching tracks. Search again?: (y/n)" redo
fi

[ "$redo" = 'n' ] && exit 2

if [ "$play" = 'r' -o "$redo" = 'y' ]; then
  { unset -v redo && find_tracks; }
else
  play_tracks "$play"
fi

}

find_tracks

Last edited by debdj (2012-06-14 03:34:15)

Offline

#1835 2012-06-24 00:20:52

ElderSnake
Member
From: Australia
Registered: 2010-12-09
Posts: 93

Re: Post your handy self made command line utilities

Not a great bash person here and tend to either improvise or take code from existing scripts and make them work so I expect I'm probably not doing this as efficiently as I could, maybe, but I made this script for my home file share server to check at certain times (via Cron job) if Transmission-Daemon, via Transmission-Remote, is downloading or doing any activity and if not, suspend the machine. 

#!/bin/bash
#
# Script to check the output of Transmission Remote and if no activity, signal the machine to suspend 

# variables

user="<username>"
#password="<password>"
query="seeding\|down\|idle"

OUTPUT=`transmission-remote -n $user -l | cut -c58-66 |grep -i $query | wc -l`

command="/usr/sbin/pm-suspend"

#actual commands

if [ $OUTPUT != 0 ]; then
  echo "Looks like we have downloads, no suspending ;)"

else
  echo "No downloads active, system going to suspend.."
  exec $command
fi

Last edited by ElderSnake (2012-06-24 00:23:23)


Arch Linux - Intel E5200 Desktop (Cinnamon 2.0) - Debian Testing - Netbook EeePC AMD C-50 (Xfce)

Offline

#1836 2012-06-24 08:21:45

ZekeSulastin
Member
Registered: 2010-09-20
Posts: 266

Re: Post your handy self made command line utilities

I'm also pretty new to actual useful scripting; in this case, I found that the current available udisks1 helper functions were lacking for my needs - I wanted something I could simply and quickly invoke from a command line to mount, unmount, eject, and check the mount status of all removable devices.  Thankfully, my system is fairly simple udisks-wise - the one optical drive is /dev/sr0, there are no floppy disks, and the card reader and usb drives all show up as /dev/sdxy.

My wrapper provides four functions, as described in the comments.  The spots to modify for your own system should are mainly the references to sr0 and the devices to ignore in [^ab].  It can't handle stuff like sdaa4 or sdv12, but for my system its perfect smile (also note that it doesn't parse ls or udisks --show-info, a pretty good thing imo if you look at the sort of functions bashmount needed to use to get its status ...)

#!/usr/bin/env bash

# Source this in your .bashrc!
# You can pass additional udisks1 options to everything except optical disk operations, ejection by
#	label, and ejection by partition.  Write them yourself if you need them >.>

# udl - udisks-list
# Lists available non-fixed drives; set the appropriate ignored devices for your system in [^ab]
# Returns a list in the following format:
#
# xy: Label (Mount status)
# 
# i.e.
#
# cd: OFFICE12			Optical drive w/ disk label OFFICE12, not mounted
# d1: ZSCruzer (M)		Partition /dev/sdd1 w/ partition label ZSCruzer, mounted
udl () {
	local _parsed=( )
	for _symlink in "/dev/disk/by-label/*"; do
		_device=$(readlink "${_symlink}" | cut -b 7-10)
   		[[ $_device =~ sr ]] && _trimdev="cd" || _trimdev="$(echo "$_device" | cut -b 3-4)"
		_label="${_symlink##*/}"
		[[ -d "/media/$_label" ]] && _mounted=" (M)" || _mounted=""
		[[ $_device =~ s[r0]|d[^ab] ]] && _parsed+=("$_trimdev: $_label$_mounted")
	done
	[[ $_parsed == "" ]] && echo "No removable devices found." || printf "%s\n" "${_parsed[@]}"
}

# udm - udisks-mount
# Mounts a drive, given "cd" for the optical drive, "d1" or similar for a block device,
# 	or the partition label.
udm () {
	if [[ $1 == "cd" ]]; then
		udisks --mount /dev/sr0;
	elif [[ $1 == ?? ]]; then
		udisks --mount /dev/sd$@;
	else
		udisks --mount /dev/disk/by-label/$@;
	fi
}

# udu - udisks-unmount
# Unmounts a drive, given "cd" for the optical drive, "d1" or similar for a block device,
#	or the partition label.
udu () {
	if [[ $1 == cd ]]; then
		udisks --unmount /dev/sr0;
	elif [[ $1 == ?? ]]; then
		udisks --unmount /dev/sd$@;
	else
		udisks --unmount /dev/disk/by-label/$@;
	fi
}

# ude - udisks-eject
# Fully ejects a drive, given "cd" for the optical drive, "d1" or similar for a block device,
#	"d" or similar for a block device, or the partition label.
#	All partitions must be unmounted or --eject will fail.
ude () {
	if [[ $1 == "cd" ]]; then
		udisks --eject /dev/sr0;
	elif [[ $1 == ?? ]]; then
		_part=$(echo $1 | cut -b 1)
		udisks --eject /dev/sd$_part;
	elif [[ $1 == ? ]]; then
		udisks --eject /dev/sd$@;
	else
		_device=$(readlink /dev/disk/by-label/$1 | cut -b 7-9)
		udisks --eject /dev/$_device;		
	fi
}

Last edited by ZekeSulastin (2012-06-24 08:22:48)

Offline

#1837 2012-06-29 03:12:59

n1x4
Member
From: Chernobyl
Registered: 2012-02-17
Posts: 149
Website

Re: Post your handy self made command line utilities

I wrote this a few days ago (it ain't much) to scale my laptops cpu frequency on the fly with cpufreq because I was having issues with it overheating during a large build. I added the script to /usr/bin and created an alias to call it. Anyway, I know this isn't much help to anyone 'out-of-the-box' but with a little adjusting it should work just fine.

t-cpu.png

#!/bin/bash
#Change cpu frequency by n1x4
#Add the module for your CPU below. ie. p4_clockmod, acpi_cpufreq, pcc_cpufreq, etc

MODULE='p4_clockmod'
sudo modprobe $MODULE

function cpufreq() {
        cpufreq-info | grep -E 'CPU frequency is'
}

case $1 in
     1)
       sudo cpufreq-set -c 0 -f 250Mhz
       echo -n -e "\e[0;5;34m$(cpufreq)\e[0m\n";;
     2)
       sudo cpufreq-set -c 0 -f 350Mhz
       echo -n -e "\e[0;5;34m$(cpufreq)\e[0m\n";;
     3)
       sudo cpufreq-set -c 0 -f 700Mhz
       echo -n -e "\e[0;5;34m$(cpufreq)\e[0m\n";;
     4)
       sudo cpufreq-set -c 0 -f 1.05Ghz
       echo -n -e "\e[0;5;34m$(cpufreq)\e[0m\n";;
     5)
       sudo cpufreq-set -c 0 -f 1.40Ghz
       echo -n -e "\e[0;5;34m$(cpufreq)\e[0m\n";;
     6)
       sudo cpufreq-set -c 0 -f 1.75Ghz
       echo -n -e "\e[0;5;34m$(cpufreq)\e[0m\n";;
     7)
       sudo cpufreq-set -c 0 -f 2.10Ghz
       echo -n -e "\e[0;5;34m$(cpufreq)\e[0m\n";;
     8)
       sudo cpufreq-set -c 0 -f 2.45Ghz
       echo -n -e "\e[0;5;34m$(cpufreq)\n\e[0m";;
    -h)
      echo -n -e "Usage: <script.sh> [1-8]\n\n\t\t1 = 350Mz\n\t\t2 = 700Mhz\n\t\t3 = 1.05Ghz\n\t\t4 = 1.40Ghz\n\t\t5 = 1.75Ghz\n\t\t6 = 2.10Ghz\n\t\t7 = 2.45Ghz\n\t\t8 = 2.80Ghz\n\nCPU frequency scaler by n1x4\n";;
     *)
       echo -n -e "\e[1;31mInvalid option\e[0m\n";;
esac

exit

||github||

Offline

#1838 2012-06-29 04:03:35

ShadowKyogre
Member
From: Hell! XP No... I'm not telling
Registered: 2008-12-19
Posts: 474
Website

Re: Post your handy self made command line utilities

Since I forget to update changelogs most of the time, I decided to write up a small script to help generate a changelog from my commits and the messages on them. Only has a single commandline option, which is to disable the dividers it makes for authors and commits for a given day if you're the only person on it. I should probably add a tag oriented mode where it groups things between git tags.Added tag oriented changelog. I could also probably toss out dateutil if I find out what git's usual date format is. Used git rev-list's --date=short option to simplify things.

#!/usr/bin/env python
import subprocess
import re
import sys
from datetime import datetime
from collections import OrderedDict as od
import argparse

commit_data=re.compile((r'commit[ ]*([0-9a-f]*)\n'
r'Author:[ ]*([^\n]*)\n'
r'Date:[ ]*([^\n]*)\n{2}'
r'([ ]+[^\n]*\n)*\n?'))
tag=re.compile(r'\(tag: ([^\)]*)\){1}')

def write_tagged_changelog(single_user=False, verbose=False):
	tags = subprocess.check_output(['git', 'log', '--simplify-by-decoration',
					 '--decorate', '--pretty=oneline'])
	tags = tags.decode(sys.getdefaultencoding())
	tags = tag.findall(tags)
	tags.reverse()
	log_by_tag=od([])
	for t in range(len(tags)-1,-1,-1):
		tag_to_write=tags[t]
		if t == 0:
			between = tags[t]
		else:
			between = "{}..{}".format(tags[t-1],tags[t])
		if verbose:
			sys.stderr.write('Getting commit data for tag range {}\n'.format(between))
		if tag_to_write not in log_by_tag.keys():
			log_by_tag[tag_to_write]={}
			if not single_user:
				log_by_tag[tag_to_write]['authors']=set([])
			log_by_tag[tag_to_write]['changes']=[]
			log_by_tag[tag_to_write]['firstd']=None
			log_by_tag[tag_to_write]['lastd']=None
		commits = subprocess.check_output(['git','log',
					'--pretty','--date=short',between])
		commits = commits.decode(sys.getdefaultencoding())
		for commit in commit_data.findall(commits):
			d = datetime.strptime(commit[2],'%Y-%m-%d').date()
			if log_by_tag[tag_to_write]['lastd'] is None:
				 log_by_tag[tag_to_write]['lastd'] = d
			if log_by_tag[tag_to_write]['firstd'] is None \
			or log_by_tag[tag_to_write]['firstd'] > d:
				 log_by_tag[tag_to_write]['firstd'] = d
			if not single_user:
				 log_by_tag[tag_to_write]['authors'].add(commit[1])
			changelog_entry = '\n'.join([l.strip() for l in commit[3].splitlines()])
			log_by_tag[tag_to_write]['changes'].append(changelog_entry)
		if verbose:
			sys.stderr.write('Got the following:\n')
			sys.stderr.write('{}\n'.format(log_by_tag[tag_to_write]))
	f=open('CHANGELOG.md','w')
	for key,item in log_by_tag.items():
		if verbose:
			sys.stderr.write('Writing changelog entry for {}\n'.format(key))
		f.write('{} ({} - {})\n====\n'.format(key,
			item['firstd'].strftime('%m/%d/%Y'),
			item['lastd'].strftime('%m/%d/%Y')))
		if not single_user:
			if verbose:
				sys.stderr.write('Writing authors\n')
			f.write("Authors\n")
			for a in item['authors']:
				f.write('* {}\n'.format(a))
			f.write("\nChanges\n")
		if verbose:
			sys.stderr.write('Writing changes\n')
		for c in item['changes']:
			f.write('* {}\n'.format(c))
		f.write('\n')
	f.close()

def write_changelog(single_user=False, verbose=False):
	commits = subprocess.check_output(['git','log',
					'--pretty','--date=short'])
	commits = commits.decode(sys.getdefaultencoding())

	log_by_date=od([])

	for commit in commit_data.findall(commits):
		date = datetime.strptime(commit[2],'%Y-%m-%d').date()
		if date not in log_by_date.keys():
			if verbose:
				sys.stderr.write('Establishing data cache for {}\n'.format(date))
			log_by_date[date]={}
			if not single_user:
				log_by_date[date]['authors'] = set([])
			log_by_date[date]['changes']=[]
		if not single_user:
			log_by_date[date]['authors'].add(commit[1])
		changelog_entry = '\n'.join([l.strip() for l in commit[3].splitlines()])
		log_by_date[date]['changes'].append(changelog_entry)

	f=open('CHANGELOG.md','w')
	for key,item in log_by_date.items():
		if verbose:
			sys.stderr.write('Writing changelog entry for {}\n'.format(key))
		f.write('{}\n====\n'.format(key.strftime('%m/%d/%Y')))
		if not single_user:
			if verbose:
				sys.stderr.write('Writing authors\n')
			f.write("Authors\n")
			for a in item['authors']:
				f.write('* {}\n'.format(a))
			f.write("\nChanges\n")
		if verbose:
			sys.stderr.write('Writing changes\n')
		for c in item['changes']:
			f.write('* {}\n'.format(c))
		f.write('\n')
	f.close()

if __name__ == "__main__":
	aparser = argparse.ArgumentParser(prog='gitrev2changelog',
					description="Generate a prettified changelog from one's git commits")
	aparser.add_argument('-t','--tagged',
			help="Output a tag oriented changelog",
			action='store_true',default=False)
	aparser.add_argument('-s','--single-user', 
			help='Turn off printing dividers for authors and changes',
			action='store_true',default=False)
	aparser.add_argument('-v','--verbose',
			help='Be noisy when generating the changelog',
			action='store_true',default=False)
	args = aparser.parse_args(sys.argv[1:])
	if args.tagged:
		write_tagged_changelog(args.single_user,args.verbose)
	else:
		write_changelog(args.single_user,args.verbose)

Last edited by ShadowKyogre (2012-06-29 05:22:04)


For every problem, there is a solution that is:
Clean
Simple and most of all...wrong!
Github page

Offline

#1839 2012-06-29 08:00:26

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

Re: Post your handy self made command line utilities

Since I had a Python training course last week, I decide to write some py scripts for proccesing MP3 files as exercise.

compressMP3_MP simply transcodes all multimedia files inside the current directory to 192kBit MP3 files. It spawns multiple concurrent encoding processes depending on how many CPUs/cores your system has. Currently the script does not delete the source file after encoding. Changing the tool chain used for encoding should be a big deal smile

Although MP3 encoding is not a big deal today where at least 2-4 CPU cores are common but the script might come handy if you have to batchcompress huge libraries of audio material to convert (e.g. FLAC library to MP3).

recurseM3U does a recursive search trough the directory tree below your current directory, cleans out old M3U playlists and generates new M3U playlists with a consistent name. I wrote the script to clean up the playlist mess in my huge audioplay collection where some audioplays had no playlist at all while others had two to three playlists in their folder. Also the names for the playlist were different. recurseM3U will not touch any of the MP3 files inside the structure. So it is pretty unlikely that bad things will happen to your collection. If you use another format to store your music / audioplay, then you will need to adjust the search pattern smile

I stored the scripts over at pastebin to not overload this thread too much.

compressMP3_MP:
http://pastebin.com/UZLLZx9n

recurseM3U:
http://pastebin.com/JWmez8RT

Those scripts work perfectly from the comandline but you may also attach them to custom actions inside your file manager (e.g. SpaceFM, Thunar).

Have fun,
-D$

Last edited by Darksoul71 (2012-06-29 08:01:03)


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

Offline

#1840 2012-07-01 18:25:45

mosquitogang201
Member
Registered: 2012-06-19
Posts: 33

Re: Post your handy self made command line utilities

This script is to help you clean up your computer by finding packages you no longer use or need.

#!/bin/bash

# This script is designed to help you clean your computer from unneeded packages. The script will find all packages that no other installed package depends on. It will output this list of packages excluding any you have placed in the ignore list. You may browse through the script's output and remove any packages you do not need.

# Enter packages and groups here which you know you wish to keep. They will not be included in the list of unrequired packages later.
ignorepkg="firefox skype spotify kgmailnotifier"
ignoregrp="base base-devel"

# Generate usable list of installed packages and packages you wish to keep.
for i in $ignorepkg; do
  ignore="$ignore $i"
done
ignore="$ignore $(pacman -Sg $ignoregrp | awk '{print $2}')"
installed=$(pacman -Qq)

# Check each installed package to see if it is required by anything.
for line in $installed; do
  check=$(pacman -Qi $line | awk '/Required By/ {print $4}')
  if [ "$check" == 'None' ]; then
    match=$(echo $ignore | grep $line)
    
    # Sometimes there may be more than one package containing the search string.
    j=0
    for k in $match; do
      if [ "$k" == "$line" ]; then
	j=1
      fi
    done
    
    # If package is not required by anything and is not on your list above of packages to ignore, print the package name to the screen.
    if [ "$j" -eq 0 ]; then
      echo $line;
    fi
  fi
done

Last edited by mosquitogang201 (2012-07-01 18:30:20)

Offline

#1841 2012-07-01 21:52:29

hesse
Member
Registered: 2011-12-08
Posts: 88

Re: Post your handy self made command line utilities

ArchLinux wrote:

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;
}

Is it faster to make the statusbar from a C program, rather than a bash-script?

Offline

#1842 2012-07-01 22:07:01

Trilby
Forum Moderator
From: Massachusetts, USA
Registered: 2011-11-29
Posts: 14,222
Website

Re: Post your handy self made command line utilities

I also have a c program to set my dwm status.  It uses at least and order of magnitude fewer resources (both memory and cpu) than a bash script.  I do not have it call xsetroot though - if you're writing it in C anyways, just have it set the root window name directly.  My version is up on github at the link to the left.

Last edited by Trilby (2012-07-01 22:07:35)


InterrobangSlider
• How's my coding? See this page.
• How's my moderating? Feel free to email any concerns, complaints, or objections.

Offline

#1843 2012-07-02 21:05:23

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

Re: Post your handy self made command line utilities

Relink broken symbolic links using regular expression.
Extra oomph if you install 'symlinks' from aur.

#!/bin/sh
# relink symbolic links
#
# provide regual expression to modify
# the current symlink path, and relink
# if regular expression affected the path.
#
# -q to silent 'no such symbolic link warnings'

usage() {
   echo "usage: $(basename $0) [-q] <regexp> <files>"
   exit 1
}

badregexp() {
   echo "^ invalid regular expression" 1>&2
   exit 1
}

main() {
   local quiet=0
   [[ -n "$1" ]] && [[ -n "$2" ]] || usage
   [[ "$1" == "-q" ]] && { quiet=1; shift 1; }
   echo -n "" | sed "$1" || badregexp
   local exp="$1"; shift 1
   while [[ -n "$1" ]]; do
      [[ -h "$1" ]] && {
         op="$(readlink "$1")"
         np="$(echo "$op" | sed "$exp")"
         [[ "$op" == "$np" ]] && { shift || break; continue; }
         ln -snf "$np" "$1" && echo "$1 -> $np"
      } || [[ -e "$1" ]] && {
         # skip normal files and directories
         foo=bar # avoid bash syntax error
      } || {
         [[ $quiet -eq 0 ]] && echo "$1: No such symbolic link" 1>&2
      }
      shift || break
   done
}
main "$@"

Stream nicovideo to mplayer

#!/bin/sh
# Streams the nicovideo to mplayer
# needs: nicovideo-dl, mplayer

_NICO_USER="<username>"
_NICO_PASS="<password>"
err() { echo "$@" 1>&2; exit 1; }

# password stuff
nicowrap() {
   nicovideo-dl        \
      -u "$_NICO_USER" \
      -p "$_NICO_PASS" $@
}

# logic
main() {
   [[ -n "$@" ]] || err "usage: $(basename $0) [url]"
   [[ -p /tmp/nicovideo.fifo ]] && rm /tmp/nicovideo.fifo
   mkfifo -m 666 /tmp/nicovideo.fifo
   nicowrap -g "$@" || return 1
   nicowrap -o /tmp/nicovideo.fifo "$@" &> /dev/null &
   mplayer -cache 300 /tmp/nicovideo.fifo
   test -z "`jobs -p`" || kill -9 `jobs -p` &> /dev/null
   rm /tmp/nicovideo.fifo &> /dev/null
}
main $@
exit $?

Offline

#1844 2012-07-07 16:34:19

n1x4
Member
From: Chernobyl
Registered: 2012-02-17
Posts: 149
Website

Re: Post your handy self made command line utilities

Too poor to afford an alarm clock, so I wrote this little script and applied it to mygtkmenu. Copied a few good 'wake-up' tunes to a dedicated folder.

#!/bin/bash

declare -rx mpg="/usr/bin/mpg123"
song_dir="/home/n1x4/music/alarm/*"
alarm=$1

if  test ! -x $mpg; then
    echo -e "$mpg is not available - aborting!"
    exit 192
fi

while [ ! "$(date +%H:%M)" = "$alarm" ];
do
    sleep 1s
done

echo -n -e "\n\n\n\n\n\n\n\n\n\n\n\t\t\t\e[1;5;31mWAKE UP YOU SON OF A BITCH!!!!\e[0m\n"
for song in $song_dir
do
    mpg123 $song 2&>/dev/null
done

exit

.menu snippet

submenu = Alarm
	    icon = false
	    
	    item = 8:00am
	    cmd = urxvt -e /home/n1x4/music/alarm/alarm.sh 08:00
	    icon = null
	    
	    item = 9:00am
	    cmd = urxvt -e /home/n1x4/music/alarm/alarm.sh 09:00
	    icon = null
	    
	    item = 9:30am
	    cmd = urxvt -e /home/n1x4/music/alarm/alarm.sh 09:30
	    icon = null
		SEPARATOR
	    item = Stop alarm
	    cmd = killall alarm.sh
	    icon = null

||github||

Offline

#1845 2012-07-09 00:32:36

kalio
Member
Registered: 2012-07-08
Posts: 7

Re: Post your handy self made command line utilities

Here's a really nice one-liner I've been using:

script -a /home/kalio/xsession.log -f -c startx

Run this instead of startx, and all output from the session will be appended to xsession.log. It's useful because the tty has a very small scrollback buffer. Great when debugging xorg or your window manager.

mosquitogang201 wrote:

This script is to help you clean up your computer by finding packages you no longer use or need.

#!/bin/bash

# This script is designed to help you clean your computer from unneeded packages. The script will find all packages that no other installed package depends on. It will output this list of packages excluding any you have placed in the ignore list. You may browse through the script's output and remove any packages you do not need.

. . .

I was able to get rid of 27 long-forgotten packages (weighing in at 1.2GB) with this script. I'll be keeping this around, very useful.

Last edited by kalio (2012-07-09 00:37:15)

Offline

#1846 2012-07-10 13:39:10

Pr0Wolf29
Member
Registered: 2012-03-30
Posts: 22

Re: Post your handy self made command line utilities

A simple shutdown menu I made. It's meant for awesome WM but it could be used for other things. I designed it to be ran by pressing Mod4 + Shift + S.

echo "Shutdown Menu 1.0"

if [ $# -eq 1 ]; #Evaluate if any arguments were entered
then
	if [ $1 == "--version" ]; #If the first argument was entered,
	then
		exit;
	fi
fi

echo -e "\n1. Shutdown"
echo "2. Reboot"
echo "3. Logout"
echo "4. Hibernate"
echo "5. Sleep"
echo "6. Cancel"

while true
do
	read inkey

	case "$inkey" in
	1)
		sudo shutdown -h now
		;;
	2)
		sudo shutdown -r now
		;;
	3)			
		if [ "$(pidof X)" ] 
		then
			# Process was found.
			killall X
		else
			# Process not found.
			echo "No X running." #It's faster to type "logout".
		fi
		;;
	4)
		sudo pm-hibernate
		exit
		;;
	5)
		sudo pm-sleep
		exit
		;;
	6)
		exit
		;;
	*)
		echo "Invalid option."
		;;
	esac
done

Offline

#1847 2012-07-15 07:30:30

ViruSzZ
Member
From: The Streets
Registered: 2010-10-14
Posts: 202
Website

Re: Post your handy self made command line utilities

on my arch linux on my lappy in conky i've used a one liner i found somehere in the forums to count the age of your installation and now i bought a desktop PC and installed gentoo on it. coniguring the conky, i needed to found a way to fetch this information so i just created the following script which should get the age of any distro. (it does not have any error checking and i'm getting the initial date from '/etc/ssh/ssh_host_dsa_key.pub'. is there any more reliable and smarter way of getting this value?

anyhow here's the script:

#!/bin/bash
########################
## get your distro age in days  ##
##	author: ViruSzZ		##
########################

###{{{ covert month from 'Jun' to '06' etc...
convertMonth () 
{
	local months=( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec )
	local count

	for (( count=0; count<11; count++ )); do
	    [[ $1 = ${months[$count]} ]] && break
	done

	echo $(( count+1 )) 
}
###}}}

###{{{ covert and return the initial date
finalDate()
{	
	# init the year
	local year=${3-$(date +%Y)}

	# init the day and fix it 
	local day=$2
	[[ ${#day} -lt 2 ]] && day="0${day}"

	local month=$(convertMonth $1)

	echo -n "${year}-${month}-${day}"
}
###}}}

## matches 'Dec  7  2011' or 'Dec  7'
installDateREGEX='[A-Z]{1}[a-z]{2}(.?){1,2}[0-9]{1,2}((.?){1,2}[0-9]{4}|)'
getDateFrom=/etc/ssh/ssh_host_dsa_key.pub

## some magic applied
IFS='
'
aRray=($(ls -l ${getDateFrom}|grep -Eo ${installDateREGEX}|sed 's# \+#\n#g'))
installDATE=$(finalDate ${aRray[0]} ${aRray[1]} ${aRray[2]})

## convert the date of installation to a more reliable format
startDATE=$(date --utc --date "${installDATE}" +%s)

## get the date of today in the required format and 
## convert it 
endDATE=$(date --utc --date "$(date +'%Y-%m-%d')" +%s)

## calulate the difference between the two dates in days
distroAGE=$(( (endDATE-startDATE)/(3600*24) ))

## print the result
echo "${distroAGE} day(s)"

here's how it looks in conky:
thumb-in_conky.png

Last edited by ViruSzZ (2012-07-15 07:35:16)


Their Momma Made Em, Their Momma Gave em & now she can`t even SAVE`em | My WebLog

Offline

#1848 2012-07-15 09:30:46

piffey
Member
From: Sioux Falls, SD
Registered: 2009-10-07
Posts: 54

Re: Post your handy self made command line utilities

I recently wrote an alarm clock myself then a friend pointed me to at(1). One line on-the-fly alarm clocks. My Mind = blown.

n1x4 wrote:

Too poor to afford an alarm clock, so I wrote this little script and applied it to mygtkmenu. Copied a few good 'wake-up' tunes to a dedicated folder.

Offline

#1849 2012-07-15 14:45:23

n1x4
Member
From: Chernobyl
Registered: 2012-02-17
Posts: 149
Website

Re: Post your handy self made command line utilities

piffey wrote:

I recently wrote an alarm clock myself then a friend pointed me to at(1). One line on-the-fly alarm clocks. My Mind = blown.

n1x4 wrote:

Too poor to afford an alarm clock, so I wrote this little script and applied it to mygtkmenu. Copied a few good 'wake-up' tunes to a dedicated folder.


HAHAHAHA.. I'll be damned! Learn something new everyday..  smile


||github||

Offline

#1850 2012-07-24 15:34:49

SeducingOrange
Member
Registered: 2012-07-24
Posts: 12

Re: Post your handy self made command line utilities

I am currently working on a shell wrapper made in Python


The John Blog for humor and linux smile

Offline

Board footer

Powered by FluxBB