You are not logged in.

#1626 2011-11-28 04:18:12

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

Re: Post your handy self made command line utilities

Try

xrandr -q|awk '/VGA1 connected/ {getline; print $1}'

Offline

#1627 2011-11-28 04:26:15

engelus
Member
From: Salta - Argentina
Registered: 2011-06-11
Posts: 46

Re: Post your handy self made command line utilities

Stebalien wrote:

Configures an external monitor connected over VGA.

#!/bin/bash
mode="$(xrandr -q|grep -A1 "VGA1 connected"| tail -1 |awk '{ print $1 }')"
if [ -n "$mode" ]; then
    xrandr --output VGA1 --mode "$mode" --right-of LVDS1
    xrandr --output LVDS1 --primary
else
    xrandr --output VGA1 --off
fi

i was trying and it work, but i have some issues in the laptop i lost lxpanel and in the desktop pc only have wallpaper, why is that?

20111128010548.th.jpg

20111128010601v.th.jpg

Offline

#1628 2011-11-28 05:57:10

x33a
Forum Moderator
Registered: 2009-08-15
Posts: 4,532
Website

Re: Post your handy self made command line utilities

A pop-up terminal notifier for cmus.

I sometimes like to look at the size of the currently playing song in cmus. Earlier i had to manually go the directory where the song resided, and then look at the size.

I was looking at ways to achieve this from within cmus. cmus supports executing shell commands. so i created this script, which basically uses cmus-remote to display the path of the currently playing song, which can be used to display the size of the file.

Now the problem was displaying the output. So i used a custom sized urxvt window, set it to float in dwm, and used it with "timeout" command so that it vanishes after the specified period. A bit like a popup notification tongue

I have bound this script to f2 key in cmus.

bind common F2 shell /home/x33a/bin/cmus-current_song_size.sh

cmus-current_song_size.sh:

#!/bin/bash

FILENAME=/tmp/cmus-$(date +%s)

ls -lh `cmus-remote -Q | grep file | awk '{print$2}'` > $FILENAME

urxvtc -title cmus-filesize -geometry 125x5+10+300 -e timeout 5 vim $FILENAME

sleep 1

rm -f $FILENAME

screencast: http://ompldr.org/vYmhodg

Offline

#1629 2011-11-28 06:48:57

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

Re: Post your handy self made command line utilities

If you want just the size & name, use 'du -h' instead of 'ls -lh'.

du -h `cmus-remote -Q | awk '/file/ {print $2}'`

BTW, this will fail if you have spaces in the path.

Last edited by karol (2011-11-28 06:54:58)

Offline

#1630 2011-11-28 11:51:09

x33a
Forum Moderator
Registered: 2009-08-15
Posts: 4,532
Website

Re: Post your handy self made command line utilities

karol wrote:

If you want just the size & name, use 'du -h' instead of 'ls -lh'.

du -h `cmus-remote -Q | awk '/file/ {print $2}'`

Thanks for the awk syntax. Saves a grep. As for du -h, ls -lh gives the permissions and modification time also.

BTW, this will fail if you have spaces in the path.

Nice catch. There are no spaces in my collection, but sometimes i do come across folders with spaces, so i'll have to look at ways to fix this when i have the time.

Offline

#1631 2011-11-28 14:02:34

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

Re: Post your handy self made command line utilities

I'm semi-guessing at what the output of cmus-remote -q looks like, but...

du -h "$(cmus-remote -q | sed -n '/^file/s/file //p')"
# or
du -h "$(cmus-remote -q | awk '/^file/ { sub(/^file /, ""); print }')"
# or
cmus-remote -q | while read field value; do [[ $field = file ]] && exec du -h "$value"; done

Note the quoting around the command substitution in the first two... The last is my preference, though.

Last edited by falconindy (2011-11-29 11:05:34)

Offline

#1632 2011-11-28 14:07:35

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

Re: Post your handy self made command line utilities

falconindy wrote:

I'm semi-guessing at what the output of cmus-remote -q looks like

[karol@black ~]$ cmus-remote -Q
status playing
file /home/karol/music/linux_sampler/Chevy_Chase.mp3
duration 187
position 7
set aaa_mode all
set continue true
set play_library true
set play_sorted false
set replaygain disabled
set replaygain_limit true
set replaygain_preamp 6.000000
set repeat false
set repeat_current false
set shuffle true
set softvol false
set vol_left 84
set vol_right 84

Offline

#1633 2011-11-28 17:32:05

Earnestly
Member
Registered: 2011-08-18
Posts: 805

Re: Post your handy self made command line utilities

Update
Making a simple AUR wrapper with research and guidance from Aurget.
I needed a basic tool to simply compare packages installed on my system to those on the AUR database.

#!/bin/bash
echo -e "\e[1;34m::\e[0m \e[1;20mSearching the AUR for \"$2\"...\e[0m"  
aur_results=$( wget -qO - "http://aur.archlinux.org/rpc.php?type=search&arg=$2" | awk -F'"' -v RS='","' '/Name":/ { printf "%s", $3 } /Version":/ { printf "|%s", $3 } /Description":/ { printf "|%s", $3 } /OutOfDate":/ { printf "|%s\n", $3 }' )
while IFS='|' read -r Name Version Description OutOfDate; do
    case $1 in
        -d) wget -qO - http://aur.archlinux.org/packages/$2/$2.tar.gz | ( tar xvfz - ) && cd $2 ;;                    
        -q) if [[ -z "$aur_results" ]]; then
                echo "Nothing found."
            else
                [[ $( pacman -Qq | grep "$2" ) == "$Name" ]] && Status="\e[1;36m[$( pacman -Q | grep "$2" | awk '{ print $2 }' )]\e[0m" || Status=""
                [[ "$OutOfDate" = 1 ]] && echo -e "\e[1;31m*\e[0m$Name \e[1;32m$Version\e[0m \e[1;33m$Status\e[0m\n\e[1;30m${ Description//\\\/// } \e[0m" || echo -e "$Name \e[1;32m$Version\e[0m \e[1;33m$Status\e[0m\n\e[1;30m${ Description//\\\/// } \e[0m"
            fi ;;
        *) echo -e "Usage: aurora [OPTIONS]\nOptions:\n  -q \t Query AUR database\n  -d \t Download package" ;;
    esac
done < <( sort <<< "$aur_results" )
Example output:
---
User@Host: $ ./aurora.sh -q musca
:: Searching the AUR for "musca"...
*musca-bzr 213-1 [213-1]
 A simple dynamic window manager for X, with features nicked from ratpoison and dwm
---
*       = Symbolising out of date
[0-9] = Currently installed version

It now does utterly everything I need all with less lines of code than the previous, and I couldn't be happier right now big_smile ( Unless it could be even more compact )

Thanks

Edit: Could anyone kindly explain what done < <(sort <<< "$aur_results") means with regard to the arrangement of "<"s, thank you.
Edit2: There is one small bug, and that is any "Description" which includes a double quote ( probably other escaped characters too ) will be cut off with a trailing backslash. Not sure how to fix this yet.

Edit3: Updated with karol's improvement ( below ) and compacted the code a tad

Last edited by Earnestly (2011-11-30 01:34:27)

Offline

#1634 2011-11-29 05:44:37

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

Re: Post your handy self made command line utilities

What

pacman -Q | grep "$2" | awk '{print $1}'

is supposed to do - print package names? If so

pacman -Qq | grep "$2"

should be enough.

Offline

#1635 2011-11-29 11:14:15

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

Re: Post your handy self made command line utilities

Kaustic wrote:

Could anyone kindly explain what done < <(sort <<< "$aur_results") means with regard to the arrangement of "<"s, thank you.

<<< is a herestring in bash. It's like a heredoc, but inline and for strings.

Kaustic wrote:

There is one small bug, and that is any "Description" which includes a double quote ( probably other escaped characters too ) will be cut off with a trailing backslash. Not sure how to fix this yet.

Sure, because you're trying to use plain awk to parse json. To "fix" it requires using something that understands json, such as jshon.

Offline

#1636 2011-11-29 12:14:26

Earnestly
Member
Registered: 2011-08-18
Posts: 805

Re: Post your handy self made command line utilities

karol wrote:
pacman -Qq | grep "$2"
falconindy wrote:

...

Ah, thank you both for the info/advice, I always appreciate it. As you can tell I'm still fairly new to scripting/Linux, but enjoying it greatly so far.

Last edited by Earnestly (2011-11-29 12:17:50)

Offline

#1637 2011-11-29 18:13:56

i_love_penguins
Member
From: Germany
Registered: 2010-03-30
Posts: 46
Website

Re: Post your handy self made command line utilities

Since I love listening to radio streams, I made little bash function which spawns cvlc with a supplied Radio URL:

alias deepmix='playstream http://deepmix.ru/deepmix128.pls'
alias mottt='playstream http://mottt.fm/motttfm192.pls'
alias bytefm='playstream http://www.byte.fm/stream/bytefm.pls'
#...and more...

function stopstream {
	kill `cat ~/.cvlc_radio.pid` &> /dev/null
}

function playstream {
	stopstream
	nohup cvlc $1 &> /dev/null &
	echo $! > ~/.cvlc_radio.pid
}

Offline

#1638 2011-11-29 18:20:00

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

Re: Post your handy self made command line utilities

If you have just one instance of an app, you can kill it with pkill:

[karol@black ~]$ nohup urxvt -e htop &
[1] 4390
[karol@black ~]$ pgrep htop
4391
[karol@black ~]$ pkill htop
[karol@black ~]$ pgrep htop
[1]+  Done                    nohup urxvt -e htop

Offline

#1639 2011-11-29 18:40:08

MrCode
Member
Registered: 2010-02-06
Posts: 373

Re: Post your handy self made command line utilities

Dead stupid-simple AUR "helper" that I shamelessly named "aurget.sh" because I knew nothing about this. tongue

#!/bin/bash

extract()
{
	if test -d ~/AUR/$1; then
		echo "Unable to extract PKGBUILD/install scripts: directory already exists"
		exit 1
	else
		echo -n "Extracting PKGBUILD/install scripts..."
		tar -C ~/AUR -xf $1.tar.gz
		echo "done"
		echo "$1 is ready to be built."
	fi
}

if test -z $1; then
	echo "Usage: $0 <pkgname>"
	echo "Gets/extracts a PKGBUILD/install script tarball from the AUR."
	exit 1
else
	if test -f ~/Archives/$1.tar.gz; then
		echo "PKGBUILD tarball already exists"
		extract $1
	else
		cd ~/Archives
		echo -n "Downloading tarball..."
		wget -q https://aur.archlinux.org/packages/$1/$1.tar.gz
	fi

	if test $? -ne 0; then
		echo "fail! "
		echo "Unable to fetch tarball."
		exit 1
	else
		echo "done"
		extract $1
	fi
fi

…and the corresponding "aurrm.sh", to speed up cleanup if I want to get rid of something:

#!/bin/bash

if test -z $1; then
	echo "Usage: $0 <pkgname>"
	echo "Removes an AUR build directory (and associated tarball) from the system."
	echo "(does not uninstall package)"
	exit 1
else
	if test -d ~/AUR/$1; then
		echo -n "Removing build directory..."
		rm -r ~/AUR/$1
		echo "done"
	else
		echo "Build directory for \"$1\" does not exist."
	fi

	if test -f ~/Archives/$1.tar.gz; then
		echo -n "Removing PKGBUILD tarball..."
		rm ~/Archives/$1.tar.gz
		echo "done"
	else
		echo "PKGBUILD tarball not found."
		exit 1
	fi
fi

Yes, I know, it's far too dependent on certain directories already existing, and I'm sure I make tons of other n00bish mistakes, but I just want to give back a little for once, in the form of code…

I mostly wrote these because I didn't want any existing AUR helper that I knew of at the time (i.e. yaourt), and I didn't want to constantly use wget (or worse yet Firefox)/tar/etc. manually to handle everything.  Well, there's that, and I also wanted to see if I could still script worth sh8. tongue

Offline

#1640 2011-11-30 01:31:51

Earnestly
Member
Registered: 2011-08-18
Posts: 805

Re: Post your handy self made command line utilities

MrCode wrote:

...

You could almost replace all that code with:

cd ~/AUR; wget -qO - http://aur.archlinux.org/packages/$1/$1.tar.gz | ( tar xvfz - ) && cd $1

It will extract the tar from the STDOUT stream ( - ) without saving it to disk so you're simply left in the newly extracted package directory ready to makepkg.

Offline

#1641 2011-12-01 20:20:48

paziul
Member
From: N.C.
Registered: 2011-11-23
Posts: 27

Re: Post your handy self made command line utilities

this idea came to me few years ago when I got bored hitting F5 on craigslist,
it connects to CL every 60 seconds ( so you do not miss a deal ), gets "electronics" and "computers" categories, creates a HTML page with a two column table, with auto page refresh.
you can use "appweb" or "boa" lightweight web servers for this purpose - than customize $CLWWWROOT for your index.html file location ( within the web server path of course ) and the CL categories for your location... make sure the sh has a r/w permission for $CLWWWROOT directory - run it from the shell, and open the browser to test... done
I am using it for about 4-5 years now.... starts during boot on my old 2.4 kernel iptables/etc.  P3 1GHz 2GB HDD 192MB RAM Compaq :)

#!/bin/sh

PATH="/sbin:/usr/sbin:/usr/local/sbin:/bin:/usr/bin:/usr/local/bin"

CLWWWROOT="/var/appWeb/web/cl"
CLCATURL1="http://charlotte.craigslist.org/ele/" # electionics
CLCATURL2="http://charlotte.craigslist.org/sys/" # computers

cd $CLWWWROOT

while true; do
  rm index*tmp
  wget -o /dev/null -O index1.html.tmp $CLCATURL1
  wget -o /dev/null -O index2.html.tmp $CLCATURL2
  echo "
<html>
<HEAD>
<META HTTP-EQUIV=REFRESH CONTENT=30>
</HEAD>
<body>
<table border="1">
<tr>
<td> " > index.html
  echo "ELECTRONICS" >> index.html
  sed -n '/h4/,$p' index1.html.tmp >> index.html
  echo "<br><br><br><br><br><br>" >> index.html
  echo "</td>" >> index.html
  echo "<td>" >> index.html
  echo "COMPUTERS" >> index.html
  sed -n '/h4/,$p' index2.html.tmp >> index.html
  echo "</td>" >> index.html
  echo "</table>" >> index.html
  sleep 60
done

Last edited by paziul (2011-12-01 20:27:18)


"...and it probably never will support anything other than AT-harddisks..."

Offline

#1642 2011-12-05 20:21:42

nomilieu
Member
Registered: 2010-07-03
Posts: 133

Re: Post your handy self made command line utilities

@paziul

Funny you should mention craigslist; I recently wrote a script to run daily and grep just for the things I want.
I'm not currently on the machine I wrote it on, but it's something like:

curl http://[my_town].craigslist.org/rea/ | grep "</a>" | grep "thing_i_want_in_a_house" > craigs.html

And similarly for cars, electronics, etc. Maybe I'll get motivated to have it detect price ranges too.
I'm quite thankful that craigslist puts each link on a new line, as otherwise I'd have to add a bunch of newlines.

(Yeah, I don't even bother making a proper html file, but most browsers can read it fine with just the links.)

Last edited by nomilieu (2011-12-05 20:23:42)

Offline

#1643 2011-12-06 13:53:59

ubertaco
Member
Registered: 2011-04-19
Posts: 23

Re: Post your handy self made command line utilities

First time rolling my own dbus service; this is for volume control.

I'd had a version of this before, but got tired of dealing with the irritating notification stacking. So:
pyvold:

#!/usr/bin/env python2
import alsaaudio as alsa, pynotify, os
import dbus, dbus.service, gtk
from dbus.mainloop.glib import DBusGMainLoop

class PyVolDaemon(dbus.service.Object):
    def __init__(self):
        bus_name = dbus.service.BusName('net.ninjatricks.pyvold', bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, '/net/ninjatricks/pyvold')
        self.mixer = alsa.Mixer('Master')
        pynotify.init("pyvol")

        self.n = pynotify.Notification("Volume", "")

    @dbus.service.method('net.ninjatricks.pyvold')
    def volumeUp(self):
        try:
            # raise volume
            vol = self.mixer.getvolume()[0]
            if vol < 5:
                vol = 0
            else:
                vol += 5
            self.mixer.setvolume(vol)


            iconURI = os.path.dirname(os.path.realpath(__file__))
            if vol > 66:
                iconURI += "/audio-volume-high-3.png"
            elif vol <= 66 and vol > 33:
                iconURI +=  "/audio-volume-medium-3.png"
            elif vol <= 33 and vol > 0:
                iconURI +=  "/audio-volume-low-3.png"
            elif vol == 0:
                iconURI =  "/audio-volume-muted-3.png"
            icon = gtk.gdk.pixbuf_new_from_file(iconURI)

            # show notification
            self.n.set_hint_string('append', '')
            self.n.set_icon_from_pixbuf(icon)
            self.n.update("Volume", "Volume is now set to " + str(vol) + "%")
            self.n.show()
        except:
            raise

    @dbus.service.method('net.ninjatricks.pyvold')
    def volumeDown(self):
        try:
            # lower volume
            vol = self.mixer.getvolume()[0]

            if vol < 5:
                vol = 0
            else:
                vol -= 5

            self.mixer.setvolume(vol)

            # detect which icon to use for notification
            iconURI = os.path.dirname(os.path.realpath(__file__))

            if vol > 66:
                iconURI += "/audio-volume-high-3.png"
            elif vol <= 66 and vol > 33:
                iconURI += "/audio-volume-medium-3.png"
            elif vol <= 33 and vol > 0:
                iconURI += "/audio-volume-low-3.png"
            elif vol == 0:
                iconURI += "/audio-volume-muted-3.png"

            icon = gtk.gdk.pixbuf_new_from_file(iconURI)

            # show notification
            self.n.set_hint_string('append', '')
            self.n.set_icon_from_pixbuf(icon)
            self.n.update("Volume", "Volume is now set to " + str(vol) + "%")
            self.n.show()
        except:
            raise

    @dbus.service.method('net.ninjatricks.pyvold')
    def mute(self):
        try:

            self.mixer.setmute(1)

            iconURI = os.path.dirname(os.path.realpath(__file__))
            iconURI +=  "/audio-volume-muted-3.png"

            icon = gtk.gdk.pixbuf_new_from_file(iconURI)

            # show notification
            self.n.set_icon_from_pixbuf(icon)
            self.n.update("Volume", "Volume muted")
            self.n.set_hint_string('append', '')
            self.n.show()
        except:
            raise

    @dbus.service.method('net.ninjatricks.pyvold')
    def toggle(self):
        try:
            ismuted = bool(self.mixer.getmute()[0])
            if ismuted:
                self.mixer.setmute(0)

                vol = self.mixer.getvolume()[0]

                # detect which icon to use for notification
                iconURI = os.path.dirname(os.path.realpath(__file__))

                if vol > 66:
                    iconURI += "/audio-volume-high-3.png"
                elif vol <= 66 and vol > 33:
                    iconURI += "/audio-volume-medium-3.png"
                elif vol <= 33 and vol > 0:
                    iconURI += "/audio-volume-low-3.png"
                elif vol == 0:
                    iconURI += "/audio-volume-muted-3.png"

                notifyString = "Volume unmuted"

            else:
                self.mixer.setmute(1)
                iconURI = os.path.dirname(os.path.realpath(__file__)) + "/audio-volume-muted-3.png"

                notifyString = "Volume muted"
                
            icon = gtk.gdk.pixbuf_new_from_file(iconURI)

            # show notification
            self.n.set_icon_from_pixbuf(icon)
            self.n.update("Volume", notifyString)
            self.n.set_hint_string('append', '')
            self.n.show()

        except:
            raise

DBusGMainLoop(set_as_default=True)
pyvold = PyVolDaemon()
gtk.main()

pyvolcontrol:

#!/usr/bin/env python2
import sys, argparse
import dbus

parser = argparse.ArgumentParser(description='command input')
parser.add_argument('command', metavar='cmd', help='command to perform')
args = parser.parse_args()

functions = { 'volup' : 'volumeUp', 'volumeup' : 'volumeUp', 'volDown' :
'volumeDown', 'volumedown' : 'volumeDown', 'voldown' : 'volumeDown', 'mute' :
'mute', 'toggle' : 'toggle', }

bus = dbus.SessionBus()
pyvold = bus.get_object("net.ninjatricks.pyvold", "/net/ninjatricks/pyvold")
operation = getattr(pyvold, functions[args.command])
operation()

Uses these icons for the notifications.

Requires: python2, pynotify, alsa (and its python bindings), dbus (and its python bindings)

A little heavy on the dependencies, but it's stuff I already had installed anyways. Glue code!

Offline

#1644 2011-12-07 13:05:08

x33a
Forum Moderator
Registered: 2009-08-15
Posts: 4,532
Website

Re: Post your handy self made command line utilities

falconindy wrote:

I'm semi-guessing at what the output of cmus-remote -q looks like, but...

du -h "$(cmus-remote -q | sed -n '/^file/s/file //p')"
# or
du -h "$(cmus-remote -q | awk '/^file/ { sub(/^file /, ""); print }')"
# or
cmus-remote -q | while read field value; do [[ $field = file ]] && exec du -h "$value"; done

Note the quoting around the command substitution in the first two... The last is my preference, though.

Sorry for the late reply, I was away for a little while. And thanks a lot, the third solution (the only one i tested), works quite nicely. As for "cmus -Q", you must have seen karol's reply.

Thanks.

Offline

#1645 2011-12-11 19:58:55

Barrucadu
Member
From: York, England
Registered: 2008-03-30
Posts: 1,158
Website

Re: Post your handy self made command line utilities

Poor man's continuous integration system:

#!/bin/zsh

echo "Started continuous build on `pwd`"

while true; do
    echo "Rebuilding..."
    make clean
    make all
    inotifywait -e modify -e move -e create -e delete -e delete_self . &>/dev/null
done

echo "Done."

I've been using this for a university report I'm writing in LaTeX, as I also use Evince (which updates when the PDF changes), I just have to save the .tex file to rebuild and read the new version.

Last edited by Barrucadu (2011-12-11 19:59:20)

Offline

#1646 2011-12-14 17:21:35

r4
Member
Registered: 2009-10-20
Posts: 19

Re: Post your handy self made command line utilities

Just made this script this morning...

The idea is for this script to utilize inotify and watch my mail directories for new files. When it finds a new file, it sends out a notification.

The script was developed with the intent of using mutt + offlineimap and letting offlineimap handle the process of getting the "new emails".

Please critique!

#!/bin/bash

####
#   This Script will monitor email directories
#   and if a new file is added, will display a notification.
####

####
#   User Configuration
####
ICON=notification-message-email
MAILDIR="${HOME}/.mail/"

####
#   Code
####
mailbox=(${MAILDIR}*)

getNumEmail()
{
    case "$1" in
        *) #Get individual account
            NUM[$1]="`find ${mailbox[$1]}/Inbox/new/ -type f | wc -l`"
            ;;
        all)  #All accounts, respectively
            for ((i=0; i< ${#mailbox[@]}; i++))
            do
                NUM[$i]="`find ${mailbox[$i]}/Inbox/new/ -type f | wc -l`"
            done
            ;;
        sumall)  #Sum of all accounts
            find ${MAILDIR}*/Inbox/new -type f | wc -l
            ;;
    esac
}

getAccountName()
{
    case "$1" in
        *) #Get individual account name
            ACC[$1]="${mailbox[$1]:${#MAILDIR}}"
            ;;
        all) #Get all account names
            for ((i=0; i< ${#mailbox[@]}; i++))
            do
                ACC[$i]="${mailbox[$i]:${#MAILDIR}}"
            done
            ;;
    esac
}

#Print status of email account
printEmail()
{
    getAccountName $1

    getNumEmail $1

    case "${NUM[$1]}" in
        0)
            printf "${ACC[$1]:0:6}: \tNo new email\n"
            ;;
        1)
            printf "${ACC[$1]:0:6}: \t${NUM[$1]} new email\n"
            ;;
        *)
            printf "${ACC[$1]:0:6}: \t${NUM[$1]} new emails\n"
            ;;
    esac
}

#Print the status of all emails
printStatus()
{
    for ((i=0; i< ${#mailbox[@]}; i++))
    do
        printEmail "$i"
    done
}

# Get all account names at initial launch of script.
#getAccountName

# If a new email shows up in any of the directories being monitored,
# get the number of emails for each account and display a notification.
while inotifywait -e create ${MAILDIR}*/Inbox/new;
do
#    getNumEmail all
    notify-send -u normal -i "${ICON}" -t 5000 "New mail" "`printStatus`"
done

...now I just need to find a way to expand on this script to pipe the total number of new emails to xmobar.

I was thinking just have xmobar cat a file and pipe it in that way but I feel it could be done in a nicer fashion.

[EDIT] Updated the code a little...design flow should be a bit easier to understand.

Last edited by r4 (2011-12-14 20:12:35)

Offline

#1647 2011-12-14 17:26:24

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

Re: Post your handy self made command line utilities

r4, please edit your post.
When pasting code, please use [ code ] tags https://bbs.archlinux.org/help.php#bbcode

like this

It makes the code more readable and more convenient to scroll through.

Offline

#1648 2011-12-15 15:05:44

iTwenty
Member
From: India
Registered: 2010-10-24
Posts: 63
Website

Re: Post your handy self made command line utilities

A couple of noobish hacks I came up with while tidying up my music directory today

#! /usr/bin/env bash
if [[ ! -d $1 ]]; then
    echo -e "Invalid Directory"
    exit 1
fi
DIRNAME="$1"

echo $DIRNAME | grep -E '^[1-9][0-9][0-9][0-9] .*' > /dev/null

if [[ $? == 0 ]]; then
    echo -e  "'$DIRNAME' has a year"
    exit 0
fi

FILENAME="`ls \"$DIRNAME\" | head -1`"
FILEPATH="$DIRNAME/$FILENAME"

YEAR=`mid3v2 "$FILEPATH" | grep -a TDRC | cut -d"=" -f2-`

if [[ "$YEAR" == "" ]]; then
    echo -e "No year found in album '$DIRNAME'"
    exit 0
fi

CHOICE="y"

echo -e "Rename '$DIRNAME' to '$YEAR $DIRNAME'?"
read CHOICE
if [[ $CHOICE = [nN] ]]; then
    exit 0
fi
mv "$DIRNAME" "$YEAR $DIRNAME"

It takes the first file found inside a directory and, if its an mp3 file with a valid year ID3 tag,  renames the directory to <year> <old dir name>. Does not work for recursively nested directrories. Use the bash for loop for that.

Another one:

#! /usr/bin/env bash
MUSIC_DIR="$HOME/Music"
COVER_NAME="Cover.jpg"
NO_COVER="$MUSIC_DIR/Cover.jpg"
while true; do
    mpc idle player > /dev/null
    PATH_TO_COVER="`mpc --format %file% | head -1 | xargs -0 dirname`"
    COVER_ART="$MUSIC_DIR/$PATH_TO_COVER/$COVER_NAME"
    if [[ ! -f $COVER_ART ]]; then
        COVER_ART="$NO_COVER"
    fi
    convert -resize 300x300 "$COVER_ART" "/tmp/$COVER_NAME"
done;

This searches for 'Cover.jpg' inside the directory of song currently playing in mpd, resizes it to 300x300 and copies it over to /tmp/Cover.jpg, which can be displayed with conky. It is invoked each time a song is changed using mpc's idle feature.


“Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore. Dream. Discover.” - Mark Twain

Offline

#1649 2011-12-17 21:22:14

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

Re: Post your handy self made command line utilities

Generates a BBCode thumbnail image link:

#! /bin/dash

REF=$(eat find $@)
REF=${REF##*\'}

printf '[url=%b][img]%b[/img][/url]\n' "$(eat blob $REF)" "$(eat thumb $REF)"

Uses eat.


gh · da · ds · cr · ab · fkr

Offline

#1650 2011-12-18 04:47:49

/dev/zero
Member
From: Melbourne, Australia
Registered: 2011-10-20
Posts: 1,176
Website

Re: Post your handy self made command line utilities

A daemon-like script to warn when the battery is low, and shut the system down gracefully before going flat.

Based on code spliced from wpa_auto and Getting a warning when battery power gets low.

Dependencies: espeak, acpi, bc.

Known problems: output from "acpi -b" changes format when the battery is low. The below code includes a workaround, but this isn't ideal.


/etc/rc.d/battery_monitor

#!/bin/bash

. /etc/rc.conf
. /etc/rc.d/functions

DAEMON_NAME=$(basename $0)
MAIN_LOOP=/usr/sbin/battery_monitor_loop

case "$1" in
    start)
        stat_busy "Starting $DAEMON_NAME daemon"
        if [[ ! -f /run/daemons/$DAEMON_NAME ]]; then
            $($MAIN_LOOP) &
            if [[ $? -gt 0 ]]; then
                stat_fail
                exit 1
            else
                add_daemon $DAEMON_NAME
                stat_done
            fi
        else
            stat_fail
            exit 1
        fi
        ;;
    stop)
        stat_busy "Stopping $DAEMON_NAME daemon"
        if [[ -f /run/daemons/$DAEMON_NAME ]]; then
            killall $(basename $MAIN_LOOP)
            rm_daemon $DAEMON_NAME
            if [[ $? -gt 0 ]]; then
                stat_fail
                exit 1
            else
                stat_done
            fi
        else
            stat_fail
            exit 1
        fi
        ;;
    restart)
        $0 stop
        sleep 1
        $0 start
        ;;
        *)
        echo "usage: $0 {start|stop|restart}"
        ;;
esac

exit 0

/usr/sbin/battery_monitor_loop

#! /bin/bash

SLEEP_TIME=5   # Default time between checks.
BUFFER_TIME=2  # Shutdown this many minutes before battery dies.

while [ true ]; do
    if [[ -n $(acpi -b | grep -i discharging) ]]; then
        rem_time=$(acpi -b | awk '{print $(NF-1)}')
        hrs=$(date --date="$rem_time" +%H)
        mins=$(date --date="$rem_time" +%M)
        rem_mins=$(echo "$hrs*60 + $mins - $BUFFER_TIME" | bc)
        
        if [[ $rem_mins -gt 30 ]]; then
            SLEEP_TIME=10
        fi
        if [[ $rem_mins -le 30 ]]; then
            SLEEP_TIME=5
            espeak "Battery low. System will shutdown in $rem_mins minutes." 2>&1 > /dev/null
        fi
        if [[ $rem_mins -le 10 ]]; then
            SLEEP_TIME=2
        fi
        if [[ $rem_mins -le 3 ]]; then
            SLEEP_TIME=1
            when=now
            if [[ $rem_mins -gt 0 ]]; then
                when="+$rem_mins"
            fi
            shutdown -hP $when
        fi
    fi
    sleep ${SLEEP_TIME}m
done

Last edited by /dev/zero (2012-01-07 08:18:22)


Linux is NOT Windows | The Rootless Root
Toshiba Satellite i5-3230M 2.6GHz CPUs, 4Gb RAM, ArchLinux, wmii, nVidia GeForce GT 740M.

Offline

Board footer

Powered by FluxBB