You are not logged in.
@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
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
Offline
@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
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
Okay, good to know. I will take a closer look next week.
Offline
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
@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
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
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
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 (MATE GTK3) | Fedora 25 - ASUS Core-i7 Optimus Laptop
Offline
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 (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
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.
#!/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
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
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
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
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
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
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
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)
"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman
Online
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
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
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.
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
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
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)"
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
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.
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
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..
||github||
Offline
I am currently working on a shell wrapper made in Python
The John Blog for humor and linux
Offline