You are not logged in.

#2276 2014-01-06 13:54:04

wirr
Member
Registered: 2009-10-25
Posts: 70

Re: Post your handy self made command line utilities

Spawn many xephyrs:

xinitwm() {
        max=10
        start=10
        resolution=${2:-936x1040}
        let end="$start+$max-1"
        for display in $(seq $start $end) ; do
                if ! [ -f "/tmp/.X${display}-lock" ] ; then
                        startx ~/.xinitrc $1 -- /usr/bin/Xephyr :$display -screen $resolution -host-cursor
                        return
                fi
        done
        echo "There are already $max Xephyrs running, you might want to check one of them."
}

To be able to chose the wm, you have to put somethin like that in your .xinitrc:

wm=${1:-hlwm}
case $wm in
  1|i3)
    sh ~/.fehbg &
    exec i3
    ;;
  2|hlwm)
    exec herbstluftwm --locked
    ;;
esac

Offline

#2277 2014-01-13 19:22:53

vik_k
Member
From: Pune, India
Registered: 2009-07-12
Posts: 227
Website

Re: Post your handy self made command line utilities

Another update to my old tpb downloader script.

Sorta changelog:
- hardcoded ip address of tpb
- added some more switches for sorting/filtering
- can provide download ranges (hyphen separated) and multiple downloads (comma separated)
  - like -> 1,2-5,10

Usage

pb -utd user    (latest uploaded first)"
pb -uti user    (oldest uploaded first)"
pb -usd user    (most seeders first)"
pb -usi user    (least seeders first)"
pb -td  pattern (latest first)"
pb -ti  pattern (oldest first)"
pb -sd  pattern (most seeders first)"
pb -si  pattern (least seeders first)"
#!/usr/bin/bash
#
# v-k 2013
# torrent downloader from tpb
###
# set -x

error_out() {
  echo "==> $@"
  clean_up
}

clean_up() {
  rm -rf "$tmp_dir"
  printf '\033[?25h'
  exit
}

message() {
  echo "usage: ${0##*/} <option> pattern"
  echo "option -utd user    (latest uploaded first)"
  echo "       -uti user    (oldest uploaded first)"
  echo "       -usd user    (most seeders first)"
  echo "       -usi user    (least seeders first)"
  echo "       -td  pattern (latest first)"
  echo "       -ti  pattern (oldest first)"
  echo "       -sd  pattern (most seeders first)"
  echo "       -si  pattern (least seeders first)"
  exit
}

search_pb() {
  local str cntr
  str="$1"
  cntr=$2

  [[ -f "$tmp_dir/tpb.1.test.$cntr" ]] || curl -s "${url}/${str// /%20}/$cntr/$sort/0" > "$tmp_dir/tpb.1.test.$cntr"
  sed -n '/class="detName"/ {p;n;n;p;n;p;n;n;p;n;p;}' "$tmp_dir/tpb.1.test.$cntr" > "$tmp_dir/tpb.2.test"
  sed -n '/class="detName"/ s/.*>\(.*\)<\/a>/\1/p; n; s/^<a href="\(.*\)" title="Download this torrent using magnet.*/\1/p; n; s/.*Uploaded \(.*\)\&nbsp\;\(.*\), Size \(.*\)\&nbsp\;\(.*\), ULed.*>\(.*\)<\/[ai]>.*/\1 \2|\3\4|\5/gp; n; s/[^0-9]//gp; n; s/[^0-9]//gp;' "$tmp_dir/tpb.2.test" > "$tmp_dir/tpb.result"
  sed -i '1,${N;N;N;N;s/\n/|/g}' "$tmp_dir/tpb.result"
}

display_res() {
  width=$(cut -d"|" -f1 "$tmp_dir/tpb.result" | wc -L)
  divider="$(printf "%-$(($width+71))s" " ")"
  i=1
  printf "\n $(tput bold)$(tput setaf 3)%2.2b | %-${width}.${width}s | %11.11b | %9.9b | %8.8b | %6.6b | %15.15b |$(tput sgr0)\n" " #" "NAME ($cmd_arg) - (Pg #$((pg_cntr+1)))" "DATE" "SIZE" "SEEDS(!)" "LEECHS" "UPLOADED BY"
  echo "${divider// /=}+"
  while read NAME LINK DATE SIZE ULDR SEED LEECH; do
    [[ ${#DATE} -ne 11 ]] && DATE="${DATE// /  }"
    printf " %2.2b | %-${width}.${width}s | %11.11b | %9.9b | $(tput setaf 2)%8.8b$(tput sgr0) | $(tput setaf 1)%6.6b$(tput sgr0) | %15.15b |\n" "$i" "$NAME" "$DATE" "$SIZE" "$SEED" "$LEECH" "$ULDR"
    ((i++))
  done < "$tmp_dir/tpb.result"
  echo "${divider// /=}+"
}

download() {
  IFS=","
  for i in $sel; do
    [[ $i =~ - ]] && \
      { start=$(echo $i | cut -d- -f1); end=$(echo $i | cut -d- -f2); echo "$(head -n $end "$tmp_dir/tpb.result" | tail -n $(($end-$start+1)) | cut -d"|" -f2)" >> "$tmp_dir/links"; } || \
      { echo "$(head -n $i "$tmp_dir/tpb.result" | tail -n 1 | cut -d"|" -f2)" >> "$tmp_dir/links"; }
  done
  IFS="$IFS_BAK"
}

# main starts here
[[ -x /usr/bin/aria2c ]] || error_out "aria2c is needed for getting metadata from magnet links"

trap 'clean_up' INT TERM EXIT

[[ $# -eq 2 ]] || message

url="http://194.71.107.80/search"

case $1 in
  -td)  sort=3;;
  -sd)  sort=7;;
  -utd) url="http://194.71.107.80/user"; sort=3;;
  -usd) url="http://194.71.107.80/user"; sort=7;;
  -ti)  sort=4;;
  -si)  sort=8;;
  -uti) url="http://194.71.107.80/user"; sort=4;;
  -usi) url="http://194.71.107.80/user"; sort=8;;
   *)  error_out "invalid option";;
esac

shift
tmp_dir="$(mktemp -d)"
cmd_arg="$1"
pg_cntr=0
printf '\033[?25l'

while true; do
  clear
  search_pb "$cmd_arg" $pg_cntr

  IFS_BAK="$IFS"
  IFS="|"
  display_res
  IFS="$IFS_BAK"

  echo
  echo -n "Enter selection: "
  read sel

  case $sel in
    ""|d)
      [[ -s "$tmp_dir/links" ]] && : || error_out "exiting !!!";
      ;;
    n)
      ((pg_cntr++)); continue;
      ;;
    b)
      ((pg_cntr--)); continue;
      ;;
    *)
      download; continue;
      ;;
  esac

  echo '... downloading metadata ...'
  aria2c --bt-metadata-only --bt-save-metadata -i "$tmp_dir/links" | perl -ne 'print if s/Saved/\033[0;32m$&\033[0m/' # &> "$tmp_dir/aria2_result" &
#   pid=$!
#
#   while kill -0 $pid &> /dev/null; do
#     printf "[.   ] Downloading torrents !!\r"
#     sleep .2s
#     printf "[ .  ] Downloading torrents !!\r"
#     sleep .2s
#     printf "[  . ] Downloading torrents !!\r"
#     sleep .2s
#     printf "[   .] Downloading torrents !!\r"
#     sleep .2s
#     printf "[  . ] Downloading torrents !!\r"
#     sleep .2s
#     printf "[ .  ] Downloading torrents !!\r"
#     sleep .2s
#   done
#
#   clear
#   echo
#   sed -n '/Download Results/,$p' "$tmp_dir/aria2_result"
  echo
  break
done

Last edited by vik_k (2014-01-13 19:23:43)


"First learn computer science and all the theory. Next develop a programming style. Then forget all that and just hack." ~ George Carrette

Offline

#2278 2014-01-15 01:24:54

esko997
Member
From: Connecticut, USA
Registered: 2014-01-13
Posts: 22

Re: Post your handy self made command line utilities

Hey all,

Yeah so this little thing I made isent really anything special, I just got tired of having to directly go to Google in the dwb browser if I wanted to search something so I wrote this for the command line:

#!/bin/bash

# This script takes user input and then uses it to search google.

echo "Enter your search terms: "
read search

searchRefine=$(echo $search | sed -e 's/ /_/g')

dwb https://www.google.com/#q=$searchRefine

I think it'll work for other browsers if you just replace dwb with "your-browser-here"

Cheres,

Esko

Offline

#2279 2014-01-15 01:30:45

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

Re: Post your handy self made command line utilities

No need for a script, a function is enough:

$ type g
g is a function
g () 
{ 
    $BROWSER "http://www.google.com/search?&num=100&q=$*"
}

Edit: I think dwb has a shortcut for searching, so you don't have to go to google.com first.

Last edited by karol (2014-01-15 01:32:01)

Offline

#2280 2014-01-15 02:42:00

HalosGhost
Forum Moderator
From: Twin Cities, MN
Registered: 2012-06-22
Posts: 2,095
Website

Re: Post your handy self made command line utilities

This might also be the perfect time to look into surfraw.

All the best,

-HG

Offline

#2281 2014-01-15 02:44:20

ANOKNUSA
Member
Registered: 2010-10-22
Posts: 2,141

Re: Post your handy self made command line utilities

esko997 wrote:

Hey all,

Yeah so this little thing I made isent really anything special, I just got tired of having to directly go to Google in the dwb browser if I wanted to search something so I wrote this for the command line:

#!/bin/bash

# This script takes user input and then uses it to search google.

echo "Enter your search terms: "
read search

searchRefine=$(echo $search | sed -e 's/ /_/g')

dwb https://www.google.com/#q=$searchRefine

I think it'll work for other browsers if you just replace dwb with "your-browser-here"

Cheres,

Esko

Such a feature is built-in. From the dwb manual:

gs

    Add a searchengine. Textfields can be chosen with tab and a keyword must be specified. The first defined searchengine will be the default searchengine. The keyword can be used in all open commands, e.g. :open <keyword> <searchterm> (command save_search_field, aliases: search).

To clarify, go to google.com and hit "gs," then choose a keyword (something like "gg") to place before searches you wish to perform through Google. So "gg stuff" will search for the word "stuff" through Google. You can see a list of all stored search engines and their keywords in the dwb settings menu. wink Surfraw is also a similar tool.

Offline

#2282 2014-01-15 02:45:46

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

Re: Post your handy self made command line utilities

HalosGhost wrote:

This might also be the perfect time to look into surfraw.

All the best,

-HG

I tired it, but a few aliases and functions are just fine for me.

Last edited by karol (2014-01-15 02:46:33)

Offline

#2283 2014-01-16 10:50:59

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

Re: Post your handy self made command line utilities

Retrieve the current working directory of the focused (or given) window:

#! /bin/sh

wid=${1:-"$(xdo id)"}
pid=$(xdo pid "$wid")
[ -z "$pid" ] && exit 1
child=$(pgrep -nP $pid)
while [ -n "$child" ] ; do
    pid=$child
    child=$(pgrep -nP $pid)
done
printf "%s\n" "$(readlink /proc/${pid}/cwd)"

gh · da · ds

Offline

#2284 2014-01-16 10:57:17

milesrout
Member
Registered: 2014-01-16
Posts: 11

Re: Post your handy self made command line utilities

cat pacman.log | grep ' installed' | cut -d ' ' -f 5 | uniq | wc -l

Count how many packages I have installed (including ones that have been uninstalled, but not reinstallations).

Offline

#2285 2014-01-16 11:12:56

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

Re: Post your handy self made command line utilities

milesrout wrote:
cat pacman.log | grep ' installed' | cut -d ' ' -f 5 | uniq | wc -l

Count how many packages I have installed (including ones that have been uninstalled, but not reinstallations).

Spare the cat:

grep ' installed' /var/log/pacman.log | cut -d ' ' -f 5 | uniq | wc -l

It doesn't really work anyway:

$ cat /var/log/pacman.log | grep ' installed' | cut -d ' ' -f 5 | uniq | less
(0.12-2)
(0.7.6-2)
(0.1.1-3)
(1:244-1)
(3.4.0-2)
(2.0.4-1)
(20120511-1)
(1.2.4-5)
(0.8-5)
(20120512-1)
(183-3)
(1.0.11-2)
installed
(20120602-1)
(8-1)
(0.7.5-1)
(2.0.19-1)
(13.0-2)
(185-1)
...

Edit: The output isn't sorted, so you have to use 'sort -u' instead of 'uniq'

$ cat /var/log/pacman.log | grep ' installed' | cut -d ' ' -f 5 | uniq | wc -l
3242
$ grep ' installed' /var/log/pacman.log | cut -d ' ' -f 5 | egrep -v [1-9/] | grep -v installed | sort -u | wc -l
737

This still leaves some false positives though and if 'cut -d ' ' -f 5' doesn't hit the mark, it's pointless anyway.


Edit 2:

$ grep ' installed' /var/log/pacman.log | cut -d ' ' -f 4 > 0a
$ grep ' installed' /var/log/pacman.log | cut -d ' ' -f 5 >> 0a
$ grep -v [0-9/:] 0a | sort -u | grep ^[a-z] | wc -l
930

Last edited by karol (2014-01-16 11:53:28)

Offline

#2286 2014-01-16 21:57:30

bulletmark
Member
From: Brisbane, Australia
Registered: 2013-10-22
Posts: 675

Re: Post your handy self made command line utilities

Here's my script to alias cd and maintain a shell directory history. Been using it all day every day for 23 years (previous version was written in shell, now python). Don't understand how the rest of you survive without something like this.

See http://github.com/bulletmark/cdhist

Offline

#2287 2014-01-16 22:04:10

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

Re: Post your handy self made command line utilities

Usually I'm using only about a dozen directories, so 'shopt -s cdable_vars' + some aliased (exported) directories is all I need.

Offline

#2288 2014-01-17 02:07:32

snakeroot
Member
Registered: 2012-10-06
Posts: 168

Re: Post your handy self made command line utilities

Programs using the freedesktop.org bookmark specification store recently used files in xml format in a per-user "recently-used.xml" file contained in $HOME/.local/share directory.

This script deletes all entries with filenames containing asf/asx/avi/mov/mp4/mpg extensions (or their uppercase versions).

#!/bin/bash
sed -Ei "/<bookmark href.*.(asf|asx|avi|mov|mp4|mpg)/I,/bookmark>/d" $HOME/.local/share/recently-used.xbel

Offline

#2289 2014-01-17 06:14:43

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

Re: Post your handy self made command line utilities

Merging with the one-liner thread...


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#2290 2014-01-17 06:34:34

wesleyac
Member
Registered: 2013-08-27
Posts: 80

Re: Post your handy self made command line utilities

So this was going to be something useful, but it quickly became "how badly can I abuse pipes?"

dialog --menu "MusicHack Client" 40 120 40 $(for OUTPUT in $(mpc -f "    [%title%]" listall | grep "    " | sed s/"    "/""/g | sed s/" "/"_"/g); do echo $((i++)); echo $OUTPUT; done) 2>/tmp/musichack;echo "play" $(cat /tmp/musichack) | netcat 127.0.0.1 6600

You'll need mpd running on localhost 6600, and have netcat and dialog installed.

This displays a list of songs and lets you select one.  That song will then start playing.

Offline

#2291 2014-01-17 21:38:54

snakeroot
Member
Registered: 2012-10-06
Posts: 168

Re: Post your handy self made command line utilities

Accepts an ISO country code and returns the full country name.

Requires installation of tzdata package.

#!/bin/bash
country_code_table="/usr/share/zoneinfo/iso3166.tab"
if [[ -f $country_code_table && -r $country_code_table && -s $country_code_table ]]; then
        if [[ $# -ne 1 || ${#1} -ne 2 ]]; then
                echo "usage: input a single two-letter country code"
        else
                country_code=$(echo "${1}" | tr '[:lower:]' '[:upper:]')
                country_name=$(grep ^"${country_code}" "${country_code_table}")
                if [[ ${#country_name} -gt 0 ]]; then
                        echo "${country_name}"
                else
                        echo "${country_code} is not a valid country code"
                fi
        fi
else
        echo "ERROR: file $country_code_table doesn't exist, isn't readable or is zero length. Is tzdata installed properly?"
fi

Offline

#2292 2014-01-17 21:43:24

Jellicent
Member
From: Berlin
Registered: 2013-09-13
Posts: 189

Re: Post your handy self made command line utilities

Only a short script to get rid of tearing while playing.
Of course this was created two days before the big update that fucks with openGL applications when compositing is NOT used. smile))

#!/bin/bash                                                                                                                                                    

killall xcompmgr
WINEPREFIX=/home/jellicent/winapps/scii wine /home/jellicent/winapps/scii/drive_c/Program\ Files/StarCraft\ II/StarCraft\ II.exe &&
sleep 15

while pgrep SC2.exe;
do sleep 1;
done;
nohup xcompmgr -n &&

exit 0

Offline

#2293 2014-01-18 07:49:31

Thaodan
Member
From: Dortmund, Nordrein-Westfalen
Registered: 2012-04-28
Posts: 448

Re: Post your handy self made command line utilities

why the loop? just run nohup xcompmgr after starting SC2


Linux odin 3.13.1-pf #1 SMP PREEMPT Wed Mar 5 21:47:28 CET 2014 x86_64 GNU/Linux

Offline

#2294 2014-01-18 08:14:46

jsoy9pQbYVNu5nfU
Member
Registered: 2013-04-19
Posts: 108

Re: Post your handy self made command line utilities

Not a script per se, but a Bash completion function for the cpufreq-set command:

#!/bin/bash
_cpufreq-set(){
    local cur=${COMP_WORDS[COMP_CWORD]}
    local prev=${COMP_WORDS[COMP_CWORD-1]}
    local tmp=
    if [[ -z ${__cpufreq_set_corelist} ]]; then
        __cpufreq_set_corelist=$(seq 0 $(( $(grep -c ^processor /proc/cpuinfo)-1 )))
    fi
    if [[ -z ${__cpufreq_set_freqlist} ]]; then
        </sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies read tmp
        __cpufreq_set_freqlist=$tmp
    fi
    if [[ -z ${__cpufreq_set_govlist} ]]; then
        </sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors read tmp
        __cpufreq_set_govlist=$tmp
    fi
    if [[ $COMP_CWORD -eq 1 || $cur =~ -* ]]; then
        COMPREPLY=($( compgen -W '-c -d -u -f -g -r -h' ))
    fi
    case "$prev" in
        -u|-d|-f)
            COMPREPLY=($( compgen -W "${__cpufreq_set_freqlist}" -- $cur ))
            ;;
        -c)
            COMPREPLY=($( compgen -W "${__cpufreq_set_corelist}" -- $cur ))
            ;;
        -g)
            COMPREPLY=($( compgen -W "${__cpufreq_set_govlist}" -- $cur ))
            ;;
    esac
}
complete -F _cpufreq-set cpufreq-set

Offline

#2295 2014-01-18 21:18:06

cris9288
Member
Registered: 2013-01-07
Posts: 348

Re: Post your handy self made command line utilities

I'm not sure how many people will find this useful, but I found a way to automate the configuration of plugged in monitors so that it emulates Windows. When you plug in a monitor in Windows, it'll duplicate your desktop across both screens. After setting the configuration for this monitor by going to Desktop right-click -> Screen Resolution, it will remember the configuration the next time you plug it in. That is what script does. To use it, you will need inotify-tools from the official repos and read-edid from the AUR.

The first script, restorescreen.sh uses the inotifywait service to monitor the card0 directory (i'm not sure if this varies across systems). When a monitor is plugged in it attemps to build a unique identifier based on the edid's of each screen. It then attemps to run a command stored in the file that is named after that unique ID. Otherwise it just runs xrandr --auto.

#!/bin/bash


export DISPLAY=:0
export XAUTHORITY=/home/christian/.Xauthority

#directory containg screens
CARD=/sys/class/drm/card0/

#director where all xrandr commands will be stored
LAYOUT_DIR=/home/christian/.screen_layouts


while inotifywait -re modify,create,delete,open,close,close_write,access $CARD; do

   #this sleep in necessary to ensure edid file is ready
   sleep 2

   ID=""

   #loop through all the inputs and build unique identifier for each one based on their edid
   for i in $CARD/card0-*; do

      SCREEN_ID=$(cat $i/edid | parse-edid | grep "Identifier" | awk '{print $2}')

      #a disconnected input will have a blank edid
      if (( ${#SCREEN_ID} > 0 )); then

         #remove quotation marks from the identifier
         SCREEN_ID=$(echo ${SCREEN_ID:1:$((${#SCREEN_ID} - 2))})

         #append the SCREEN_ID to the master id
         ID="$ID$SCREEN_ID"
      fi

   done


   #check if an ID for this setup has been set before, otherwise let xrandr figure it out
   eval $(cat $LAYOUT_DIR/$ID) || xrandr --auto

done

The second script, storexrandr.sh just runs an xrandr command for you. If the command succeeds it will use the same logic as restorescreen.sh to build a unique id based on the currently available screens. It touches a file with the ID as it's name and writes the xrandr command to it.

 

#!/bin/bash
eval $1

if [ $? -eq 0 ]; then

   export DISPLAY=:0
   export XAUTHORITY=/home/christian/.Xauthority
     
   CARD=/sys/class/drm/card0/card0-
   LAYOUT_DIR=$HOME/.screen_layouts
   ID=""

   for i in $CARD*; do

      SCREEN_ID=$(cat $i/edid | parse-edid | grep "Identifier" | awk '{print $2}')

      if (( ${#SCREEN_ID} > 0 )); then

         SCREEN_ID=$(echo ${SCREEN_ID:1:$((${#SCREEN_ID} - 2))})
         ID="$ID$SCREEN_ID"
      fi
   done

   touch $LAYOUT_DIR/$ID && echo "$1" > $LAYOUT_DIR/$ID

fi
 

I run restorescreen.sh in a systemd service started by xinitrc. I'm trying to set up auto login to X so I can just enable these services, but that works for now. Parsing parse-edid was kind of annoying; I just found the substring logic somewhere on Stack Overflow. I'm sure there's a better way to get the output I want. All in all, it really isn't that useful. Previously I just had a udev rule with my screen settings hardcoded in, and it worked just fine. This was at least kind of instructive, though I'm sure there are better ways to do certain things. I'm open to any criticism/feedback anyone might have.

Offline

#2296 2014-01-18 22:59:24

snakeroot
Member
Registered: 2012-10-06
Posts: 168

Re: Post your handy self made command line utilities

This is a wrapper for coreutils "date" that uses the tzdata "zone.tab" file as a hash to return the date in a specified location. The location can be specified in two-letter country code format (and will return a list of timezones for multizone countries) or in placename form (for placenames referenced in /usr/share/zoneinfo/zone.tab).

Additional placenames (or even personal names) can be specified in a per-user file named localzone.tab maintained in $HOME/.local/share. The only requirement is that the placename be longer than two letters.

As a second parameter, one can input a date string (conforming to the requirements of date's "--date=" strings), which will determine the corresponding time in the user's zone and then return the equivalent time in the place named in the first parameter.

#!/bin/bash
if [[ $# -eq 0 ]]; then
	echo ""
	echo "Usage: enter a two-digit country code or a place name"
	echo "If the place name has a space in it, put it in quotes"
	echo "for example \"New York\" or \"Buenos Aires\"."
	echo ""
	echo "For a time other than the current time, enter it after"
	echo "the country code/place name. For more details see"
	echo "\"man (1) date\" --date."
	echo ""
	echo "Custom placenames can be placed in the file"
	echo '"$HOME/.local/share/localzone.tab". Entries are'
	echo "in the form:"
	echo ""
	echo "Place	TZ"
	echo ""
	echo "For example:"
	echo ""
	echo "Hyderabad	Asia/Kolkata"
	echo ""
	exit
fi
local=$(echo $1 | sed 's: :_:g')
tz_list="/usr/share/zoneinfo/zone.tab"
tz_local_list="$HOME/.local/share/localzone.tab"
if [[ ! -s "${tz_list}" || ! -r "${tz_list}" ]]; then
	echo "${tz_list} is not a readable, non-zero-size file. Is tzdata installed properly?"
	exit
fi
cc_count=$(grep -c ^"${local}" "${tz_list}")
place_count=$(grep -c "${local}" "${tz_list}")
if [[ $place_count -eq 0 && -e "${tz_local_list}" ]]; then
	place_count=$(grep -c "${local}" "${tz_local_list}")
fi
if [[ ${#local} -eq 2 ]]; then
	case $cc_count in
		0)
			echo "No such country in timezone list"
			exit
			;;
		1)
			;;
		*)
			echo "There is more than one timezone in ${local}. Please select from among:"
			grep ^"${local}" "${tz_list}" | awk '{print $3}'
			exit						
			;;
	esac
else
	if [[ $place_count -eq 0 ]]; then
		echo "No such place in timezone list. Try entering the two-letter country code."
		exit
	fi
fi
tz=$(grep "${local}" "${tz_list}" | awk '{print $3}')
if [[ -e "${tz_local_list}" ]]; then
	tz="${tz}"$(grep "${local}" "${tz_local_list}" | awk '{print $2}')
fi
if [[ $# -eq 1 ]]; then
	TZ="${tz}" date
elif [[ $# -eq 2 ]]; then
	ldate=$(date --date="$2")
	TZ="${tz}" date --date="${ldate}"
fi		

An example of the per-user file:

Hyderabad     Asia/Kolkata
Lennart       Europe/Berlin

Offline

#2297 2014-01-22 05:09:39

mohmann
Member
Registered: 2013-03-31
Posts: 13

Re: Post your handy self made command line utilities

screenswitcher

Display switcher utility for laptops

Especially useful, if you've got a laptop with two output ports, e.g. as in my case DisplayPort and VGA (Thinkpad X220). At home and at the office I use an external display through DisplayPort. At the university however, they supply Beamers with VGA only, so i use the VGA port. When invoked, screenswitcher will use the external display available (if there is any connected).

Customizable defaults for displays and behaviour (see head of the code or use the CLI-flags). Displays will cycle on invocation (see examples below). I mapped screenswitcher to hotkeys for easy display switching, but it's also pretty neat and easy on the CLI if you are too lazy for all that xrandr stuff.

#!/bin/bash
#
# Display switcher utility for laptops
#

## user config

# display identifiers
internal="LVDS1"
output0="HDMI1"
output1="VGA1"

# clone by default
clone="false" 

# default clone resolution
default_mode="1024x768"

# activate only one display at a time by default
single="false"

# default extend orientation of output0
o_output0="left-of" 

# default extend orientation of output1
o_output1="left-of" 

# verbose output by default
verbose="false"


## screenswitcher begin
xrandr_q=$(xrandr -q)

usage() {
	echo "Display switcher utility for laptops"
	echo
	echo "Invoke multiple times to cycle through display modes (default mode)"
	echo "(internal displayy -> external display -> both -> internal display etc.)"
	echo
	echo "Usage: $(basename "$0") [-h] [-d] [-c] [-m <mode>] [-e [<orientation>]]"
	echo "                        [-s] [-o <output>] [-q]"
	echo 
	echo "    -h                  Display this dialog and exit"
	echo
	echo "    -v                  Verbose output"
	echo
	echo "    -c                  Clone display instead of extending it."
	echo
	echo "    -m <mode>           Set clone resolution. Use pattern '[0-9]{3,}x[0-9]{3,}', "
	echo "                        e.g. 800x600 (default: $default_mode)"
	echo
	echo "    -e [<orientation>]  Extend display (default). Optional orientation param"
	echo "                        might be one of 'above|below|left-of|right-of'"
	echo
	echo "    -s                  Single display: don't (cycle) extend or clone,"
	echo "                        just switch between internal/external screen"
	echo
	echo "    -o <output>         External output to use. One of 'output0|output1'."
	echo "                        Will fallback to internal if output not connected."
	echo "                        If not set, will try output0 -> output1 -> internal"
	echo
	echo "    -q                  Quiet. Don't print active outputs after successful switch"
}

msg() {
	[[ "$verbose" == "true" ]] && echo "[$(basename "$0")] $1"
}

bail() {
	msg "xrandr failed to set display mode"
	exit 1
}

connected() {
	if [[ -n "$(echo "$xrandr_q" | grep "$1 connected")" ]]; then
		echo "true" 
	else 
		echo "false"
	fi
}

enabled() {
	if [[ -z "$(echo "$xrandr_q" | grep "$1 connected (")" ]] && 
		[[ -z "$(echo "$xrandr_q" | grep "$1 disconnected (")" ]]; then
		echo "true"
	else
		echo "false"
	fi
}

extend() {
	xrandr --output "$1" --auto "--$4" "$2" --output "$3" --off > /dev/null 2>&1 || bail
	[[ -z "$quiet" ]] && echo "extend: $1 $4 $2"
}

clone() {
	xrandr --output "$1" --mode "$4" --output "$2" --mode "$4" --output "$3" --off > /dev/null 2>&1 || bail
	[[ -z "$quiet" ]] && echo "clone: $1 $2 @ $4"
}

single() {
	xrandr --output "$1" --auto --output "$2" --off --output "$3" --off > /dev/null 2>&1	|| bail
	[[ -z "$quiet" ]] && echo "single: $1"
}

cycle() {
	local out0=$1
	local out1=$2

	msg "$out0 connected"

	if [[ $(enabled "$out0") == "true" ]]; then
		if [[ "$single" == "true" ]] || [[ $(enabled "$internal") == "true" ]]; then
			msg "$out0 enabled, switching to single display $internal"
			single "$internal" "$out0" "$out1"
		elif [[ "$clone" == "true" ]]; then
			msg "cloning $internal and $out0 @ ${mode:-$default_mode}"
			clone "$internal" "$out0" "$out1" "${mode:-$default_mode}"
		else
			msg "extending $internal $orientation $out0"
			extend "$internal" "$out0" "$out1" "$orientation"
		fi
	else
		msg "$internal enabled, switching to single display $out0"
		single "$out0" "$internal" "$out1"
	fi
}

# parse args
while [[ -n "$1" ]]; do
	case $1 in
		-h) 
			usage; exit 0;;
		-v)
			verbose="true"; shift;;
		-c)
			clone="true"; single="false"; shift;;
		-m)
			[[ ! "$2" =~ ^[0-9]{3,}x[0-9]{3,}$ ]] && { usage; exit 1; }
			mode=$2; shift; shift;;
		-e)
			clone="false"; single="false";
			case "$2" in
				above|below|left-of|right-of)
					orientation="$2"; shift;;
				*) ;;
			esac
			shift;;
		-s)
			clone="false"; single="true"; shift;;
		-o)
			no_auto="true"; shift
			case "$1" in
				output0) ;; # output0 already first in line, do nothing
				output1) # swap output configs to have output1 go first
					output=$output0;  o_output=$o_output0 # tmp
					output0=$output1; o_output0=$o_output1
					output1=$output;  o_output1=$o_output
					;;
				*)
				usage; exit 1;;
			esac
			shift;;
		-q)
			quiet="true"; shift;;
		*)
			usage; exit 1;;
	esac
done

# switch screen
if [[ $(connected "$output0") == "true" ]]; then
	orientation=${orientation:-$o_output0}
	cycle "$output0" "$output1"
elif [[ -z "$no_auto" ]] && [[ $(connected "$output1") == "true" ]]; then
	orientation=${orientation:-$o_output1}
	cycle "$output1" "$output0"
else
	msg "no external displays, single display $internal"
	single "$internal" "$output0" "$output1"
fi
exit 0

https://raw2.github.com/martinohmann/sc … enswitcher

If you've got only one output, setting "output1" to something invalid e.g. "donthaveoutput1" should work (xrandr will warn, but proceed), or remove the output1 part from the script altogether. DO NOT set the same identifier in output0 and output1. This will break the script.

"output0" is always the preferred one, but can be overridden (see below). Some examples:

screenswitcher -e (default behaviour)
    internal laptop display -> external display -> extend displays -> internal laptop display etc.

screenswitcher -c
    internal laptop display -> external display -> clone displays -> internal laptop display etc.

screenswitcher -s
    internal laptop display -> external display -> internal laptop display etc.

screenswitcher -e left-of -o output1
    internal laptop display -> external display -> extend internal left of output1  -> internal laptop display etc.

screenswitcher -c -m 800x600
    internal laptop display -> external display -> clone 800x600 -> internal laptop display etc.

Screenswitcher will output state to STDOUT after successful display mode switch (can be suppressed with -q), so you can trigger actions depending on that.

Best regards

Last edited by mohmann (2014-01-25 09:10:58)

Offline

#2298 2014-01-25 23:00:30

snakeroot
Member
Registered: 2012-10-06
Posts: 168

Re: Post your handy self made command line utilities

Use curl and the dict Protocol to Look Up Information in Online Dictionaries

This script allows you to look up a word in the Jargon File maintained at dict.org. Because the server and database are variables it would be easy to adapt it to use other dictionaries as well.

A list of available dict databases can be found here. Other dict based utilities can be found in this thread at post 1438 (gadamat) and post 473 (Barracadu).

#!/bin/bash

trm=$1
server="dict.org"
db="jargon"
curl_exe="/usr/bin/curl"

if [[ $# -ne 1 ]]; then
	echo ""
	echo "USAGE: Input one term for lookup on the ${server} ${db} dictionary"
	echo "Phrases containing a space (e.g., open source) should be put in"
	echo "quotation marks (\"open source\")."
	echo ""
fi

if [[ ! -x "${curl_exe}" ]]; then
	echo "ERROR: $curl_exe is not installed or is not executable. Exiting"
	exit
fi

if [[ $# -eq 1 ]]; then
	echo ""
	curl -Ss dict://"${server}"/d:"${trm}":"${db}" | sed -e "s:552 .*:Term ${trm} not found in ${db} dictionary\n:g" -e "/^[0-9][0-9][0-9] .*/d"  -e "/^\./d"
fi

Here's a more complicated variant which looks up information on chemical elements. It can accept an element name (Gold), symbol (Au) or atomic number (79) and returns information on the relevant element. It requires bash 4.0 or above since it uses an associative array.

#!/bin/bash

trm=$1
server="dict.org"
db="elements"
curl_exe="/usr/bin/curl"

if [[ $# -ne 1 ]]; then
	echo ""
	echo "USAGE: Input one atomic numer (1-118), atomic symbol or element name for lookup on the ${server} ${db} dictionary"
	echo ""
fi

if [[ ! -x "${curl_exe}" ]]; then
	echo "ERROR: $curl_exe is not installed or is not executable. Exiting"
	exit
fi

declare -A pt

pt[H]="Hydrogen"
pt[He]="Helium"
pt[Li]="Lithium"
pt[Be]="Beryllium"
pt[B]="Boron"
pt[C]="Carbon"
pt[N]="Nitrogen"
pt[O]="Oxygen"
pt[F]="Flourine"
pt[Ne]="Neon"
pt[Na]="Sodium"
pt[Mg]="Magnesium"
pt[Al]="Aluminum"
pt[Si]="Silicon"
pt[P]="Phosphorus"
pt[S]="Sulfur"
pt[Cl]="Clorine"
pt[Ar]="Argon"
pt[K]="Potassium"
pt[Ca]="Calcium"
pt[Sc]="Scandium"
pt[Ti]="Titanium"
pt[V]="Vanadium"
pt[Cr]="Chromium"
pt[Mn]="Manganese"
pt[Fe]="Iron"
pt[Co]="Cobalt"
pt[Ni]="Nickel"
pt[Cu]="Copper"
pt[Zn]="Zinc"
pt[Ga]="Gallium"
pt[Ge]="Germanium"
pt[As]="Arsenic"
pt[Se]="Selenium"
pt[Br]="Bromine"
pt[Kr]="Krypton"
pt[Rb]="Rubidium"
pt[Sr]="Strontium"
pt[Y]="Yttrium"
pt[Zr]="Zirconium"
pt[Nb]="Niobium"
pt[Mo]="Molybdenum"
pt[Tc]="Technetium"
pt[Ru]="Ruthenium"
pt[Rh]="Rhodium"
pt[Pd]="Palladium"
pt[Ag]="Silver"
pt[Cd]="Cadmium"
pt[In]="Indium"
pt[Sn]="Tin"
pt[Sb]="Antimony"
pt[Te]="Tellurium"
pt[I]="Iodine"
pt[Xe]="Xenon"
pt[Cs]="Cesium"
pt[Ba]="Barium"
pt[La]="Lanthanum"
pt[Ce]="Cerium"
pt[Pr]="Praseodymium"
pt[Nd]="Neodymium"
pt[Pm]="Promethium"
pt[Sm]="Samarium"
pt[Eu]="Europium"
pt[Gd]="Gadolinium"
pt[Tb]="Terbium"
pt[Dy]="Dysprosium"
pt[Ho]="Holmium"
pt[Er]="Erbium"
pt[Tm]="Thulium"
pt[Yb]="Ytterbium"
pt[Lu]="Lutetium"
pt[Hf]="Hafnium"
pt[Ta]="Tantalum"
pt[W]="Tungsten"
pt[Re]="Rhenium"
pt[Os]="Osmium"
pt[Ir]="Iridium"
pt[Pt]="Platinum"
pt[Au]="Gold"
pt[Hg]="Mercury"
pt[Tl]="Thallium"
pt[Pb]="Lead"
pt[Bi]="Bismuth"
pt[Po]="Polonium"
pt[At]="Astatine"
pt[Rn]="Radon"
pt[Fr]="Francium"
pt[Ra]="Radium"
pt[Ac]="Actinium"
pt[Th]="Thorium"
pt[Pa]="Protactinium"
pt[U]="Uranium"
pt[Np]="Neptunium"
pt[Pu]="Plutonium"
pt[Am]="Americium"
pt[Cm]="Curium"
pt[Bk]="Berkelium"
pt[Cf]="Californium"
pt[Es]="Einsteinium"
pt[Fm]="Fermium"
pt[Md]="Mendelevium"
pt[No]="Nobelium"
pt[Lr]="Lawrencium"
pt[Rf]="Rutherfordium"
pt[Db]="Dubnium"
pt[Sg]="Seaborgium"
pt[Bh]="Bohrium"
pt[Hs]="Hassium"
pt[Mt]="Meitnerium"
pt[Ds]="Darmstadtium"
pt[Rg]="Roentgenium"
pt[Cn]="Copernicium"
pt[Uut]="Ununtrium"
pt[Fl]="Flerovium"
pt[Uup]="Ununpentium"
pt[Lv]="Livermorium"
pt[Uus]="Ununseptium"
pt[Uuo]="Ununoctium"

declare ptn

ptn[1]="Hydrogen"
ptn[2]="Helium"
ptn[3]="Lithium"
ptn[4]="Beryllium"
ptn[5]="Boron"
ptn[6]="Carbon"
ptn[7]="Nitrogen"
ptn[8]="Oxygen"
ptn[9]="Flourine"
ptn[10]="Neon"
ptn[11]="Sodium"
ptn[12]="Magnesium"
ptn[13]="Aluminium"
ptn[14]="Silicon"
ptn[15]="Phosphorus"
ptn[16]="Sulfur"
ptn[17]="Clorine"
ptn[18]="Argon"
ptn[19]="Potassium"
ptn[20]="Calcium"
ptn[21]="Scandium"
ptn[22]="Titanium"
ptn[23]="Vanadium"
ptn[24]="Chromium"
ptn[25]="Manganese"
ptn[26]="Iron"
ptn[27]="Cobalt"
ptn[28]="Nickel"
ptn[29]="Copper"
ptn[30]="Zinc"
ptn[31]="Gallium"
ptn[32]="Germanium"
ptn[33]="Arsenic"
ptn[34]="Selenium"
ptn[35]="Bromine"
ptn[36]="Krypton"
ptn[37]="Rubidium"
ptn[38]="Strontium"
ptn[39]="Yttrium"
ptn[40]="Zirconium"
ptn[41]="Niobium"
ptn[42]="Molybdenum"
ptn[43]="Technetium"
ptn[44]="Ruthenium"
ptn[45]="Rhodium"
ptn[46]="Palladium"
ptn[47]="Silver"
ptn[48]="Cadmium"
ptn[49]="Indium"
ptn[50]="Tin"
ptn[51]="Antimony"
ptn[52]="Tellurium"
ptn[53]="Iodine"
ptn[54]="Xenon"
ptn[55]="Cesium"
ptn[56]="Barium"
ptn[57]="Lanthanum"
ptn[58]="Cerium"
ptn[59]="Praseodymium"
ptn[60]="Neodymium"
ptn[61]="Promethium"
ptn[62]="Samarium"
ptn[63]="Europium"
ptn[64]="Gadolinium"
ptn[65]="Terbium"
ptn[66]="Dysprosium"
ptn[67]="Holmium"
ptn[68]="Erbium"
ptn[69]="Thulium"
ptn[70]="Ytterbium"
ptn[71]="Lutetium"
ptn[72]="Hafnium"
ptn[73]="Tantalum"
ptn[74]="Tungsten"
ptn[75]="Rhenium"
ptn[76]="Osmium"
ptn[77]="Iridium"
ptn[78]="Platinum"
ptn[79]="Gold"
ptn[80]="Mercury"
ptn[81]="Thallium"
ptn[82]="Lead"
ptn[83]="Bismuth"
ptn[84]="Polonium"
ptn[85]="Astatine"
ptn[86]="Radon"
ptn[87]="Francium"
ptn[88]="Radium"
ptn[89]="Actinium"
ptn[90]="Thorium"
ptn[91]="Protactinium"
ptn[92]="Uranium"
ptn[93]="Neptunium"
ptn[94]="Plutonium"
ptn[95]="Americium"
ptn[96]="Curium"
ptn[97]="Berkelium"
ptn[98]="Californium"
ptn[99]="Einsteinium"
ptn[100]="Fermium"
ptn[101]="Mendelevium"
ptn[102]="Nobelium"
ptn[103]="Lawrencium"
ptn[104]="Rutherfordium"
ptn[105]="Dubnium"
ptn[106]="Seaborgium"
ptn[107]="Bohrium"
ptn[108]="Hassium"
ptn[109]="Meitnerium"
ptn[110]="Darmstadtium"
ptn[111]="Roentgenium"
ptn[112]="Copernicium"
ptn[113]="Ununtrium"
ptn[114]="Flerovium"
ptn[115]="Ununpentium"
ptn[116]="Livermorium"
ptn[117]="Ununseptium"
ptn[118]="Ununoctium"

if [ "${1}" -eq "${1}" ] 2>/dev/null; then
	if [[ "${1}" -ge 1 && "${1}" -le 118 ]]; then
		element_name="${ptn[$1]}"
	else
		echo "Not a valid atomic number (1-118)"
		exit
	fi
elif [[ ${#1} -ge 1 && ${#1} -le 3 ]]; then
	element_name="${pt[$1]}"
	if [[ ! -n "${element_name}" ]]; then
		echo "Not a valid atomic symbol"
		exit
	fi
else
	element_name=${1}
fi

echo ""
curl -Ss dict://"${server}"/d:"${element_name}":"${db}" | sed -e "s:552 .*:Element ${element_name} not found in ${db} dictionary\n:g" -e "/^[0-9][0-9][0-9] .*/d"  -e "/^\./d"

Last edited by snakeroot (2014-01-26 02:45:39)

Offline

#2299 2014-02-06 17:22:15

easysid
Member
From: India
Registered: 2013-01-01
Posts: 256

Re: Post your handy self made command line utilities

A calendar popup widget for dzen2

#pop-up calendar for dzen
#
# based on (c) 2007, by Robert Manea
# http://dzen.geekmode.org/dwiki/doku.php?id=dzen:calendar
# modified by easysid 
# Use fifo pipe to change month

FONT="dejavu sans mono"
FONTSIZE="10"
PAD='  '
ACT='onstart=uncollapse;button1=exit;button3=exit'

# Colors
FG="#a0a0a0"
BG="#202020"
highlight="#ffffff"
highlight2="#3f3f3f"

WIDTH=150
LINES=8
XPOS=1194
YPOS=30

# define pipe
PIPE=/tmp/calendar_pipe

TODAY=$(expr `date +'%d'` + 0)
MONTH=$(date +'%m')
YEAR=$(date +'%Y')

MM=${1:-"$MONTH"}
YY=${2:-"$YEAR"}
NEXT=$((MM+1))
PREV=$((MM-1))
let Y_NEXT=Y_PREV=YY

if [[ $NEXT -eq 13 ]]; then
    NEXT=1
    Y_NEXT=$((YY+1))
fi

if [[ $PREV -eq 0 ]]; then
    PREV=12
    Y_PREV=$((YY-1))
fi

# generate calender
if [[ "$MM" -eq "$MONTH" ]] && [[ "$YY" -eq "$YEAR" ]]; then  # current month, highlight header and date
    CAL=$(cal | sed -re "s/^(.*[A-Za-z][A-Za-z]*.*)$/^fg($highlight)\1^fg()/;s/(^|[ ])($TODAY)($|[ ])/\1^bg($highlight2)^fg($highlight)\2^fg()^bg()\3/")
else  # another month, just highlight header
    CAL=$(cal "$MM" "$YY" | sed -re "s/^(.*[A-Za-z][A-Za-z]*.*)$/^fg($highlight)\1^fg()/")
fi

# read from pipe
if [ ! -e "$PIPE" ]; then
  mkfifo "$PIPE"
  ( dzen2 -u -bg $BG -fg $FG -fn "${FONT}:pixelsize=${FONTSIZE}" -x $XPOS -y $YPOS -w $WIDTH -l $LINES -sa 'c' -e "$ACT" -title-name 'popup_calendar' < "$PIPE"
   rm -f "$PIPE") &
fi

# feed the pipe
(
echo "$CAL"
echo "^ca(1, $0 $PREV $Y_PREV)<<Prev^ca()  ^ca(1, $0 $NEXT $Y_NEXT)Next>>^ca()"
sleep 10s
) > "$PIPE"

Offline

#2300 2014-02-07 12:14:47

whilealive
Member
Registered: 2012-09-04
Posts: 17

Re: Post your handy self made command line utilities

I use mbsync along with mutt in a tmux session. This script syncs mail every 10 minutes with gpg security as suggested in the "passwords management" section of the mutt article in the ArchWiki. So I only have one gpg-encrypted file "my-pwds.gpg" for both mutt and mbsync. I don't know, whether this can be really considered "secure"...

#!/bin/bash

period="10"
let "period_sec = 60 * $period"

INBOX1=""

# has to be adjusted to the individual .my-pwds file...
passwd1="$(gpg2 -dq ~/.my-pwds.gpg | cut -c 40- | sed -n 1p)"

while true
do
    echo "running mbsync..."

    # copy password into a temporary rc file.
    # the right position in the rc file is crucial and marked in the original file by the line '#Pass1' etc.
    sed s/\#Pass1/Pass\ $passwd1/ ~/.mbsyncrc > ~/.mbsyncrc-temp

    # run mbsync using the temporary rc file and delete it aftwerwards
    mbsync -q -c ~/.mbsyncrc-temp -a
    shred -xu ~/.mbsyncrc-temp

    # count new messages
    NEW1=`find $INBOX1 -type f | wc -l`
    echo -e "new messages:\t $NEW1"

    # some information
    echo -n -e "\nlast sync: "
    date +"%H:%M"
    echo "next sync in $period minutes."

    # either wait for 10 minutes or check again immediately by pressing Enter
    echo -e "to sync mails now, press [Enter]\n"
    read -s -t $period_sec input
done

Offline

Board footer

Powered by FluxBB