You are not logged in.

#1401 2010-12-30 02:01:35

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

Re: Post your handy self made command line utilities

mpd 0.16 seems to have removed smart previous, that rewinded the song instead of playing the previous song when you were a few seconds in.

#! /bin/bash
IFS='()%' read a b c < <(mpc | tail -n 2)
((b<=2)) && mpc prev || mpc seek 0

Offline

#1402 2011-01-02 10:23:41

Nichollan
Member
From: Stavanger, Norway
Registered: 2010-05-18
Posts: 110

Re: Post your handy self made command line utilities

I wanted a simple client to LambdaMOO (a social text-based virtual world in which players can program objects and areas), but with better command editing features than what telnet and netcat offered. This client uses rlwrap to provide readline features. It also underlines directions such as "north" and "downwards."

I am somewhat new to shell scripting and welcome constructive feedback – especially if there's an alternative to create the named pipe (mkfifo), or if there is a more conventional directory to place such things. I suspect I unwittingly violate some etiquette as well.

#!/bin/bash

# The directory in which the named pipe will be placed.
gamedir=$HOME/games/muds

mud=lambda.moo.mud.org
port=8888

if ! [ -p $gamedir/stdin ]; then
   echo "The named pipe $gamedir/stdin does not exist. Do you wish to create it?"
   read ANSWER
   if [ $(echo $ANSWER | egrep "^[yY]") ]; then
      if ! [ -d $gamedir ]; then
         mkdir -p $gamedir
      fi
      mkfifo $gamedir/stdin
   else
      exit
   fi
fi

if [ $1 ]; then
   mud=$1
   if [ $2 ]; then
      port=$2
   else
      port=23
   fi
fi

rlwrap sh -c "
telnet $mud $port < $gamedir/stdin |
sed 's/\([^a-z]\|^\)\(west\|east\|south\|north\|up\|down\)\([a-z]*\)/\1\x1b[4m\2\3\x1b[0m/ig'&

cat > $gamedir/stdin"

Offline

#1403 2011-01-02 10:32:11

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

Re: Post your handy self made command line utilities

@Nichollan Nice! I am not familiar with rlwrap, reading the man page now. The Wikipedia page for LambdaMOO is fascinating reading. smile

Offline

#1404 2011-01-04 04:04:31

crouse
Arch Linux f@h Team Member
From: Iowa - USA
Registered: 2006-08-19
Posts: 907
Website

Re: Post your handy self made command line utilities

Wrote this and stuck it in my .bashrc file so I could get a realtime stock quote quickly from my shell sessions.

stock ()
{
lynx -dump "http://www.google.com/finance?client=ob&q=${1}" | sed 's/.*']'//' | perl -00ne "print if /Watch this stock/i" | sed 's/Watch this stock//' | sed 's/Disclaimer//' | sed '/^$/d' | sed 's/Currency in USD//'
}

Looks like this when run

crouse@archie stock slv

slv
   30.26
   +0.08 (0.27%)
   Real-time:   11:41AM EST

    1. Range 30.14 - 30.44
    2. 52 week 14.37 - 30.44
    3. Open 30.29
    4. Vol / Avg. 9.57M/26.84M
    5. Mkt cap 9.73B
    6. P/E 95.32
    7. Div/yield     -
    8. EPS 0.32
    9. Shares 321.50M
   10. Beta 0.38
   11. Inst. own 25%

Offline

#1405 2011-01-04 07:11:35

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

Re: Post your handy self made command line utilities

@crouse, sometimes xmllint really rocks!

#!/bin/bash
xmllint='xmllint --html --xpath'
UA='Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20110101 Firefox/3.6.13'
stock()
{
  local p=$(curl -s -A "${UA}" "http://www.google.com/finance?client=ob&q=${1}")
  company "${p}"
  echo
  price_panel "${p}"
  echo
  snap_panel "${p}"
}
snap_panel()
{
  local p=$1
  ${xmllint} 'string(//*[@id="snap-panel"]/ol)' - <<<"${p}" 2>/dev/null |
  sed -e :a -e '2~3N;s/\n/\t/;ta' -e '/^$/d' | column -s $'\t' -t
}
price_panel()
{
  local p=$1
  ${xmllint} 'string(//*[@id="price-panel"])' - <<<"${p}" 2>/dev/null |
  sed '/^$/d' |
  sed -r -e '/[0-9]+\.[0-9]+$/{:a;/%\)$/be;N;s/\n/ /;ta;:e}' -e '/^Disclaimer$/d'
}
company()
{
  local p=$1
  ${xmllint} 'string(//*[@id="companyheader"]/div[1])' - <<<"${p}" 2>/dev/null |
  sed '1!d'
}
stock "${1}"

Result:

$ ./stock.sh Google
Google Inc. (Public, NASDAQ:GOOG)  

604.35 0.00 (0.00%)
Pre-market: 605.98 +1.63 (0.27%)
Jan 4, 8:58AM EST  
NASDAQ real-time data -
Currency in USD

Range           -
52 week     62.05 - 630.85
Open            -
Vol / Avg.  1,695.00/2.17M
Mkt cap     193.26B
P/E         24.46
Div/yield       -
EPS         24.71
Shares      319.78M
Beta        1.20
Inst. own   62%

Edit: improved.
Edit: improved, again. Added company header; improved sed in price_panel, but it still will fail on e.g. ZL due to lack of % in the result.

Last edited by lolilolicon (2011-01-04 14:07:12)


This silver ladybug at line 28...

Offline

#1406 2011-01-05 20:46:28

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

Re: Post your handy self made command line utilities

rotN.sh

#!/bin/dash

N=${1:-13}
case $N in *[!0-9]*) echo >&2 "$0: error: $N: NaN"; exit 1; esac

while read -r line
do

    i=0; while [ $i -lt ${#line} ]
    do

        eval '
            c=${line#'$(j=0; while [ $j -lt $i ]; do printf \?; j=$((j+1)); done)'}
            c=${c%'$(j=0; while [ $j -lt $((${#line}-i-1)) ]; do printf \?; j=$((j+1)); done)'}
        '

        noconv=false
        caps=false

        case $c in
        a) n=00 ;; b) n=01 ;; c) n=02 ;; d) n=03 ;; e) n=04 ;; f) n=05 ;; g) n=06 ;; h) n=07 ;;
        i) n=08 ;; j) n=09 ;; k) n=10 ;; l) n=11 ;; m) n=12 ;; n) n=13 ;; o) n=14 ;; p) n=15 ;;
        q) n=16 ;; r) n=17 ;; s) n=18 ;; t) n=19 ;; u) n=20 ;; v) n=21 ;; w) n=22 ;; x) n=23 ;;
        y) n=24 ;; z) n=25 ;;

        *)
            caps=true
            case $c in
            a) n=00 ;; b) n=01 ;; c) n=02 ;; d) n=03 ;; e) n=04 ;; f) n=05 ;; g) n=06 ;; h) n=07 ;;
            i) n=08 ;; j) n=09 ;; k) n=10 ;; l) n=11 ;; m) n=12 ;; n) n=13 ;; o) n=14 ;; p) n=15 ;;
            q) n=16 ;; r) n=17 ;; s) n=18 ;; t) n=19 ;; u) n=20 ;; v) n=21 ;; w) n=22 ;; x) n=23 ;;
            y) n=24 ;; z) n=25 ;;
            *) noconv=true
            esac

        esac

        if $noconv
        then printf %s "$c"
        else

            n=$(( (n+N)%26 ))

            if $caps
            then case $n in
                 0) printf A ;;  1) printf B ;;  2) printf C ;;  3) printf D ;;  4) printf E ;;  5) printf F ;;
                 6) printf G ;;  7) printf H ;;  8) printf I ;;  9) printf J ;; 10) printf K ;; 11) printf L ;;
                12) printf M ;; 13) printf N ;; 14) printf O ;; 15) printf P ;; 16) printf Q ;; 17) printf R ;;
                18) printf S ;; 19) printf T ;; 20) printf U ;; 21) printf V ;; 22) printf W ;; 23) printf X ;;
                24) printf Y ;; 25) printf Z ;;
            esac else case $n in
                 0) printf a ;;  1) printf b ;;  2) printf c ;;  3) printf d ;;  4) printf e ;;  5) printf f ;;
                 6) printf g ;;  7) printf h ;;  8) printf i ;;  9) printf j ;; 10) printf k ;; 11) printf l ;;
                12) printf m ;; 13) printf n ;; 14) printf o ;; 15) printf p ;; 16) printf q ;; 17) printf r ;;
                18) printf s ;; 19) printf t ;; 20) printf u ;; 21) printf v ;; 22) printf w ;; 23) printf x ;;
                24) printf y ;; 25) printf z ;;
            esac fi

        fi

        i=$((i+1))

    done

    echo

done

MMMYYY EEEYYYEEESSS !!! !!! !!!

Last edited by TaylanUB (2011-01-05 20:47:01)


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

Offline

#1407 2011-01-06 02:01:13

crouse
Arch Linux f@h Team Member
From: Iowa - USA
Registered: 2006-08-19
Posts: 907
Website

Re: Post your handy self made command line utilities

lolilolicon wrote:

@crouse, sometimes xmllint really rocks!


If you say so,
I like my version, more concise wink

Offline

#1408 2011-01-11 22:24:08

cubeist
Member
Registered: 2010-08-01
Posts: 36

Re: Post your handy self made command line utilities

here is a quick script I use to turn an image into a black and white.  This uses a different method than typical de-saturation and gives a very nice result 90% of the time.  This is a nautilus script so place it in your scripts folder and make it executable, then select image and run the script from the right-click script menu.

#!/bin/bash
#Requires imagemagick
input=$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS
fileName=$( basename $input | cut -f1 -d.)
(echo "25" ; convert -depth 16 $input -colorspace HSL -channel B -separate ${fileName}'_bw.jpg') | zenity --progress --width=350 --title="Quick Black & White" --text="Converting..." --pulsate --auto-close
exit 0

Edit-
-Added a zenity progress window
-forgot code tags

Last edited by cubeist (2011-01-19 00:18:57)

Offline

#1409 2011-01-11 22:27:20

some-guy94
Member
Registered: 2009-08-15
Posts: 360

Re: Post your handy self made command line utilities

Mount/Unmount removable devices using udisks and dmenu

#!/bin/bash
# Credit goes to steve___ for help with cleaning this up
dmenu='dmenu -i'
all_devices=$(udisks --enumerate-device-files | grep /dev/sd)
selection=$(udisks --enumerate-device-files | grep /dev/sd | (while read dev; do
    info=$(udisks --show-info $dev)
    [[ $(awk '/system internal/ {print $3}'<<<"$info") == '0' ]] || continue
    [[ $(awk '/usage/ {print $2}'<<<"$info") == 'filesystem' ]]  || continue
    if [[ $(awk '/is mounted/ {print $3}'<<<"$info") == '0' ]]; then
        echo "mount:$dev"
    else
        echo "unmount:$dev"
    fi
done) | sort | $dmenu "$@")

[[ $selection ]] || exit 1

if [[ $selection == mount:* ]]; then
    exec udisks --mount ${selection#mount:}
else
    exec udisks --unmount ${selection#unmount:}
fi

Last edited by some-guy94 (2011-01-12 05:08:16)

Offline

#1410 2011-01-11 22:55:17

Yannick_LM
Member
Registered: 2008-12-22
Posts: 142

Re: Post your handy self made command line utilities

A quick hack to use vim in sever mode on command-line.

vim () {
    local vim_orig=$(which 2>/dev/null vim)
    if [ -z $vim_orig ]
    then
        echo "$SHELL: vim: command not found"
        return 127
    fi
    $vim_orig --serverlist | grep --color=auto -q VIM
    if [ $? -eq 0 ]
    then
        if [ $# -eq 0 ]
        then
            $vim_orig
        else
            $vim_orig --remote "$@"
        fi
    else
        $vim_orig --servername vim "$@"
    fi
}

Anytime you type vim with a file name, the file will be open in the existing vim.

If you really want an other vim window, simply type vim without arguments.

Offline

#1411 2011-01-22 21:33:55

bsdard
Member
From: Surrey, UK
Registered: 2011-01-22
Posts: 15

Re: Post your handy self made command line utilities

I wrote a simple and very lightweight analog of xbacklight with much lesser dependencies (none actually). Anyway I can attach it here?
Works perfect on my laptop + dwm.

Offline

#1412 2011-01-22 21:44:38

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

Re: Post your handy self made command line utilities

bsdard wrote:

I wrote a simple and very lightweight analog of xbacklight with much lesser dependencies (none actually). Anyway I can attach it here?

Just post the code using [ code ] tags https://bbs.archlinux.org/help.php#bbcode

Offline

#1413 2011-01-22 21:47:45

bsdard
Member
From: Surrey, UK
Registered: 2011-01-22
Posts: 15

Re: Post your handy self made command line utilities

karol wrote:
bsdard wrote:

I wrote a simple and very lightweight analog of xbacklight with much lesser dependencies (none actually). Anyway I can attach it here?

Just post the code using [ code ] tags https://bbs.archlinux.org/help.php#bbcode

There are multiple files (it written in C). It's going to be a huge post.

Offline

#1414 2011-01-22 21:52:20

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

Re: Post your handy self made command line utilities

Then host it somewhere like github and link to it from Community Contributions - this is more for simple scripts...


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#1415 2011-01-27 19:13:51

ScottKidder
Member
Registered: 2008-10-27
Posts: 23

Re: Post your handy self made command line utilities

Just to fall asleep and wake up to music :)

#!/usr/bin/python
import sys, string, time, subprocess

level = levels = 13.0
timeToSleep = int(sys.argv[1])
step = timeToSleep / levels

print ("Going to sleep!")
print ("Taking to %d seconds to fall down %f levels." % (timeToSleep, levels))
while (level > 0):
    print ("Sleeping, level = %d, sleeping %f seconds" % (level, step)) 
    time.sleep(step)
    subprocess.Popen('amixer set Master 1%-', shell=True)
    level-=1

subprocess.Popen('cmus-remote -u', shell=True)
#!/usr/bin/python
import sys, string, time, subprocess

levels = 13.0
timeToFade = int(sys.argv[1])
step = timeToFade / levels
subprocess.Popen('amixer set Master 58%', shell=True)
subprocess.Popen('cmus-remote -u', shell=True)

t = 0
while (t < 11): # Only fade up to 90%
    print ("Fading in, t =%f" % t) 
    time.sleep(step)
    subprocess.Popen('amixer set Master 1%+', shell=True)
    t = t + 1

archlinux|xmonad
++++++++++[>++++++++>+++++++>+++<<<-]>+++.>---.<----.+++++..>>++.<++++++++.--.-----..+.<--.

Offline

#1416 2011-01-28 20:59:20

klixu
Member
Registered: 2009-10-29
Posts: 19

Re: Post your handy self made command line utilities

import sys, shutil, os

n=0
for  file in os.listdir('.'):
    type (file)
    if file.endswith('.zip')==True: 
        os.mkdir(file[:-4])
        shutil.move(file,  './'+file[:-4])
        n=n+1
    print 'moved %d files' ,  n
                

I invented the wheel umpteenth time once, it's a script to take a directory of zips and move them to subdirectories with the zips name, so that a.zip b.zip become a/a.zip b/b.zip

Offline

#1417 2011-01-30 16:52:47

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

Re: Post your handy self made command line utilities

Procyon wrote:

https://bbs.archlinux.org/viewtopic.php … 30#p864130
This is a script for Compiz' Enhanced Zoom Desktop.

I made some improvements to this script.

New:

  • `zoombm prev` : automatically zoom to the top-most entry in ~/.zoombm

  • In entry for x and y coordinates "orig+123 orig+10" : zoom to 123x10 from the top-left of the currently active window

  • --sync mode to avoid race condition bugs

  • Return the mouse to its original location after finishing the zoom

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

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

[[ -n "$1" && -n "$2" ]] && {
 x=$1
 y=$2
} || {
 [[ "$1" == prev ]] && {
  result=$(head -n 1 $bmfile)
  read name a b x y <<< "$result"
 } || {
  result=$(cat $bmfile | dmenu)
  read name a b x y <<< "$result"
 }
 [[ -z "$a" ]] && exit
 origmode=0
 if [[ ${a:0:5} = orig+ ]]; then
  a=${a:5}
  origmode=1
 fi
 if [[ ${b:0:5} = orig+ ]]; then
  b=${b:5}
  origmode=1
 fi
 if [[ $origmode = 1 ]]; then
  firstmove="mousemove --sync $(xwininfo -id $(xprop -root | grep NET_ACTIVE_WINDOW\( | cut -d# -f2) | grep Absolute\ upper | cut -d: -f2) mousemove_relative --sync $a $b"
 else
  firstmove="mousemove --sync $a $b"
 fi
 { # make it the new No.1
  echo "$result"
  grep -v "$result" $bmfile
 } > $bmfile.new
 mv $bmfile.new $bmfile
}

xdotool $firstmove \
keydown Super \
mousedown 3 \
mousemove_relative --sync $x $y \
mouseup 3 \
keyup Super \
mousemove_relative --sync -- -$x -$y \
mousemove --sync restore

Offline

#1418 2011-01-31 04:24:09

ewaller
Administrator
From: Pasadena, CA
Registered: 2009-07-13
Posts: 19,739

Re: Post your handy self made command line utilities

I am now using pulse audio and needed a way to increment, decrement or mute the volume in a way that could be bound to media keys in xfce4:

#!/bin/bash
oldvolume=$(pacmd dump|grep set-sink-volume|grep alsa |cut -f3 -d' ')
pacmd dump | grep set-sink-mute | grep alsa | grep yes > /dev/null
oldmute=$?
case $1 in

increase)
    newvolume=$(($oldvolume + 0x400))
    if (($newvolume >0x10000)) ; then
        newvolume=$((0x10000))
    fi
    pacmd set-sink-volume 0 $(printf '0x%x' $((newvolume)) ) 
    ;;

decrease)
    newvolume=$(($oldvolume - 0x400))
    if (($newvolume < 0 )) ; then
        newvolume=$((0x0000))
    fi
    pacmd set-sink-volume 0 $(printf '0x%x' $((newvolume)) ) 
    ;;

mute)
    if [[(($oldmute == 0))]] ; then
       pacmd set-sink-mute 0 0
    else
       pacmd set-sink-mute 0 1
    fi
    ;;
*)
    echo "usage pavolume increase | decrease | mute"
esac

Based on some one liners found on the net.  Assuming program is called pavolume:

pavolume increase
pavolume decrease
pavolume mute

Note that the last example toggles the mute state


Nothing is too wonderful to be true, if it be consistent with the laws of nature -- Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. -- Alan Turing
---
How to Ask Questions the Smart Way

Offline

#1419 2011-02-01 00:16:28

Jodell
Member
Registered: 2009-10-09
Posts: 285

Re: Post your handy self made command line utilities

@ ewaller

Thank you very much for the script. You're a life saver! big_smile

Offline

#1420 2011-02-01 16:34:46

rich_o
Member
Registered: 2008-07-28
Posts: 49

Re: Post your handy self made command line utilities

As it's cold outside i really watch a lot of tv series right now. I wrote a small but ugly zsh function to auto-choose the next file to play. It's far from elegant and i have a few ideas to improve and enhance it. I think it's ok for the 15 minutes of work i put into it.

mp is an alias to mplayer.ext, change all occurances to fit your player, e.g. mplayer.

# guess next file to play with mp
# TODO: handle errors
# TODO: check if next_file is a movie file
# TODO: check if last file in folder
# TODO: use full path
next()
{
    # get last occurance of mp in history, get rid of the number and mp
    last_para=$(history 1 | egrep -e "[0-9]  mp " | tail -n 1 |\
        awk '{for (i=3;i<NF+1;i++) printf("%s", $i)}')
    last_path=$(dirname ${last_para})
    next_file=$(ls -1 ${last_path} | grep -A 1 `basename ${last_para}`\
        | tail -n 1)    
    run="mp ${last_path}/${next_file}"
    # put it in history
    print -s -r -- ${run}
    print -s -r -- "next"
    # run it
    print ${run}
    mp ${last_path}/${next_file}
}

Offline

#1421 2011-02-08 12:05:53

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

Re: Post your handy self made command line utilities

I have the output of:

function router_ps1 {
    if [[ $( </proc/sys/net/ipv4/ip_forward ) == 1 ]]; then
        echo "-[0]- "
    fi
}

at the beginning of my BASH prompt in red. It lets me know when I am logged into a router and when I am not. Helps to let me know which machine I am on:

mike@mercury (0) pts/0 ~ $

-- or --

-[0]- mike@carbon (0) pts/0 ~ $

Offline

#1422 2011-02-20 09:26:54

masterkoppa
Member
Registered: 2009-04-14
Posts: 92

Re: Post your handy self made command line utilities

Here's a little script I wrote last night that gives me some system info. I run it with stdin widget from kde-look.org on my desktop, it's very light weight and while searching found nothing similar to it.

'''
Created on Feb 18, 2011

@author: andres
'''
import os, time, platform, pwd

def getTimeList():
    statFile = open("/proc/stat", "r")
    timeList = statFile.readline().split(" ")[2:6]
    statFile.close()
    for i in range(len(timeList))  :
        timeList[i] = int(timeList[i])
    return timeList

def deltaTime(interval)  :
    x = getTimeList()
    time.sleep(interval)
    y = getTimeList()
    for i in range(len(x))  :
        y[i] -= x[i]
    return y


dt = deltaTime(.1)
print("------------------------------------------")
print("|             Andres Desktop             |")
print("------------------------------------------")
print("OS:   " + platform.system() + " " + platform.release() + " " + platform.architecture()[0])
print("User: " + pwd.getpwuid(os.getuid())[0])
cpuPct = 100 - (dt[len(dt) - 1] * 100.00 / sum(dt))
print("CPU:  " + platform.processor())
print("RAM:  " + "Patriot 4 GB DDR2 1066 MHz")
print("------------------------------------------")
print("|              System Usage              |")
print("------------------------------------------")
print("CPU:  " + str('%.2f' %cpuPct) + "%")
memStream = os.popen("free -m")
mem = None
count = 1
for i in memStream:
    if count == 2:
        m = i.split()
        mem = str(m[2]) + "MB/" + str(m[1]) + "MB"
    count += 1
print("Ram:  " + mem)
stream = os.popen("nvidia-smi -a")
print("GPU:  NVidia 9800 GT Green Edition")
count = 1
for i in stream:
    i = i.split()
    if count == 16:
        print("   Temp:       " + str(i[-2] + i[-1]))
    elif count == 17:
        print("   Fan Speed:  " + str(i[-1]))
    elif count == 19:
        print("   GPU:        " + i[-1])
    elif count == 20:
        print("   Memory Use: " + i[-1])
    count += 1
print("------------------------------------------")
print("|              System Temps              |")
print("------------------------------------------")
sensorsStream = os.popen("sensors -f")
count = 1
cpu0_temp = ""
cpu1_temp = ""
acpi = ""
for i in sensorsStream:
    i = i.split()
    if count == 7:
        cpu0_temp = i[2][1:]
    if count == 11:
        cpu1_temp = i[2][1:]
    if count == 3:
        acpi = i[1][1:]
    count += 1
print("              Core1     Core2")
print("CPU Temps:   " + str(cpu0_temp) + "     " + str(cpu1_temp))
print()
print("Motherboard: " + acpi)
print("------------------------------------------")
print("|             Hard Drive Space           |")
print("------------------------------------------")
HDDStream = os.popen("df -h")
print("Mount Point         Used/Capacity       %")
count = 1
for i in HDDStream:
    if count > 4 or count == 3:
        line = i.split()
        space = ""
        for i in range(20-len(line[5])):
            space += " "
        space2 = ""
        for i in range(19-len(str(line[2] + "/" + line[1] + space2))):
            space2 += " "
        print(line[5] + space + line[2] + "/" + line[1] + space2 + line[4])
    count += 1

print("------------------------------------------")

I'm going to try and maybe expand this for more info. If you guys have any pointers let me know, I know there's a lot of hard coded stuff in there but I found that it was probably better for performance sakes...

Note: the code for the CPU time I got from searching, can't really find the website now. Anyway enjoy!

Offline

#1423 2011-02-20 12:39:46

botzoboy
Member
From: Romania/Deutschland
Registered: 2010-02-03
Posts: 90

Re: Post your handy self made command line utilities

some-guy94 wrote:

Mount/Unmount removable devices using udisks and dmenu

#!/bin/bash
# Credit goes to steve___ for help with cleaning this up
dmenu='dmenu -i'
all_devices=$(udisks --enumerate-device-files | grep /dev/sd)
selection=$(udisks --enumerate-device-files | grep /dev/sd | (while read dev; do
    info=$(udisks --show-info $dev)
    [[ $(awk '/system internal/ {print $3}'<<<"$info") == '0' ]] || continue
    [[ $(awk '/usage/ {print $2}'<<<"$info") == 'filesystem' ]]  || continue
    if [[ $(awk '/is mounted/ {print $3}'<<<"$info") == '0' ]]; then
        echo "mount:$dev"
    else
        echo "unmount:$dev"
    fi
done) | sort | $dmenu "$@")

[[ $selection ]] || exit 1

if [[ $selection == mount:* ]]; then
    exec udisks --mount ${selection#mount:}
else
    exec udisks --unmount ${selection#unmount:}
fi

This is a very usefull script, it will be great if you can extend it to mount/umount optical devices, floppy or mmc drives.
Thanks!

Offline

#1424 2011-02-20 14:51:41

ninian
Member
From: United Kingdom
Registered: 2008-02-24
Posts: 726
Website

Re: Post your handy self made command line utilities

botzoboy wrote:

This is a very usefull script, it will be great if you can extend it to mount/umount optical devices, floppy or mmc drives.
Thanks!

You might be interested in my extended version of this script called udsks
You'll notice that I've added optical drives at the top as "/dev/sr", and there's no reason you couldn't add floppy drives, etc too.
Udsks gives a bit more information and is less rigid in requiring udisks to report a filesystem on the device.

Hope this helps.
wink

Offline

#1425 2011-02-24 09:18:01

PReP
Member
From: Sweden
Registered: 2010-06-13
Posts: 359
Website

Re: Post your handy self made command line utilities

Here is a first (not actually first, but is/was the first "release-mature")
version of a handy music playing script i made for mplayer.

The idea is that it randomizes the songs from a given folder,
but the twist is that it does so with different set speeds each time it
plays a new song.

It might sound crazy, but it does not actually _sound_ that crazy,
it is within (i think atleast) sane upper and lower speed limits
and for me it makes any song sound like a new "version" each time smile

I most often use it to get some background music running while surfing, or doing something else.


I got it up to AUR aswell: https://aur.archlinux.org/packages.php?ID=41543


I am pondering whether is should make the syntax more "standard"-like,
with -switches or so.
And the name with an underscore i most often use to be extra certain that their won't be
any "name-collisions" or such.


I am quite new at bash, so this served as my second stab at it, and i have some ideas
on some improvements, what do you think?



#!/bin/bash

#
# PReP - RandomSpeedPlay 3.0
#
# This silly script randomizes two set of numbers,
# One for mplayer to play an mp3 with a random faster speed,
# And Another for playing it slower.
# Lastly It Randomized wheter using the "syntax" for lower of faster
# - And then invokes mplayer, the mp3 and the speed setting with the
# Randomized Variable. :)
#
# Thanks to gam, who solved the new (real) random-file-picker-thingie'.
#
# Syntax: prep_mp [Number of times to play] [directory-path to randomize in]
# (                                i.e $1 and $2                           )
#

RANGEONE=25
FLOORONE=0

RANGETWO=99
FLOORTWO=80

RANGETHREE=4
FLOORTHREE=1

HEARDMUSIC=0

PLAYMUSIC=$1

DONUMBERONE=0

echo
echo -e "     <----- \033[1m PReP Mp3-Random-Play 3.0 \033[0m ----->"
echo
echo " Syntax: prep_mp [times to play] [directory-path]"
echo
echo


if [ $PLAYMUSIC -lt 1  ]; then
echo "No times-to-play set - See Syntax"
echo
exit
fi


##################################


while [ $HEARDMUSIC -le $PLAYMUSIC ]

do

#RANDOM=$$

numberone=0

while [ "$numberone" -le $FLOORONE ]

do
  numberone=$RANDOM
  let "numberone %= $RANGEONE"
done


#################################

while [ $DONUMBERONE -lt 1 ]

do

if [ $numberone = 10 ]; then
    numberone="1.10"
break
fi 

if [ $numberone -lt 10 ]; then
    numberone="1.0${numberone}"
break
fi 

if [ $numberone -gt 10 ]; then
    numberone="1.${numberone}"
break
fi 

echo "numberone randomization went wrong somehow: $numberone"
exit

done

#################################


#RANDOM=$$

numbertwo=0

while [ "$numbertwo" -le $FLOORTWO ]

do
  numbertwo=$RANDOM
  let "numbertwo %= $RANGETWO"
done


##################################
##################################


#RANDOM=$$

THEDO=0

while [ "$THEDO" -le $FLOORTHREE ]

do
  THEDO=$RANDOM
  let "THEDO %= $RANGETHREE"
done


###################################################################

let HEARDMUSIC=HEARDMUSIC+1

if [ $HEARDMUSIC -gt $PLAYMUSIC ]; then
exit
fi

###################################################################


(

            IFS=$'\n' # Separate by newline 
     
            files=(`find $2 -type f -iname "*.mp3"`) 
            file_count=${#files[@]}      
            let "selected_num=$RANDOM % $file_count" 
     
            file=${files[$selected_num]} 
            #echo "$: $file" 


echo
echo -e "\E[33;40m <¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤>"
echo
echo -e "\E[32;40m  Playing: $HEARDMUSIC of $PLAYMUSIC times"
echo
echo -e "  File and mp3-pick/total: $file/$selected_num/$file_count"
echo


if [ $THEDO = 2 ]; then 

echo "  Using a higher speed/pitch of: $numberone"
echo
echo -e "\E[33;40m -----------------------------------------------------------"
echo
echo

mplayer -really-quiet -msgcolor -msglevel statusline=6 -vo none -speed $numberone $file

fi



if [ $THEDO = 3 ]; then 

echo "  Using a lower speed/pitch of: 0.$numbertwo"
echo
echo -e "\E[33;40m -----------------------------------------------------------"
echo
echo

mplayer -really-quiet -msgcolor -msglevel statusline=6 -vo none -speed 0.$numbertwo $file

fi


)


echo
echo ; tput sgr0


###################################################################


done

exit

Last edited by PReP (2011-02-24 09:21:53)


. Main: Intel Core i5 6600k @ 4.4 Ghz, 16 GB DDR4 XMP, Gefore GTX 970 (Gainward Phantom) - Arch Linux 64-Bit
. Server: Intel Core i5 2500k @ 3.9 Ghz, 8 GB DDR2-XMP RAM @ 1600 Mhz, Geforce GTX 570 (Gainward Phantom) - Arch Linux 64-Bit
. Body: Estrogen @ 90%, Testestorone @ 10% (Not scientific just out-of-my-guesstimate-brain)

Offline

Board footer

Powered by FluxBB