You are not logged in.

#226 2009-03-11 20:08:42

test1000
Member
Registered: 2005-04-03
Posts: 834

Re: Post your handy self made command line utilities

Daenyth wrote:

Procyon wrote:

    @Daenyth: Good idea. You know I find it really silly bash puts that * there.

http://wooledge.org:8000/BashFAQ/004

heh, had this discussion with people in #bash a little while ago.. where i proposed you can just use just use

echo ./*
echo $?

turns out you have to turn on failglob first though(shopt -s failglob) and i just tested now, also dotglob(shopt -s dotglob) if you want to test for .dotfiles


KISS = "It can scarcely be denied that the supreme goal of all theory is to make the irreducible basic elements as simple and as few as possible without having to surrender the adequate representation of a single datum of experience." - Albert Einstein

Offline

#227 2009-03-11 20:58:24

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

Can someone give me a little feedback on this mpc script? Any additional feature or bugfixes? http://gist.github.com/77731

EDIT: Perl version with many more features will be coming at some point; check back to the gist now and then. I just have to extend Audio::MPD to support more commands...

Last edited by Daenyth (2009-03-11 22:20:58)

Offline

#228 2009-03-11 22:05:42

test1000
Member
Registered: 2005-04-03
Posts: 834

Re: Post your handy self made command line utilities

Don't have mpc..(songbird finally supports m4a btw!)

here's the script i use the most tongue

#!/bin/bash
#DESC: Creates a script in proper dir, sets executable perm. and enters with vim. if file already exists open it in vim :-)

function exiT { echo include a scriptname or make a ~/bin dir; exit 1; }

{ cd && cd bin; } 2>/dev/null || exiT
if [ -n "$1" -a ! -f "$1" -a "$#" -eq 1 ]
then
        echo \#\!/bin/bash$'\n'\#DESC: "$1" > "$1"
        chmod +x "$1"
        vim "$1"
elif [ -f "$1" -a -n "$1" ]
then
        exec vim "$1"
else
        exiT
fi

I was going to post this to Community Contributions and maybe i will.. I have a bad feeling the date stuff could have been done easier though? oh well.

#!/bin/bash
#DESC: rollback. this script doesn't actually rollback anything yet but it gives you $0 number-of-days-back
# of the pacman log and colors it ugly just to be mean.. (;))
shopt -s extglob

if [[ $1 == +([0-9]) ]]
then
        yeaR=$(date +%Y)
        export LANG=C
        p_M=$(date --date="-${1} days"|cut -d " " -f 2)
        p_D=$(date --date="-${1} days"|cut -d " " -f 3)

        case $p_M in
                Jan)    p_M=01  ;;
                Feb)    p_M=02  ;;
                Mar)    p_M=03  ;;
                Apr)    p_M=04  ;;
                May)    p_M=05  ;;
                Jun)    p_M=06  ;;
                Jul)    p_M=07  ;;
                Aug)    p_M=08  ;;
                Sep)    p_M=09  ;;
                Oct)    p_M=10  ;;
                Nov)    p_M=11  ;;
                Des)    p_M=12  ;;
        esac

# COLORS
removeD=$(tput setaf 1)
installeD=$(tput setaf 3)
upgradeD=$(tput setaf 4)
synC=$(tput setaf 5)
fG=$(tput setaf 7)
otheR=$(tput setaf 0)

        sed -n "/${yeaR}-${p_M}-${p_D}/,\$p" /var/log/pacman.log| \
        sed -e "s/.*/${otheR}&${fG}/" \
        -e "s/synchronizing package lists/${synC}&${fG}/" \
        -e "s/starting full system upgrade/${synC}&${fG}/" \
        -e "s/removed.*/${removeD}&${fG}/" \
        -e "s/installed.*/${installeD}&${fG}/" \
        -e "s/upgraded.*/${upgradeD}&${fG}/"
        # download selected files
else
        echo you need to run the program like $(basename "${0}") [daysback]
fi

then there's diffwithcolor because the diff with color perl program didn't work properly(and is like 500 lines or something..)

#!/bin/bash
# diffwithcolor - gives you colored diffs :)

OLD=$(tput setaf 1) # red
SAMELINE=$(tput setaf 4) # blue
NEW=$(tput setaf 2) # green

diff -W 180 -w -y --suppress-common-lines $1 $2|sed "s#\(.*|.*\)#`echo $SAMELINE`&#"|sed "s#\(.*>.*\)#`echo $NEW`&#"|sed "s#\(.*<.*\)#`echo $OLD`&#"

edit: posted the right script #1 tongue

Last edited by test1000 (2009-03-17 09:13:42)


KISS = "It can scarcely be denied that the supreme goal of all theory is to make the irreducible basic elements as simple and as few as possible without having to surrender the adequate representation of a single datum of experience." - Albert Einstein

Offline

#229 2009-03-12 11:43:54

scj
Member
From: Sweden
Registered: 2007-09-23
Posts: 158

Re: Post your handy self made command line utilities

#!/bin/bash
#shutup: stores the volume and temporarily pauses mpd

volume=$(mpc volume | tr -d '[:alpha:]:% ')
cmd=$1
shift
args=("$@")
mpc pause > /dev/null
$cmd "${args[@]}"
mpc volume $volume > /dev/null
mpc play > /dev/null

I use it whenever I'm going to watch something and mpd happens to be running.

Offline

#230 2009-03-15 11:11:40

initbox
Member
Registered: 2008-09-27
Posts: 172

Re: Post your handy self made command line utilities

I decided to make a completely graphical script to control every aspect of my Samsung NC10.

Depends on xdialog, which, atleast for me, was a 0.30mb download.

Remember to add your own nameservers if you use 3G! Also, adding the command to your sudoers makes it easy to initiate this command as a lowly user!

Command:
whateveryounameit (completely interactive)
whateveryounameit add|rm|cmd (goes straight to add|rm|cmd)
whateveryounameit add lan (etc, completely automatic and only notifies you with a popup)

#!/bin/sh
touch /dev/shm/nc10;
tempfile=/dev/shm/nc10
title=$0
args=""
param=""
command=""

adder () {
    if [ -z $args ]; then
        Xdialog --title "$title" --stdout --menubox "What would you like to activate?" 0 0 5 "LAN" "" "WLAN" "" "Bluetooth" "" "3G" "" 1> $tempfile;
        command=`cat $tempfile`
    else
        command=$args
    fi

    case $command in
        LAN|lan)
        Xdialog --title "$title" --msgbox "Activated LAN." 0 0 &>/dev/null &
        modprobe sky2;
        /etc/rc.d/network start;
        ;;
        WLAN|wlan)
        Xdialog --title "$title" --msgbox "Activated WLAN." 0 0 &>/dev/null &
        modprobe ath5k;
            /etc/rc.d/network stop &>/dev/null &
        /etc/rc.d/dbus start &>/dev/null &
        /etc/rc.d/wicd start &>/dev/null &
        ;;
        Bluetooth|bt)
        Xdialog --title "$title" --msgbox "Activated Bluetooth." 0 0 &>/dev/null &
        modprobe btusb;
        modprobe bluetooth;
        ;;
        3G|3g)
        #Xdialog --title "$title" --msgbox "Activated 3G." 0 0 &>/dev/null &
        Xdialog --no-cancel --logbox $tempfile 0 0 &>/dev/null &
        modprobe ppp-generic;
        echo 'nameserver 1.2.3.4' > /etc/resolv.conf;
        echo 'nameserver 4.3.2.1' >> /etc/resolv.conf;
        wvdial &>$tempfile;
        ;;
        *)
        if [ -z $command ]; then
        Xdialog --title "$title" --msgbox "Action cancelled!" 0 0 &>/dev/null &
        else
        Xdialog --title "$title" --msgbox "Invalid action '$command'!" 0 0 &>/dev/null &
        fi
        ;;
        esac
}

remover () {
    if [ -z $args ]; then
        Xdialog --title "$title" --stdout --menubox "What would you like to inactivate?" 0 0 5 "LAN" "" "WLAN" "" "Bluetooth" "" "3G" "" 1> $tempfile;
        command=`cat $tempfile`
    else
            command=$args
    fi
    
    case $command in
        LAN|lan)
        Xdialog --title "$title" --msgbox "Inactivated LAN." 0 0 &>/dev/null &
        /etc/rc.d/network stop;
        rmmod sky2;
        ;;
        WLAN|wlan)
        Xdialog --title "$title" --msgbox "Inactivated WLAN." 0 0 &>/dev/null &
        /etc/rc.d/network stop &>/dev/null &
        /etc/rc.d/wicd stop &>/dev/null &
        /etc/rc.d/dbus stop &>/dev/null &
        rmmod ath5k;
        ;;
        Bluetooth|bt)
        Xdialog --title "$title" --msgbox "Inactivated Bluetooth." 0 0 &>/dev/null &
        rmmod btusb;
        rmmod bluetooth;
        ;;
        3G|3g)
        Xdialog --no-cancel --logbox $tempfile 0 0 &>/dev/null &
        pkill wvdial &>$tempfile &
        rmmod bsd_comp;
        rmmod ppp_async;
        rmmod ppp_deflate;
        rmmod zlib_deflate;
        rmmod zlib_inflate;
        rmmod ppp_generic;
        ;;
        *)
        if [ -z $command ]; then
        Xdialog --title "$title" --msgbox "Action cancelled!" 0 0 &>/dev/null &
        else
        Xdialog --title "$title" --msgbox "Invalid action '$command'!" 0 0 &>/dev/null &
        fi
        ;;
    esac
}

cmd () {
    if [ -z $args ]; then
        Xdialog --title "$title" --stdout --menubox "What command would you like to perform?" 15 50 5 "Suspend" "- to RAM" "Hibernate" "- to HDD" "Backlight" "- laptop backlight" "Sound" "- soundlevels" "Powersave" "- set cpufreq to 'powersave'" "OnDemand" "- set cpufreq to 'ondemand'" 1> $tempfile;
        command=`cat $tempfile`
    else
            command=$args
    fi
    
    case $command in
        Suspend|susp)
        Xdialog --title "$title" --msgbox "Suspending to RAM." 0 0 &>/dev/null &
        pm-suspend;
        ;;
        Hibernate|hibe)
        Xdialog --title "$title" --msgbox "Hibernating to HDD." 0 0 &>/dev/null &
        pm-hibernate;
        ;;
        Backlight|back)
        Xdialog --title "$title" --stdout --rangebox "Backlight:" 0 0 0 100 30 1> $tempfile;
        xbacklight -set `cat $tempfile`
        ;;
        Sound|snd)
        Xdialog --title "$0" --stdout --separator " " --3rangesbox "Volume:" 0 0 "Master" 0 100 80 "PCM" 0 100 100 "Front" 0 100 100 1> $tempfile;
        #| sed 's/\// /g' 1> $tempfile;
        amixer -q set Master unmute
        amixer -q set Master `cat $tempfile | awk '{print $1}'`%
        amixer -q set PCM `cat $tempfile | awk '{print $2}'`%
        amixer -q set Front `cat $tempfile | awk '{print $3}'`%
        ;;
        Powersave)
        Xdialog --title "$title" --msgbox "Setting cpufreq to 'powersave'." 0 0 &>/dev/null &
        cpufreq-set -g powersave;
        ;;
        OnDemand)
        Xdialog --title "$title" --msgbox "Setting cpufreq to 'ondemand'." 0 0 &>/dev/null &
        cpufreq-set -g ondemand;
        ;;
        *)
        if [ -z $command ]; then
        Xdialog --title "$title" --msgbox "Action cancelled!" 0 0 &>/dev/null &
        else
        Xdialog --title "$title" --msgbox "Invalid action '$command'!" 0 0 &>/dev/null &
        fi
        ;;
    esac
    
}

if [ $# -eq 0 ]; then
    Xdialog --title "$title" --stdout --menubox "What action would you like to perform?" 0 0 5 "Add" "" "Remove" "" "Command" "" 1> $tempfile;
    param=`cat $tempfile`
else
        param=$1
        if [ $# -eq 2 ]; then
        args=$2
        fi
fi

case $param in
    Add|add)
    adder
    ;;
    Remove|rm)
    remover
    ;;
    Command|cmd)
    cmd
    ;;
    *)
    Xdialog --title "$title" --msgbox "invalid parameter '$1' or operation cancelled." 0 0;
    ;;
esac

Last edited by initbox (2009-03-15 11:12:52)

Offline

#231 2009-03-15 15:55:25

simongmzlj
Member
From: Canada
Registered: 2008-11-06
Posts: 135

Re: Post your handy self made command line utilities

Following scripts are all inspired from other ones here; nothing really original

Use dmenu to play artist

#!/bin/sh

cmd="$(mpc ls | dmenu ${1+"$@"})"

if [ -f ~/Music/"$cmd" ] || [ -d ~/Music/"$cmd" ] && [ -n "$cmd" ]
then
  mpc clear & mpc add "$cmd"
  mpc play
fi

Use dmenu to select netcfg profile

#!/bin/sh

cmd="$(ls /etc/network.d/ -1Ap | grep -v /\$ | dmenu ${1+"$@"})"

if [ -n "$cmd" ]
then
    netcfg -a
    netcfg $cmd
fi

mpd/mplayer status; current song playing through mpd or the filename of whats playing in mplayer

#!/bin/bash

title=$(mpc | awk '/-/ {print $0}')
textp=$(mpc | gawk '/play/ {print $3,$4}')

if [ "${#title}" -eq 0 ]    
then
    mplayer=$(pgrep -d ' ' mplayer)
    if [ "${mplayer}" ]
    then
        proc_file="/proc/$mplayer/cmdline"
        title=$(cat $proc_file | sed 's/^mplayer//g')
        
        echo -n "MPlayer: $title"
    else
        echo -n "Nothing playing"
    fi
else
    echo -n $title
    [ "${#textp}" -eq 0 ] && echo -n " *paused*" 
fi
echo ""

dwm bar; prints useful information: song playing, battery, weather, time

#!/bin/bash

counter=0

while true
do
    #update the weather every 15 minutes - every 2 seconds it too often
    counter=$((counter%900))
    flag=""
    if [ "$counter" -eq 0 ]
    then
        weather=$(weatherget -s CAXX0531 -m -f .weatherget-minimalrc) 
        flag=" *updated*"
    fi

    xsetroot -name "$(./mpd-stat) :: $(acpi | awk '{ print $3, $4 }' | sed s/","//g) :: $weather$flag :: $(date +"%R - %D")"

    sleep 2
    counter=$counter+2
done

script to enable some agressive power saving features. really helps battery life. when turned on with the wireless off, powertop reports 10W, which translates to a comfortable 4 hours of battery life.

#!/bin/bash

case $1 in
    "off")
        # backlight
        echo 8 > /sys/class/backlight/acpi_video0/brightness

        # harddrive settings
        echo 0 > /proc/sys/vm/laptop_mode
        echo 10 > /proc/sys/vm/dirty_ratio
        echo 5 > /proc/sys/vm/dirty_background_ratio
        echo 500 > /proc/sys/vm/dirty_writeback_centisecs

        # soundcard settings
        echo 0 > /sys/module/snd_hda_intel/parameters/power_save

        # network settings
        ethtool -s eth0 autoneg on speed 1000 > /dev/null
        ethtool -s eth0 wol d > /dev/null

        # hal settings
        hal-disable-polling --device /dev/cdrom --enable-polling > /dev/null
        ;;
    "on")
        # backlight
        echo 0 > /sys/class/backlight/acpi_video0/brightness

        # harddrive settings
        echo 5 > /proc/sys/vm/laptop_mode
        echo 40 > /proc/sys/vm/dirty_ratio
        echo 10 > /proc/sys/vm/dirty_background_ratio
        echo 1500 > /proc/sys/vm/dirty_writeback_centisecs

        # soundcard settings
        echo 10 > /sys/module/snd_hda_intel/parameters/power_save

        # network settings
        ethtool -s eth0 autoneg off speed 100 > /dev/null
        ethtool -s eth0 wol d > /dev/null

        # hal settings
        hal-disable-polling --device /dev/cdrom > /dev/null
        ;;
esac

Offline

#232 2009-03-15 15:58:42

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

Offline

#233 2009-03-16 16:55:46

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

Re: Post your handy self made command line utilities

Small edit to my atq replacement, now it will display the remaining amount of hours:minutes:seconds instead of the day and time.
So
-00:37:30> echo test
And once again it needs read & execute permission of /var/spool/atd, and it is currently set to only display one line of the command too.

#! /bin/bash
for file in /var/spool/atd/*; do
[ ! -f "$file" ] && echo no atd jobs && exit
awk -W non-decimal-data '{time=$1*60 - systime(); minutes=time%3600/60; hours=time/60/60; seconds=time%60;printf "-%02d:%02d:%02d> ",hours,minutes,seconds }' <<< "0x$(cut -b22- <<< $file)"
sed -n '/}/{n;p}' "$file"
done

edit: fixed hour and minute display

Last edited by Procyon (2009-03-23 14:55:24)

Offline

#234 2009-03-17 01:56:25

Fingel
Member
Registered: 2009-02-28
Posts: 98

Re: Post your handy self made command line utilities

This thread has some really great stuff in it, stuff that is the reason why I love to use linux - custom scripting that doesnt suck!
I realize im not the first to think having a central repository for this would be a good idea. There is the script wiki. But no offense to whoever made the script wiki but it kinda sucks. Its hard to navigate and use because it hasn't really be modified at all. So I present to you:

http://www.toxiccode.com/sscript.php

Its very streamlined and designed for the purpose, I coded it from scratch using PHP (if anyone wants to see the source let me know tongue )
Pick out a username and pass and you can post your scripts/config files/ other stuff as well as rate and comment on others.
I will be adding more features soon such as user pages, search and sortby links. Hope you guys like it.

I took some of the scripts and added them to the page to get it started, giving full credit to the original authors. If I posted your script and you want me to take it down just let me know.

Of course feedback is always welcome and desired.

Offline

#235 2009-03-17 15:42:09

initbox
Member
Registered: 2008-09-27
Posts: 172

Re: Post your handy self made command line utilities

I know some people wanted something like this some time ago and I decided to practice bash arithmetics, so here you go:

This program executes some action once the current song playing in your mpd is finished.
For example: lolscript "shutdown -h now" - remember the quotes!

#!/bin/sh
#### MPD song changing action ####
#### execute a command when mpd changes songs ####
#### Usage: commandname "command"; for example: mympdscript "shutdown -h now" ####

min1=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $1}'`
min2=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $3}'`
s1=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $2}'`
s2=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $4}'`
rdy=
cmd=$1

while [ $min1 -ne 0 ]; do
    let s1=$s1+60
    let min1=$min1-1
done

while [ $min2 -ne 0 ]; do
    let s2=$s2+60
    let min2=$min2-1
done

let rdy=$s2-$s1
sleep $rdy; $cmd

Offline

#236 2009-03-17 20:22:57

fflarex
Member
Registered: 2007-09-15
Posts: 466

Re: Post your handy self made command line utilities

@initbox: I wrote a very similar script here, with a few more features as well. But as someone who doesn't know awk at all, I don't understand your script. Does it handle song changes when the next song has an identical title and artist? Because I have been trying to figure out how to do that without complicating my script too much (and also without requiring too much effort).

Offline

#237 2009-03-17 20:30:20

initbox
Member
Registered: 2008-09-27
Posts: 172

Re: Post your handy self made command line utilities

fflarex wrote:

@initbox: I wrote a very similar script here, with a few more features as well. But as someone who doesn't know awk at all, I don't understand your script. Does it handle song changes when the next song has an identical title and artist? Because I have been trying to figure out how to do that without complicating my script too much (and also without requiring too much effort).

My script just counts when the current song ends and then executes something. It's very simple ^^

Awk is only used to parse the track elapsed/length from mpc status.

Offline

#238 2009-03-20 00:58:10

Killa B
Member
From: United States
Registered: 2008-10-28
Posts: 42
Website

Re: Post your handy self made command line utilities

I've got a really simple, but very effective script. Well, it's not technically even a script...

lsi - case insensitive ls (place in ~/.bashrc)

alias lsi='ls | grep -i'

Example usage:

socrates@localhost ~/Shared/audio $ lsi redman
De La Soul  ft.Redman - Oooh.mp3
Keith Murray - Yeah, Yeah, You Know It (feat. Erick Sermon & Redman).mp3
LL Cool J - 4, 3, 2, 1 (Feat. Method Man, Redman, Canibus & DMX).mp3
Method Man & Redman - Broken Language 2008.mp3
Method Man & Redman - Lets Get Dirty.mp3
Method Man & Redman feat. Damian Marley (Jr. Gong) - Lyrical .44.mp3
Method Man, Redman, & Busta Rhymes - Simon Says Remix .mp3
Methode Man & Redman - Americas Most.mp3
Redman - Cant Wait.mp3
Redman - Ill Be Dat.mp3
Redman feat. Busta Rhyme - Da Goodness.mp3
WEED SMOKER - Styles P feat Jin, Redman & Method Man - Good Times (I Get High) unreleased remix.mp3

Offline

#239 2009-03-20 01:03:04

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

You can get the same behavior by «ls *redman*», assuming that you have nocaseglob set.

Offline

#240 2009-03-20 14:24:00

initbox
Member
Registered: 2008-09-27
Posts: 172

Re: Post your handy self made command line utilities

Here's another script! tongue

This one leverages the previous mpd-action script as a function.

It will execute a command when your mpd playlist ends. Sometimes it whines about errors and sometimes it doesn't, but it works every time so I don't really care.

scriptname "echo yay finished playing!"

#!/bin/sh
#### Wait until mpd playlist ends and execute action ####
#### example: scriptname "echo yay finished playing!" ####

last=`mpc playlist | wc -l`
action=$1

sleeper () {
min1=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $1}'`
min2=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $3}'`
s1=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $2}'`
s2=`mpc status | awk 'NR==2' | awk '{print $3}' | tr "[:,/]" " " | awk '{print $4}'`
end=

while [ $min1 -ne 0 ]; do
    let s1=$s1+60
    let min1=$min1-1
done

while [ $min2 -ne 0 ]; do
    let s2=$s2+60
    let min2=$min2-1
done

let end=$s2-$s1
sleep $end
}

while [[ $np != $last ]]; do
    np=`mpc | awk 'NR==2' | tr -d '[A-Za-z\#]' | sed 's/\// /g' | awk '{print $1}'`
    sleeper
done

sleeper
$action

Offline

#241 2009-03-20 14:25:22

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

Eep.. where to begin... I'll take a little time and remake that for you

EDIT: Nevermind.. I'd recommend a total rewrite of it from scratch. Probably in pure awk or perl. (I'd use perl + Audio::MPD)

Last edited by Daenyth (2009-03-20 14:38:54)

Offline

#242 2009-03-20 19:07:04

initbox
Member
Registered: 2008-09-27
Posts: 172

Re: Post your handy self made command line utilities

Daenyth wrote:

Eep.. where to begin... I'll take a little time and remake that for you

EDIT: Nevermind.. I'd recommend a total rewrite of it from scratch. Probably in pure awk or perl. (I'd use perl + Audio::MPD)

Hehe, I can't program Perl at all.

But yeah, I guess it's a sucky script, kind of. I'm just trying to do random bash scripts so I can practice.

I'd actually really like to start programming, but trying to figure out something to program is a tedious task. I like bash scripting, it's kind of like writing simple websites, you can see the results immediately and you can actually do something useful as well. But then again I really, REALLY want to learn programming, it's just that I don't really like writing useless programs just for the sake of it.

(Random babbling, heh.)

Offline

#243 2009-03-20 19:09:16

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

Look at project Euler... it might be a handy place to start.

Offline

#244 2009-03-21 14:17:50

rwd
Member
Registered: 2009-02-08
Posts: 664

Re: Post your handy self made command line utilities

Fingel wrote:

This thread has some really great stuff in it, stuff that is the reason why I love to use linux - custom scripting that doesnt suck!

To be fair Windows has shellscripting too (WSH/Powershell/Python/PHP/etc..). But with bash combined with all the commandline tools you can do a lot in a few lines of code that would take a whole page of those other scripting languages.

Offline

#245 2009-03-21 15:18:15

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Post your handy self made command line utilities

rwd wrote:

To be fair Windows has shellscripting too (WSH/Powershell/Python/PHP/etc..). But with bash combined with all the commandline tools you can do a lot in a few lines of code that would take a whole page of those other scripting languages.

Yeah, this is true. I memorized the following single line batch script during my high school networking class. Since Windows doesn't have an IP scanner by default, I created this for simple host discovery. It scans an entire Class C network range. More loops can be added for class B or A, obviously.

( for /l %a in (1,1,254) do ( for /f %b in ('ping -n 1 -w 1 192.168.1.%a') do ( if "%b" equ "Reply" ( echo 192.168.1.%a>>tmp )))) && ( cls && echo Found && type tmp && del tmp )

Offline

#246 2009-03-21 15:28:24

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

Why not just install nmap?

Offline

#247 2009-03-21 17:23:03

wimac
Member
From: Michigan, USA
Registered: 2008-06-06
Posts: 20
Website

Re: Post your handy self made command line utilities

a better df

#!/bin/bash

# newdf - a friendlier version of df

sedscript="/tmp/newdf.$$"

trap "rm -f $sedscript" EXIT

cat << 'EOF' > $sedscript
function showunit(size)
{ mb = size / 1024; prettymb=(int(mb * 100)) / 100;
  gb = mb / 1024; prettygb=(int(gb * 100)) / 100;

  if ( substr(size,1,1) !~ "[0-9]" ||
       substr(size,2,1) !~ "[0-9]" ) { return size }
  else if ( mb < 1) { return size "K" }
  else if ( gb < 1) { return prettymb "M" }
  else              { return prettygb "G" }
}

BEGIN { 
  printf "%-27s %7s %7s %7s %8s  %-s\n",
    "Filesystem", "Size", "Used", "Avail", "Capacity", "Mounted"
}

!/Filesystem/ {

  size=showunit($2); 
  used=showunit($3); 
  avail=showunit($4);

  printf "%-27s %7s %7s %7s %8s  %-s\n",
    $1, size, used, avail, $5, $6
}
EOF

df -k | awk -f $sedscript

exit 0

.wimac

//screenshots//configs//

Offline

#248 2009-03-21 17:45:26

GraveyardPC
Member
Registered: 2008-11-29
Posts: 99

Re: Post your handy self made command line utilities

Daenyth wrote:

Why not just install nmap?

I carried around a thumb drive with nmap and much more when I could, but this works well if you're caught without any tools and no Internet access.

Offline

#249 2009-03-21 22:07:08

Daenyth
Forum Fellow
From: Boston, MA
Registered: 2008-02-24
Posts: 1,244

Re: Post your handy self made command line utilities

I present to you torso, the missing link between "head" and "tail"

Usage: torso N [-n M] [FILE]
Prints M lines (default 10) from FILE (or STDIN if FILE is not given), starting at line N

Offline

#250 2009-03-21 22:28:47

colbert
Member
Registered: 2007-12-16
Posts: 809

Re: Post your handy self made command line utilities

I really like this idea, how would I use it though? Add to .bashrc or have as separate script?

Thanks

Daenyth wrote:

Here's my version of the filetype-agnostic extractor... Dependencies are pacman, bzip2, gzip, p7zip. It also supports tar, gzip, bzip2, cpio, zip, 7zip, rar. Probably others as well..

ex() {
    for file in "$@"; do
        if [ -f "$file" ]; then
            local file_type=$(file -bizL "$file")
            case "$file_type" in
                *application/x-tar*|*application/zip*|*application/x-zip*|*application/x-cpio*)
                    bsdtar -x -f "$file" ;;
                *application/x-gzip*)
                    gunzip -d -f "$file" ;;
                *application/x-bzip*)
                    bunzip2 -f "$file" ;;
                *application/x-rar*)
                    7z x "$file" ;;
                *application/octet-stream*)
                    local file_type=$(file -bzL "$file")
                    case "$file_type" in
                        7-zip*) 7z x "$file" ;;
                        *) echo -e "Unknown filetype for '$file'\n$file_type" ;;
                    esac ;;
                *)
                    echo -e "Unknown filetype for '$file'\n$file_type" ;;
            esac
        else
            echo "'$file' is not a valid file"
        fi
    done
}

Offline

Board footer

Powered by FluxBB