You are not logged in.

#2001 2012-12-08 18:43:40

skydrome
Member
From: The Soviet States of Legos
Registered: 2012-09-03
Posts: 8
Website

Re: Post your handy self made command line utilities

edit

Last edited by skydrome (2012-12-08 19:21:09)

Offline

#2002 2012-12-08 20:27:18

kaszak696
Member
Registered: 2009-05-26
Posts: 543

Re: Post your handy self made command line utilities

Very rudimentary 'news reader' in python:

#!/usr/bin/python

import pickle
import feedparser
import time
import sys
import webbrowser
import os

if __name__ == '__main__':
	
	TIME_FILE = os.getenv('HOME') + '/.last_time'
	RSS_FILE = os.getenv('HOME') + '/rss_urls'
	
	rss_urls =[]
	
	print('Parsing files...')
	
	try:
		with open(TIME_FILE, 'rb') as time_file:
			last_time = pickle.load(time_file)
	except FileNotFoundError:
		last_time = time.gmtime()
		with open(TIME_FILE, 'wb') as time_file:
			pickle.dump(time.gmtime(), time_file)
		print('Saved current time as last_time.')
		sys.exit()
	
	try:
		with open(RSS_FILE) as rss_file:
			for line in rss_file:
				rss_urls.append(line.strip())
	except FileNotFoundError:
		print('The configuration file with feed urls is missing, fix it!')
		sys.exit(1)

	print('Parsing feeds...')

	for url in rss_urls:
		parsed = feedparser.parse(url)
		for entry in parsed.entries:
			if entry.published_parsed > last_time:
				webbrowser.open_new_tab(entry.link)
	
	with open(TIME_FILE, 'wb') as time_file:
		pickle.dump(time.gmtime(), time_file)

It reads RSS urls from rss_urls file in home directory and opens entries newer than last saved time in the default's browser new tab. If file with saved time is missing, it creates new one with the current time. Most likely will crash or freeze browser if there are too many unread feeds.
Depends on 'python-feedparser' package.


'What can be asserted without evidence can also be dismissed without evidence.' - Christopher Hitchens
'There's no such thing as addiction, there's only things that you enjoy doing more than life.' - Doug Stanhope
GitHub Junkyard

Offline

#2003 2012-12-08 22:56:09

moetunes
Member
From: A comfortable couch
Registered: 2010-10-09
Posts: 1,033

Re: Post your handy self made command line utilities

I wanted a quick and easy way to check what I haven't read in gmail, either in a terminal or in X using dmenu_run so I came up with this:

#!/bin/bash

## Quickly checks if I have new gmail

outtox=0
[[ "$1" != "" ]] && outtox=1
tmp=/tmp/gmail_check.atomfeed
[[ -f $tmp ]] || touch $tmp
mssg=""

wget -T 3 -t 1 -q --secure-protocol=TLSv1 \
 --no-check-certificate \
 --user=username --password="password" \
 https://mail.google.com/mail/feed/atom -O $tmp

if [ "$(wc -l $tmp | awk '{print $1}')" -lt "2" ]; then
    echo -e "   GMAIL CHECK FAILED   \n       CHECK NEEDED     \n" |\
     xmessage -center -file -
    exit 1
fi 

have_mail=`sed -n 's|<fullcount>\(.*\)</fullcount>|\1|p' $tmp`
what_mail=`sed -n 's|<title>\(.*\)</title>|\1|p' $tmp`
#echo "$what_mail"

if [ $have_mail -gt "0" ]; then
    mssg="   You have new gmail.  \n"
    mssg="$mssg   There are:\n      $have_mail new messages\n\n"
    while read -r line; do
        mssg="$mssg      $line\n"
    done < <(echo "$what_mail")
    if [ "$outtox" -lt "1" ]; then
        echo -e "$mssg" | xmessage -center -file -
     else
         echo -e "$mssg"
     fi
else
    mssg="   No new gmail.  "
    [[ "$outtox" -lt "1" ]] && echo -e "$mssg" | xmessage -center -timeout 4 -file - ||\
     echo -e "$mssg"
fi

exit 0

Without a parameter it shows the subject line of each email in xmessage, with a parameter it prints to the terminal.


You're just jealous because the voices only talk to me.

Offline

#2004 2012-12-09 21:33:39

ezzetabi
Member
Registered: 2006-08-27
Posts: 947

Re: Post your handy self made command line utilities

A new version of wmctrl, it allows to move windows to the corners of the screen with easy and hide windows decoration... all from command line.

Last edited by ezzetabi (2012-12-28 11:57:51)

Offline

#2005 2012-12-10 03:29:41

AaronBP
Member
Registered: 2012-08-06
Posts: 149
Website

Re: Post your handy self made command line utilities

Wasn't really satisfied with what I was using so I made a wrapper around less/source-highlight.

~/bin/view

#!/bin/sh

hcat() {
	if [ "$(head -1 "$1")" = "#!/bin/dash" ]
	then
		lang="--src-lang=shell"
	fi
	if [ "$lang" ]
	then
		source-highlight "$lang" -n --failsafe -f esc -i "$arg"
	else
		source-highlight -n --failsafe -f esc -i "$arg"
	fi
}

for arg in $@
do
	if [ ! -f "$arg" ]
	then
		echo $arg does not exist. >&2
		continue
	fi
	flines=$(eval "wc -l "$arg" | fex '1'")
	if [ $flines -le $(expr $(tput lines) - 3) ]
	then
		hcat "$arg"
		echo
	else
		hcat "$arg" | less -R -X
	fi
done

This of course uses source-highlight. It also needs fex from the AUR.

So far it seems to work the way I want.

EDIT:

I wanted to be able to do something like

sudo journalctl | grep "Dec 11" | view -l log

I moved a lot of things around in the process. This is what I've got now. On top of fex, V2 also requires docopts in the AUR (I'm really fond of it so I use it a lot).

#!/bin/bash
usage="view - pager (with syntax highlighting)

Usage:
    view [options] <file>...
    view [options]
    view --list
    view -h | --help

Options:
    -l <language> --lang=<language>  Force language
    --list  List available languages"


eval "$(docopts "$usage" "$version" "--" "$@")"

highlight() {
	# source-highlight wigs out if there's and empty argument
	if [ $1 ]
	then
		source-highlight "$1" -n --failsafe -f esc -i "$2"
	else
		source-highlight -n --failsafe -f esc -i "$2"
	fi
}

hcat() {
	if [ "$lang" ]
	then
		larg="--src-lang="$lang""
	fi
	for arg in "$@"
	do
		if [ ! -f "$arg" ]
		then
			echo "$arg" does not exist. >&2
			continue
		fi
		flines=$(eval 'wc -l <"$arg"')
		if [ $flines -le $(expr $(tput lines) - 3) ]
		then
			highlight "$larg" "$arg"
			echo
		else
			highlight "$larg" "$arg" | less -R -X
		fi
	done
}

main() {
	if [ $list != "false" ]
	then
		source-highlight --lang-list | fex '1'
		exit 0
	fi

	if [ "$file" ]
	then
		hcat "${file[@]}"
	else
		tmpfile=$(mktemp)
		cat /dev/stdin >"$tmpfile"
		hcat "$tmpfile"
		rm "$tmpfile"
	fi
}

main

Last edited by AaronBP (2012-12-12 05:00:03)

Offline

#2006 2012-12-30 19:07:56

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

Re: Post your handy self made command line utilities

I wrote a small password manager script which I call passman.

Basically it uses GPG to crypt a file containing logins mostly for websites I regularly visit.
With the help of dmenu and xdotool, login forms can be filled in a few keystrokes. Everytime I need a login, I type a WM shortcut to call the script followed by a part of the site name, press Enter and the form gets automatically filled and submitted by xdotool.

I mapped "passman fillbrowser" to Super-z.

I thought, maybe you will like it, so I put it on github: https://github.com/mlux/passman
Usage instructions can be found in the README.md file.

Offline

#2007 2013-01-01 13:31:15

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

Re: Post your handy self made command line utilities

I have been using this script a lot recently to split individual songs from a larger stream.
It produces a file called output.mp3.
When you run it on a file it asks for a start time which can be formatted as: seconds or mm:ss or hh:mm:ss. Decimal places are allowed.
It will then play 5 seconds and ask for the start time again (with the previous time in the prompt). If you fill in the same time it will continue or else it will play 5 seconds again.
Then it'll do the same thing for the end time.
And finally write output.mp3.

#! /bin/bash

[[ -f output.mp3 ]] && echo 'Output file already exists.' && exit

file=$1
[[ "$file" =~ mp3 ]] && extra="-c:a copy" || extra="-sameq"

while read -e -i "$OLDBEGIN" -p 'Begin time> ' BEGIN; do
if [[ $BEGIN =~ : ]]; then #00:30:20 / #30:10
	seconds=${BEGIN##*:}
	seconds=${seconds#0}
	[[ $seconds ]] || seconds=0
	notseconds=${BEGIN%:*}
	minutes=${notseconds##*:}
	minutes=${minutes#0}
	[[ $minutes ]] || minutes=0
	[[ $notseconds =~ : ]] && hours=${notseconds%:*} || hours=00
	hours=${hours#0}
	[[ $hours ]] || hours=0
	seconds=$( echo "$seconds + ( $minutes * 60 ) + ( $hours * 3600 )" | bc)
else
seconds=$BEGIN
fi
[[ $BEGIN == $OLDBEGIN ]] && break
ffmpeg -y -i "$file" -ss $seconds -t 5 $extra output.mp3
mpg123 output.mp3
OLDBEGIN=$BEGIN
done
bseconds=$seconds

while read -e -i "$OLDEND" -p 'End time> ' END; do
if [[ $END =~ : ]]; then #00:30:20 / #30:10
	seconds=${END##*:}
	seconds=${seconds#0}
	[[ $seconds ]] || seconds=0
	notseconds=${END%:*}
	minutes=${notseconds##*:}
	minutes=${minutes#0}
	[[ $minutes ]] || minutes=0
	[[ $notseconds =~ : ]] && hours=${notseconds%:*} || hours=00
	hours=${hours#0}
	[[ $hours ]] || hours=0
	seconds=$( echo "$seconds + ( $minutes * 60 ) + ( $hours * 3600 )" | bc)
else
seconds=$END
fi
[[ $END == $OLDEND ]] && break
ffmpeg -y -i "$file" -ss $(echo "$seconds -5" | bc) -t 5 $extra output.mp3
mpg123 output.mp3
OLDEND=$END
done
eseconds=$seconds

ffmpeg -i "$file" -ss $bseconds -t $(echo "$eseconds-$bseconds" | bc) $extra -y output.mp3

echo File output.mp3 created.

Offline

#2008 2013-01-03 01:01:13

bslackr
Member
Registered: 2012-01-27
Posts: 131

Re: Post your handy self made command line utilities

i_love_penguins wrote:

I wrote a small password manager script which I call passman.

Basically it uses GPG to crypt a file containing logins mostly for websites I regularly visit.
With the help of dmenu and xdotool, login forms can be filled in a few keystrokes. Everytime I need a login, I type a WM shortcut to call the script followed by a part of the site name, press Enter and the form gets automatically filled and submitted by xdotool.

I mapped "passman fillbrowser" to Super-z.

I thought, maybe you will like it, so I put it on github: https://github.com/mlux/passman
Usage instructions can be found in the README.md file.

I might start using this instead of gnome-keyring, thanks.

Offline

#2009 2013-01-03 15:05:12

saf1
Member
Registered: 2011-04-04
Posts: 17

Re: Post your handy self made command line utilities

this is a shell script to check files quickly
using VirusTotal service (https://www.virustotal.com).

#!/bin/bash

#  Shell script to scan files using VirusTotal service (https://www.virustotal.com)
#
#  Author       : saf1
#  Home         : http://www.linuxac.org
#  Date         : Mon Aug 20 2012
#  Dependencies : md5sum, curl, And don't forget to be connected 

help(){
  echo -e "\nThis is a Shell-Script that help you to scan your files"
  echo -e "using VirusTotal service (https://www.virustotal.com)\n"
  echo -e "Usage : ./${0##*/} [OPTION] [File][Directory]"
  echo -e "  Available Options:"
  echo -e "           -f [file]        Scan file"
  echo -e "           -d [directory]   Scan all the contents of the directory"
  echo -e "           -h               Show this help\n"
}

scan(){
  file="$1"
  md5="$(md5sum "$file" | awk '{print $1}')"
  url="https://www.virustotal.com/file/${md5}/analysis/"
  result="$(curl -s --head --connect-timeout 3 --retry 1 $url | awk '/HTTP/ {print $2}')"

  if [ "$result" == "200" ]; then
    ratio="$(curl -s $url | grep '<td class=\" text-.*</td>' | cut -d'>' -f2 | cut -d'<' -f1)"
    if [ "${ratio:0:1}" == "0" ];then
      status="\033[1;32mClean\033[0m"
    else
      status="\033[1;31mInfected\033[0m"
    fi
    echo -e "\nFile             : $file"
    echo -e "MD5              : $md5"
    echo -e "Status           : $status"
    echo -e "Detection ratio  : $ratio"
    echo -e "Raport           : $url\n"
  else
    echo -e "\nFile             : $file"
    echo -e "MD5              : $md5"
    echo -e "Status           : \033[36mSuspected\033[0m\n"
  fi
}

case "$1" in
  -d)
    if [ ! -d "$2" ]; then
      echo -e "\n[!] cannot access $2: No such directory\n"
      exit 1
    else
      export -f scan
      find "$2" -type f -exec bash -c "scan \"{}\"" \;
    fi
  ;;
  -f)
    if [ ! -f "$2" ] ; then
      echo -e "\n[!] cannot access $2: No such file\n"
      exit 1
    else
      scan "$2"
    fi
  ;;
  *)
    help
  ;;
esac

I hope that's be useful for someone.

Last edited by saf1 (2013-01-03 15:19:21)

Offline

#2010 2013-01-20 18:44:23

Brcher
Member
Registered: 2011-06-20
Posts: 36

Re: Post your handy self made command line utilities

This is nowhere near as clever as most of the scripts ya'll've shared so far, but I find it sort of useful to be able to have skeleton .tex file that I can turn into a pdf from the command line. I keep all my scripts, etc, in a directory called .mystuff.

"newtex"

  
#! /bin/bash
cp /home/<account_name>/.mystuff/template.tex $1

"tex2pdf"

name=$1
latex $name
dvipdfm ${name//.tex/.dvi}
rm ${name//.tex/.dvi} 
rm ${name//.tex/.aux} 
cat ${name//.tex/.log}
rm ${name//.tex/.log} 

I've yet to find a more convenient way to get ".tex in, .pdf out, and don't generate a bazillion other junk files"

Oh also I guess
"template.tex"

 
\documentclass[11pt]{article}
\title{}
\author{<your name here>}
\begin{document}
\maketitle
\section{}
\end{document}

And from there the regular rules of tex apply.
I guess you need the "article" template thimgamajiggy, but it was installed by default on my fairly minimal tex install so it is probably installed on yours too. smile

Offline

#2011 2013-01-20 21:00:45

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,423
Website

Re: Post your handy self made command line utilities

Brcher wrote:

I've yet to find a more convenient way to get ".tex in, .pdf out, and don't generate a bazillion other junk files

Try out latexmk with the "clean" options.


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#2012 2013-01-21 17:27:46

dancer69
Banned
Registered: 2011-08-05
Posts: 66

Re: Post your handy self made command line utilities

I'm new to arch and I had difficulties to remember the pacman/powerpill/yaourt different commands.
So here is a script with some of them(not all), with a short discription:

#!/bin/bash
printf '\033[8;36;77t'
clear

method ()

{
	echo -e "\033[01;35m***************************** Package Manager ***************************\033[39m"
	echo
	echo -e "---------------------------------\033[01;36mPOWERPILL\033[39m-------------------------------"
	echo "  1    Install"
	echo "  2    Sync-update"
	echo "  3    Remove- keep dependencies"
	echo "  4    Remove- keep only dependencies which required 
	by any other package"
	echo "  5    Remove- package, its dependencies and all packages
	that depend on the target package"
	echo "  6    Remove- package, which is required by another package,
	without removing the dependent package"
	echo "  7    Search- for installed package"
	echo "  8    Search- all, searching both in package's 
	names and descriptions"
	echo "  9    Info-all, information for given package"
	echo "  10    Info-local, locally installed packages"
	echo "  11   Filelist- list of files installed by a package"
	echo "  12   BelongTo- in which package belongs the given file"
	echo "  13   Orphan- list packages no longer 
	requred as dependencies"
	echo "  14   DependencyList- package's dependency list"
	echo	
	echo -e "------------------------------------\033[01;36mYAOURT\033[39m-------------------------------"
	echo "  15   Install- install one or more packages including AUR"
	echo "  16   Update- upgrade all packages to their newest version"
	echo "  17   Remove- uninstall one or more packages"
	echo "  18   Search- search for a package or a PKGBUILD using 
	one or more keywords"
	echo "  19   Info- show information about a package"
	
	echo "**************************************************************************"
	echo -e '\033[01;33m'
	PS3="Please enter your choice between 1-19 or q to quit: "	
	echo "$PS3"
	echo -e '\033[39m'
	read i 	
	case "$i" in
		1) echo "Type the packages for install->[ENTER]:"
		read names
		echo
		read -p "Install $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -S --needed $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		2) echo "Type the packages(or nothing) for update-> [ENTER]:"
		read names
		echo   
		read -p "sync-update $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Syu $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		3) echo "Type the package(s) for removing-> [ENTER]:"
		read names
		echo   
		read -p "Remove $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -R $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		4) echo "Type the packages for removing-> [ENTER]:"
		read names
		echo   
		read -p "Remove $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Rs $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		5) echo "Type the package(s) for removing-> [ENTER]:"
		read names
		echo   
		read -p "Remove $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Rsc $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		6) echo "Type the package(s) for removing-> [ENTER]:"
		read names
		echo   
		read -p "Remove $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Rdd $names
		read -s -n 1 -p "Press any key to continue…"		
		echo;;

		7) echo "Type the package for searching-> [ENTER]:"
		read names
		echo   
		read -p "Search $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Qs $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		8) echo "Type the package for searching-> [ENTER]:"
		read names
		echo   
		read -p "Search-all $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Qs $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		9) echo "Type the package for info-> [ENTER]:"
		read names
		echo   
		read -p "Info-all $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Si $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		10) echo "Type the package for information-> [ENTER]:"
		read names
		echo   
		read -p "Info-local $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Qi $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		11) echo "Type the package for filelist-> [ENTER]:"
		read names
		echo   
		read -p "Filelist $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Ql $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		12) echo "Type the path and name of package-> [ENTER]:"
		read names
		echo   
		read -p "BelongsTo $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Qo $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		13) read -p "Get the Orphans? (y/n)?"
		[ "$REPLY" == "y" ] && sudo powerpill -Qdt $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		14) echo "Type the  package for dependency list-> [ENTER]:"
		read names
		echo   
		read -p "Dependency list $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo pactree $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		15) echo "Type the  package(s) for install-> [ENTER]:"
		read names
		echo   
		read -p "Install $names (y/n)?"
		[ "$REPLY" == "y" ] && yaourt -S $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		16)echo   
		read -p "Upgrade all packages to newest version $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo yaourt -Syua $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		17) echo "Type the  package(s) to remove-> [ENTER]:"
		read names
		echo   
		read -p "Remove $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo yaourt -Rs $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		18) echo "Type the  name of package(s) for searching-> [ENTER]:"
		read names
		echo   
		read -p "Search $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo yaourt -Ss $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;
		
		19) echo "Type the  name of package for Information-> [ENTER]:"
		read names
		echo   
		read -p "Info $names (y/n)?"
		[ "$REPLY" == "y" ] && sudo yaourt -Si $names
		read -s -n 1 -p "Press any key to continue…"
		echo;;

		q) echo -e "\033[01;33mbye!!!\033[39m"
		sleep 1
		clear
		exit ;;
		 *)
			echo "Unknown command"
			read -s -n 1 -p "Press any key to continue…"
			echo
	esac
}
while :
do
	method 
done

Last edited by dancer69 (2013-01-22 15:11:09)

Offline

#2013 2013-01-22 14:44:34

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

Re: Post your handy self made command line utilities

A small notification script for net connections. I use netcfg and this comes in handy. It uses notify-send alert whenever connection drops or is connected

#!/bin/bash

#net-monitor.sh - a script to run in background and generate notifications for connection events.
# Right now it only monitors wlan0, because that is what i use.

notified_conn=0	# notification status flags
notified_disconn=0
ESSID=

function connected()
{
		notify-send " " -i notification-network-wireless-full -t 3500 "Connected to \"$ESSID\""
		notified_conn=1
		notified_disconn=0
}

function disconnected()
{
		notify-send " " -i notification-network-disconnected -t 3500 "Disconnected"
		notified_disconn=1
		notified_conn=0
}

# main code
while true; do
		if grep -i 'wlan' /proc/net/route > /dev/null 2>&1; then # test if interface is connected. Can also use ping 
			ESSID=$(iwconfig wlan0 | grep -i essid | cut -d '"' -f 2) #get ESSID
			if [ $notified_conn -eq "0" ]; then # check if already notified
				connected
			fi
		elif [ $notified_disconn -eq "0" ]; then #check if already notified
			disconnected
		fi
		sleep 2 #run every 2 sec
done

Offline

#2014 2013-01-26 05:18:05

milo64
Banned
From: Chiang Mai, Thailand
Registered: 2013-01-18
Posts: 86
Website

Re: Post your handy self made command line utilities

I've made one handy shell script that checks the MD5 Sum, so we don't have to compare them with our eyes.

#!/bin/bash
if [ "$1" = "" ]; then
	echo "ERR: Missing command-line parameter."
	echo " "
	echo "Syntax:"
	echo "	md5-check.sh FILE ACTUAL-MD5"
	exit 1
fi

if [ "$2" = "" ]; then
	echo "ERR: Missing command-line parameter."
	echo " "
	echo "Syntax:"
	echo "	md5-check.sh FILE ACTUAL-MD5"
	exit 1
fi

if [ -a "$1" ]; then
	echo 123 > /dev/null
else
	echo "ERR: '$1' No such file."
	exit 1;
fi

if [ "$(md5sum $1 | awk '{print $1}')" = "$2" ]; then
	echo "Checksum matched."
	exit 0
else
	echo "Checksum not matched."
	exit 1
fi

If you don't understand the syntax, here is an example:

./md5-check.sh my-filename.txt d41d8cd98f00b204e9800998ecf8427e

milo64.
Registered Linux User: #555436
My Blog @ http://milo64.blogspot.com/

Offline

#2015 2013-01-26 11:38:13

MatejLach
Member
From: United Kingdom
Registered: 2011-06-22
Posts: 314
Website

Re: Post your handy self made command line utilities

@milo64

Very handy, thanks!

Offline

#2016 2013-01-26 21:22:00

bslackr
Member
Registered: 2012-01-27
Posts: 131

Re: Post your handy self made command line utilities

milo64 wrote:

I've made one handy shell script that checks the MD5 Sum, so we don't have to compare them with our eyes.

You could simplify this:

#!/bin/bash
if [ "$1" = "" ]; then
	echo "ERR: Missing command-line parameter."
	echo " "
	echo "Syntax:"
	echo "	md5-check.sh FILE ACTUAL-MD5"
	exit 1
fi

if [ "$2" = "" ]; then
	echo "ERR: Missing command-line parameter."
	echo " "
	echo "Syntax:"
	echo "	md5-check.sh FILE ACTUAL-MD5"
	exit 1
fi

to

if [ ! $# == 2]; then
    echo "ERR: Missing command-line parameter."
    ...
    exit 1
fi

and this

if [ -a "$1" ]; then
	echo 123 > /dev/null
else
	echo "ERR: '$1' No such file."
	exit 1;
fi

to

if [ ! -f "$1"]; then
    ...
   exit 1
fi

Offline

#2017 2013-02-01 19:12:50

TheeMahn
Member
Registered: 2013-02-01
Posts: 1
Website

Re: Post your handy self made command line utilities

I am not a Arch linux user.  I am a linux distro writer / programer of Ultimate Edition Linux. I have found over the years many nice snippits of code from this forum.  I thought it would be a nice gesture to give a little back. That said.

A few big toys for the big boyz. I'd like to introduce a few upcoming tools to the Ultimate Edition arsenal. Most people will find them useless, programmers on the other hand will find them indispensable. I use this tool daily in my packaging and programing process. This tool complements Repomaster perfectly (unreleased until copywriten). This will be a part of the tm-tools meta-package which is well beyond the scope of the post. Arch linux users as well distro writers are also free to use as well distribute this package.

I have scoured the Internet looking for a tool to do exactly what this tool does. All I have read is that it is impossible. Feel free to form your own opinion. The package in question is ultimate-edition-code-cleanup.deb and contains the following 2 tools:

  • bashdepends

  • code-cleanup

1. bashdepends

theemahn@JackHammer:~$ bashdepends --help
bashdepends 1.7.1-8, 01/31/2013
GNU bashdepends home page: <http://www.ultimateedition.info/>.
E-mail bug reports to: <theemahn@ultimateedition.info>.
Be sure to include the word bashdepends somewhere in the Subject: field.

bashdepends is a part of the tm-tools package. Many of the tools are heavy and
are not intended to be ran by the common user. The tools are geared for the
admininstrator. Please see man tmtools for more info.

Usage: bashdepends -[-COMMAND] <BASHSCRIPT>
Mandatory arguments to long options are identical for short options.
possible commands...

    -d    --depends    find dependencies for <BASHSCRIPT>
    -h    --help        this help message
    -v    --version    dump version info

Example: bashdepends mybashscript.sh
bashdepends --help [COMMAND] for further information.
theemahn@JackHammer:~$

What about the source code?

#!/bin/bash
# ==============================================================================
# title			:bashdepends
# description		:Build dependancies script for bash
# author		:Glenn Cady <theemahn@ultimateedition.info>
# date			:01/31/2013
# version		:1.7.1-8
# usage			:builddeps --help
# manual		:man bashdepends
# notes			:See change-log below for further information.
# bash_version		:4.2.8(1)-release
# ==============================================================================
# Change-log: 1.7.1-8: Currently unreleased / unleashed
# ==============================================================================
VERSION="1.7.1-8"
BUILDDATE="01/31/2013"
# set colors so errors etc. stand out.

txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

#Folder where executed
CURRENT=$PWD

function Chkdeps (){
	# verify a parameter was passed
	if [[ $1 == "" ]];then
		echo -e "${bldred}Please specify a file.${txtrst}"
		exit 0
	fi

	# Filename in case user entered /bin/repomaster for example set to repomaster
	filename=${1##*/}

	# set bash file to process copy to temp
	cp $1 /tmp/
	BFTP="/tmp/"$filename

	# test for bash script existance
	test -s $BFTP || exit 0;
	echo -e "${bldgrn}Please wait this may take a while depending on the size of the script.${txtrst}"

	# roll to temp to begin processing.
	cd /tmp/

	# strip tabs
	sed -i 's/^[ \t]*//' $BFTP

	# strip comments
	sed -e 's/#.*$//' -e '/^$/d' $filename > wip.txt

	# strip echo a builtin
	sed -i '/echo .*/d' wip.txt

	# strip functions
	sed -i '/function .*/d' wip.txt
	sed -i '/}.*/d' wip.txt

	# strip Printf
	sed -i '/printf .*/d' wip.txt

	# strip braces
	cat wip.txt | tr -d "[]" > $filename

	# test for existance of temporary words list in case
	# this tool has been ran before.if so remove file.
	test -e /tmp/words.txt && rm /tmp/words.txt

	# grab commands used in bash file
	for word in $(cat "$BFTP")
	do
		[ -f '$word' -o -f /bin/$word ] && echo $word >> /tmp/words.txt &2>/dev/null
		[ -f '$word' -o -f /usr/bin/$word ] && echo $word >> /tmp/words.txt &2>/dev/null
	done

	cat $BFTP | grep '$(' | cut -d'(' -f2 | sed 's/ .*//g' >> /tmp/words.txt
	cat $BFTP | grep '`' | cut -d'`' -f2 | sed 's/ .*//g' >> /tmp/words.txt
	#strip empty lines
	sed -i '/^$/d' /tmp/words.txt
	#cat $filename | cut -d' ' -f1 >> words.txt
	#intiate array
	array_counter=0
	array_value=0

	#Declare array with all bash builtins
	declare -a Builtins=('alias' 'bg' 'bind' 'break' 'builtin' 'cd' 'command' 'compgen' 'complete' 'continue' 'declare' 'dirs' 'disown' 'echo' 'enable' 'eval' 'exec' 'exit' 'export' 'fc' 'fg' 'getopts' 'hash' 'help' 'history' 'jobs' 'kill' 'let' 'local' 'logout' 'popd' 'printf' 'pushd' 'pwd' 'read' 'readonly' 'return' 'set' 'shift' 'shopt' 'source' 'suspend' 'test' 'times' 'trap' 'type' 'typeset' 'ulimit' 'umask' 'unalias' 'unset' 'wait');

	#Strip references to bash builtin commands
	echo -e "${bldgrn}Stripping bash builtin commands.${txtrst}"
	for number in ${Builtins[@]}
	do
		sed -i "s/${Builtins[$array_counter]}//g" /tmp/words.txt
		array_counter=$(($array_counter + 1))
	done

	#scrap open brackets* from list
	sed -i 's/\[.*//g' /tmp/words.txt

	#scrap empty lines and a few builtins
	sed -i '/^$/d' /tmp/words.txt
	sed -i '/for .*/d' /tmp/words.txt
	sed -i '/from.*/d' /tmp/words.txt
	sed -i "/'/d" /tmp/words.txt

	#Start building dependancy list
	cat /tmp/words.txt | tr " " "\n" | sort | uniq >/tmp/depends.txt

	#Strip #'s
	sed -i '/sh/d' /tmp/depends.txt

	#Strip empty lines
	sed -i '/^$/d' /tmp/depends.txt

	#Initiate header & display results to end user
	echo -e "${bldgrn}Externally called commands:${txtrst}"

	# Check list existance no list no dependancies
	if test -s /tmp/depends.txt
		then
		cat /tmp/depends.txt
	else
		echo -e "${bldred}$1 has no external dependancies.${txtrst}"
		CleanUP
		exit 0
	fi

	#Initate header to display progress in scanning. Make it pretty ;)
	echo -e "${bldgrn}SCANNING FOR NON-ESSENTIAL / ESSENTIAL PACKAGE(S)..."
	printf '%-15s %-30s %-10s %s\n' \
	"COMMAND" "PACKAGE" "PRIORITY" "VERSION"

	#Punch out package database to reference later
	echo -e "${bldwht}________________________________________________________________________________${txtrst}"
	dpkg-query -Wf '${Package}:${Priority}:${Version}\n' | sort -b -k2,2 -k1,1 >/tmp/packages.txt
	test -e /tmp/list.txt && rm /tmp/list.txt

	#Set header for Control file
	cat /tmp/depends.txt | while read FILE
	do
		BINARY=$(which $FILE)
		if [[ $BINARY != "" ]]; then
			POSSIBLE=$(dpkg -S `which $BINARY` | cut -d":" -f1)
			PACKAGEPRIORITY=$(dpkg-query -s $POSSIBLE | grep "Priority:" | cut -d: -f2 | sed 's/ //g')
			PVERSION=$(dpkg-query -s $POSSIBLE | grep "Version:" | cut -d: -f2 | sed 's/ //g')
		else
			exit 0
		fi
		# I have not seen an unknown ever come up please report if you
		# see one and the package involved.
		case $PACKAGEPRIORITY in
			"standard")
			echo -e -n "${bldgrn}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";;
			"required")
			echo -e -n "${bldgrn}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";;
			"important")
			echo -e -n "${bldgrn}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";;
			"optional")
			echo -e -n "${bldred}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";
			echo "$POSSIBLE:$PVERSION" >> list.txt;;
			"extra")
			echo -e -n "${bldred}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "$PACKAGEPRIORITY" "$PVERSION";
			echo "$POSSIBLE:$PVERSION" >> list.txt;;
			*)
			echo -e -n "${bldblu}";
			printf '%-15s %-30s %-10s %s\n' \
			"$FILE" "$POSSIBLE" "UNKNOWN" "$PVERSION";;
		esac
	done
	echo -e "${bldwht}Please add all red packages to your control file.${txtrst}"
	GenerateList
}

function GenerateList {
	if test -s list.txt
	then
		echo -n "Depends: "
	else
		echo -e "${bldgrn}No external dependancies.${txtrst}"
		CleanUP
		exit 0
	fi
	NDEPENDS=$(cat list.txt | wc -l)
	cat /tmp/list.txt | while read FILE
	do
		PROCESS=$(($PROCESS + 1))
		DEPEND=$(echo $FILE | cut -d: -f1)
		DVERSION=$(echo $FILE | cut -d: -f2)
		# make sure if is not entered twice on the list for example the 
		# commands "ar" and "as" are both part of binutils. We only want
		# it referenced once.
		if test -s fulllist.txt
		then
			ISTHERE=$(cat fulllist.txt | grep $DEPEND)
			if [[ $ISTHERE == "" ]]; then
				if [[ $NDEPENDS != $PROCESS ]]; then
					OUT=$OUT$DEPEND" (>="$DVERSION"), "
				else
					OUT=$OUT$DEPEND" (>="$DVERSION")"
				fi
			fi
		else
			if [[ $NDEPENDS != $PROCESS ]]; then
				OUT=$OUT$DEPEND" (>="$DVERSION"), "
			else
				OUT=$OUT$DEPEND" (>="$DVERSION")"
			fi
		fi
		# push list out to file bash gets dumb when it leaves a do done
		# loop and I do not feel like writing it to run in a sub shell.
		echo $OUT > fulllist.txt
	done
	cat fulllist.txt
	CleanUP
}

function CleanUP {
	# self explanatory
	test -e /tmp/list.txt && rm /tmp/list.txt
	test -e /tmp/fulllist.txt && rm /tmp/fulllist.txt
	test -e /tmp/words.txt && rm /tmp/words.txt
	test -e /tmp/packages.txt && rm /tmp/packages.txt
	test -e /tmp/wip.txt && rm /tmp/wip.txt
	test -e /tmp/depends.txt && rm /tmp/depends.txt
	test -e $BFTP && rm $BFTP
}

function Version {
	# dump version number and exit
	echo -e "${undwht}bashdepends $VERSION, $BUILDDATE${txtrst}
	==============
	GNU builddeps home page: <http://www.ultimateedition.info/>.
	E-mail bug reports to: <theemahn@ultimateedition.info>.
	Be sure to include the word builddeps somewhere in the Subject: field."
	exit 0
}

function Help() {

	if [[ $1 == "" ]];
		then
		PRAM="ALL"
	else
		PRAM=$1
	fi

echo -e "${undwht}bashdepends $VERSION, $BUILDDATE${txtrst}"

	case $PRAM in
		ALL)
	echo -e "${txtgrn}GNU bashdepends home page: <http://www.ultimateedition.info/>.
E-mail bug reports to: <theemahn@ultimateedition.info>.
Be sure to include the word bashdepends somewhere in the Subject: field.${txtrst}";
echo "
bashdepends is a part of the tm-tools package. Many of the tools are heavy and
are not intended to be ran by the common user. The tools are geared for the
admininstrator. Please see man tmtools for more info.";
echo -e "
${bldgrn}Usage: bashdepends -[-COMMAND] <BASHSCRIPT>${txtrst}
Mandatory arguments to long options are identical for short options.
possible commands...

	-d	--depends	find dependencies for <BASHSCRIPT>
	-h	--help		this help message
	-v	--version	dump version info

${bldgrn}Example: bashdepends mybashscript.sh
${bldgrn}bashdepends --help [COMMAND] for further information.${txtrst}";;
	ALL|d|depends)
	echo -e "
	${bldwht}Usage depends;${txtrst}
	${txtgrn}bashdepends -d <BASHSCRIPT>${txtrst}
	Displays external dependencies on <BASHSCRIPT>.";;
	ALL|v|version)
	echo -e "
	${bldwht}Usage version;${txtrst}
	${txtgrn}bashdepends -v${txtrst}
	Displays bashdepends version number and exits.";;
	ALL|h|help|\?)
	echo -e "
	${bldwht}Useage Help [COMMAND];${txtrst}
	${txtgrn}bashdepends -h [COMMAND]${txtrst}
	Displays this message. For futher information bashdepends help [COMMAND]
	or refer to the manpages.
	man bashdepends"
	echo -e "${txtgrn}"
	echo -e "Example: bashdepends mybashscript.sh"
	echo -e "${txtwht}Will find the build dependancies for mybashscript.sh${txtrst}"
	esac
exit 0
}

#Command switch preprocessor
case "$1" in
	-h|--help|-\?) Help $2; exit 0;;
	-v|--version) Version; exit 0;;
	-d|--depends) Chkdeps $2; exit 0;;
	*) Help; exit 0;;
esac

Let's see it in action:

theemahn@JackHammer:~$ bashdepends --depends conky-builder.sh 
bashdepends 1.7.1-8, 01/31/2013
GNU builddeps home page: <http://www.ultimateedition.info/>.
E-mail bug reports to: <theemahn@ultimateedition.info>.
Be sure to include the word builddeps somewhere in the Subject: field.
Please wait this may take a while depending on the size of the script.
Stripping bash builtin commands.
Externally called commands:
cat
cut
dpkg
expr
grep
hddtemp
ls
lsb_release
rm
sed
sensors
uname
wc
xrandr
yes
SCANNING FOR NON-ESSENTIAL / ESSENTIAL PACKAGE(S)...
COMMAND         PACKAGE                        PRIORITY   VERSION
________________________________________________________________________________
cat             coreutils                      required   8.13-3ubuntu3.2
cut             coreutils                      required   8.13-3ubuntu3.2
dpkg            dpkg                           required   1.16.1.2ubuntu7.1
expr            coreutils                      required   8.13-3ubuntu3.2
grep            grep                           required   2.10-1
hddtemp         hddtemp                        extra      0.3-beta15-51
ls              coreutils                      required   8.13-3ubuntu3.2
lsb_release     lsb-release                    extra      4.0-0ubuntu20.2
rm              coreutils                      required   8.13-3ubuntu3.2
sed             sed                            required   4.2.1-9
sensors         lm-sensors                     extra      1
uname           coreutils                      required   8.13-3ubuntu3.2
wc              coreutils                      required   8.13-3ubuntu3.2
xrandr          x11-xserver-utils              optional   7.6+3
yes             coreutils                      required   8.13-3ubuntu3.2
Please add all red packages to your control file.
Depends: hddtemp (>=0.3-beta15-51), lsb-release (>=4.0-0ubuntu20.2), lm-sensors (>=1), x11-xserver-utils (>=7.6+3)
theemahn@JackHammer:~$

Well that is sweet, it looks like I have to now change conky-builders control file in the deb. I did not include sensors and xrandr in version 1.17 of the conky-builder now at 1.18 for this exact reason. It definately did its job here. False positives are a possibality on huge scripts such as the repomaster (largest script I have ever seen), however it really does narrow things down. Let's move on to the second tool.

2. code-cleanup
I did not write this tool Paul Lutus did under GPL, I did however modify it for use with bash and Repomastered it. It is written in ruby hense the dependency on ruby. It is the same tool that cleaned up the code in the above app to make it more readable. Auto indent / outdent.

#!/usr/bin/ruby -w
# ==============================================================================
# title			:code-cleanup
# description		:Auto build, repository management script
# author		:Glenn Cady <theemahn@ultimateedition.info>
# date			:01/26/2013
# version		:1.7.1-8
# usage			:code-cleanup --help
# manual		:man code-cleanup
# notes			:See change-log below for further information.
# ==============================================================================
# Change-log: 1.7.1-8: Currently unreleased / unleashed
# ==============================================================================
# Original code: Copyright (C) 2008, Paul Lutus under GPL
PVERSION = "1.7.1-8"

module RBeautify

   # user-customizable values

   RBeautify::TabStr = "\t"
   RBeautify::TabSize = 1

   # indent regexp tests

   IndentExp = [
      /^module\b/,
      /^class\b/,
      /^if\b/,
      /(=\s*|^)until\b/,
      /^unless\b/,
      /(=\s*|^)while\b/,
      /(=\s*|^)begin\b/,
      /(^| )case\b/,
      /^rescue\b/,
      /^def\b/,
      /^do\b/,
      /^else\b/,
      /^elsif\b/,
      /^ensure\b/,
      /\bwhen\b/,
      /\{[^\}]*$/,
      /\[[^\]]*$/
   ]

   # outdent regexp tests

   OutdentExp = [
      /^rescue\b/,
      /^ensure\b/,
      /^elsif\b/,
      /^end\b/,
      /^else\b/,
      /^fi\b/,
      /^esac\b/,
      /^done\b/,
      /\bwhen\b/,
      /^[^\{]*\}/,
      /^[^\[]*\]/,
   ]

   def RBeautify.rb_make_tab(tab)
      return (tab < 0)?"":TabStr * TabSize * tab
   end

   def RBeautify.rb_add_line(line,tab)
      line.strip!
      line = rb_make_tab(tab) + line if line.length > 0
      return line
   end

   def RBeautify.beautify_string(source, path = "")
      comment_block = false
      in_here_doc = false
      here_doc_term = ""
      program_end = false
      multiLine_array = []
      multiLine_str = ""
      tab = 0
      output = []
      source.each do |line|
         line.chomp!
         if(!program_end)
            # detect program end mark
            if(line =~ /^__END__$/)
               program_end = true
            else
               # combine continuing lines
               if(!(line =~ /^\s*#/) && line =~ /[^\\]\\\s*$/)
                  multiLine_array.push line
                  multiLine_str += line.sub(/^(.*)\\\s*$/,"\\1")
                  next
               end

               # add final line
               if(multiLine_str.length > 0)
                  multiLine_array.push line
                  multiLine_str += line.sub(/^(.*)\\\s*$/,"\\1")
               end

               tline = ((multiLine_str.length > 0)?multiLine_str:line).strip
               if(tline =~ /^=begin/)
                  comment_block = true
               end
               if(in_here_doc)
                  in_here_doc = false if tline =~ %r{\s*#{here_doc_term}\s*}
               else # not in here_doc
                  if tline =~ %r{=\s*<<}
                     here_doc_term = tline.sub(%r{.*=\s*<<-?\s*([_|\w]+).*},"\\1")
                     in_here_doc = here_doc_term.size > 0
                  end
               end
            end
         end
         if(comment_block || program_end || in_here_doc)
            # add the line unchanged
            output << line
         else
            comment_line = (tline =~ /^#/)
            if(!comment_line)
               # throw out sequences that will
               # only sow confusion
               while tline.gsub!(/\{[^\{]*?\}/,"")
               end
               while tline.gsub!(/\[[^\[]*?\]/,"")
               end
               while tline.gsub!(/'.*?'/,"")
               end
               while tline.gsub!(/".*?"/,"")
               end
               while tline.gsub!(/\`.*?\`/,"")
               end
               while tline.gsub!(/\([^\(]*?\)/,"")
               end
               while tline.gsub!(/\/.*?\//,"")
               end
               while tline.gsub!(/%r(.).*?\1/,"")
               end
               # delete end-of-line comments
               tline.sub!(/#[^\"]+$/,"")
               # convert quotes
               tline.gsub!(/\\\"/,"'")
               OutdentExp.each do |re|
                  if(tline =~ re)
                     tab -= 1
                     break
                  end
               end
            end
            if (multiLine_array.length > 0)
               multiLine_array.each do |ml|
                  output << rb_add_line(ml,tab)
               end
               multiLine_array.clear
               multiLine_str = ""
            else
               output << rb_add_line(line,tab)
            end
            if(!comment_line)
               IndentExp.each do |re|
                  if(tline =~ re && !(tline =~ /\s+end\s*$/))
                     tab += 1
                     break
                  end
               end
            end
         end
         if(tline =~ /^=end/)
            comment_block = false
         end
      end
      error = (tab != 0)
      STDERR.puts "Error: indent/outdent mismatch: #{tab}." if error
      return output.join("\n") + "\n",error
   end # beautify_string

   def RBeautify.beautify_file(path)
      error = false
      if(path == '-') # stdin source
         source = STDIN.read
         dest,error = beautify_string(source,"stdin")
         print dest
      else # named file source
         source = File.read(path)
         dest,error = beautify_string(source,path)
         if(source != dest)
            # make a backup copy
            File.open(path + "~","w") { |f| f.write(source) }
            # overwrite the original
            File.open(path,"w") { |f| f.write(dest) }
         end
      end
      return error
   end # beautify_file

   def RBeautify.main
      error = false
      if(!ARGV[0])
         STDERR.puts "usage: Ruby filenames or \"-\" for stdin."
         exit 0
      end
      ARGV.each do |path|
         error = (beautify_file(path))?true:error
      end
      error = (error)?1:0
      exit error
   end # main
end # module RBeautify

# if launched as a standalone program, not loaded as a module
if __FILE__ == $0
   RBeautify.main
end

I highly recommend installing the deb over copy pasting of the scripts.  The deb includes bash auto completion. In the terminal you can type bashdepends --d hit the [tab] key and it will fill in the --depends hit it again and it will list files in your current directory.  I will not rob you of the source for it either:

# Debian bashdepends(8) completion.

have bashdepends &&
_bashdepends() 
{
	dashify()
	{
		local i

		for (( i=0; i < ${#COMPREPLY[@]}; i++ )); do
			if [ ${#COMPREPLY[i]} -le 2 ]; then
				COMPREPLY[i]=-${COMPREPLY[i]}
			else
				COMPREPLY[i]=--${COMPREPLY[i]}
			fi
		done
	}

	local cur cur_nodash prev

	COMPREPLY=()
	cur=${COMP_WORDS[COMP_CWORD]}
	cur_nodash=${cur#-}
	prev=${COMP_WORDS[COMP_CWORD-1][COMP_CWORD-2]}

	if [ $COMP_CWORD = 1 ]; then
		# first parameter on line
		case "$cur" in
		-d*)
			COMPREPLY=( $( compgen -W 'depends' \
				       $cur_nodash ) )
			dashify
			return 0
			;;
		-*)
			COMPREPLY=( $( compgen -W 'depends version help' ${cur_nodash#-} ) )
			dashify;
			return 0
			;;
		--*)
			COMPREPLY=( $( compgen -W 'depends version help' ${cur_nodash#-} ) )
			dashify;
			return 0
			;;
		*)
			COMPREPLY=( $( compgen -f $cur ) )
			return 0
			;;
		esac
	fi

	if [ $COMP_CWORD = 2 ]; then
		case "${COMP_WORDS[1]}" in
		--d*)
			# standard filename completion
			COMPREPLY=( $( compgen -f $cur ) )
			return 0
			;;
		-d)
			# standard filename completion
			COMPREPLY=( $( compgen -f $cur ) )
			return 0
			;;
		--h*)
			# complete on list of relevant options
			COMPREPLY=( $( compgen -W 'depends version' ${cur_nodash#-} ) )
			#dashify;
			return 0
			;;
		-h)
			# complete on list of relevant options
			COMPREPLY=( $( compgen -W 'depends version' ${cur_nodash#-} ) )
			#dashify;
			return 0
			;;
		esac
	fi
}
complete -F _bashdepends bashdepends

Arch Linux, Thanks for all the code you have provided to me.

TheeMahn,
Manual for repomaster
ultimate-edition-code-cleanup.deb

Offline

#2018 2013-02-02 00:44:39

piluke
Member
From: Texas
Registered: 2012-12-08
Posts: 2

Re: Post your handy self made command line utilities

Here's several handy scripts I've written:

confirm

#!/bin/bash
# Displays a confirmation prompt
#
# Usage:
#	confirm [-n] ["prompt"]
# Options:
#	-n
#		Changes the default option to N
# Exit Status:
#	0	Y selected
#	1	N seleected

default="y"
question="Are you sure?"
if [ -n "${BASH_ARGV[0]}" ]; then
	if [ ${BASH_ARGV[0]:0:1} != "-" ]; then
		question="${BASH_ARGV[0]}"
	fi
fi
while getopts "n" arg; do
	case $arg in
		n)
			default="n"
			question+=" [y/N] "
			;;
	esac
done

if [ $default != "n" ]; then
	question+=" [Y/n] "
fi

read -r -p "$question" response

case $response in
	[yY][eE][sS]|[yY])
		exit 0
		;;
	[nN][oO]|[nN])
		exit 1
		;;
	*)
		if [[ $default == "y" ]]; then
			exit 0
		else
			exit 1
		fi
		;;
esac

nuke
* Requires the above confirm command
* The command used to shred files can be changed with the $shred variable
* Files supplied on the command line cannot start with a '-', but files within given directories are fine

#!/bin/bash
# Securely deletes the given directories
#
# Usage:
#	nuke [-v] file...
# Options:
#	-v
#		Verbose mode, echo each file
# Exit Status:
#	0	Success
#	1	Aborted at confirm
# Known Bugs:
#	File names cannot start with a '-'

shred="shred -fuz"
verbose=0

`confirm -n "Are you sure you want to nuke these files?"`
if [ $? -eq 1 ]; then
	exit 1
fi

while getopts "v" arg; do
	case $arg in
		v)
			verbose=1
			;;
	esac
done

for d in "$@"; do
	if [ ${d:0:1} != "-" ]; then
		echo -e "\e[01;37mNow nuking '$d'...\e[00m"
		if [ -f "$d" ]; then
			$shred "$d"
		elif [ -d "$d" ]; then
			if [ $verbose -eq 1 ]; then
				cd "$d"
				find . -type f -exec echo "    Nuking '{}'..." \; -execdir $shred "{}" \;
				cd - > /dev/null
			else
				find "$d" -type f -execdir $shred "{}" \;
			fi
			rm -rf "$d"
		fi
	fi
done

exit 0

passgen
* Requires haveged

#!/bin/bash
# Generates a secure password with haveged and echoes it
#
# Usage:
#	passgen [-n length]
# Options:
#	-n
#		The length of the password to be generated

n=64
while getopts n: x; do
	n=$OPTARG
done; OPTIND=0

echo -n `haveged -n 10000 -f - 2>/dev/null | tr -dc "a-zA-Z0-9" | fold -w $n | head -n 1 | tr -d "\n"`

yt
* Requires youtube-dl
* Downloads YouTube videos, saves them by name in ~/.yt/, then plays them

#!/bin/bash
# Plays YouTube videos from the given URL
#
# Usage:
#	yt url
# Exit Status:
#	0	Success
#	1	Download error
#	2	Update error

HOME=$(eval echo ~$USERNAME)

echo "Loading title..."

stopsaver="xscreensaver-command -deactivate"

yt="/usr/bin/youtube-dl"
op="-k -o $HOME/.yt/%(id)s.flv"

t=`$yt -e $1`
t=${t// /_}
t=${t////}

if [ ! -f "$HOME/.yt/$t.flv" ]; then
	echo "Downloading $t..."
	`$yt $op $1 > /dev/null`
	if [ $? -ne 0 ]; then
		echo "Download error"
		echo "Updating youtube-dl..."
		`sudo $yt -U > /dev/null`
		if [ $? -ne 0 ]; then
			echo "Retrying download..."
			`$yt $op $1 > /dev/null`
			if [ $? -ne 0 ]; then
				echo "Download error"
				exit 1
			fi
		else
			echo "Update error"
			exit 2
		fi
	fi
	mv "$HOME/.yt/${1#*v=}.flv" "$HOME/.yt/$t.flv"
fi

echo -n "Playing video: "
echo "~/.yt/$t.flv"
mplayer "$HOME/.yt/$t.flv" -title "$t" -heartbeat-cmd "$stopsaver" > /dev/null 2>&1

exit 0

mmswitch
* The variables $monitor1, $monitor2, and $m2type can be changed to your liking

#!/bin/bash
# Automatically switches to and from multimonitor mode when the VGA cable is connected
#
# Usage:
#	mmswitch &
# Exit Status:
#	1	Another instance exists

r=`ps ax | grep mmswitch | wc -l`
if [ $r -gt 3 ]
then
	echo "Already running."
	exit 1
fi

mode=0

monitor1="--output LVDS1 --mode 1366x768 --rotate normal"
monitor2="--output VGA1 --mode 1280x1024 --rotate normal"
m2type="VGA1 connected"

while :
do
	xrandr --prop | grep -q "$m2type"
	if [ $? -eq 0 ]; then
		if [ $mode -ne 2 ]; then
			echo "Entering multimonitor mode..."
			xrandr $monitor1 --pos 0x688 $monitor2 --pos 1366x0
			mode=2
		fi
	else
		if [ $mode -ne 1 ]; then
			echo "Leaving multimonitor mode..."
			xrandr $monitor1 --pos 0x0 --output VGA1 --off
			mode=1
		fi
	fi
	sleep 3
done

Last edited by piluke (2013-02-02 22:08:45)

Offline

#2019 2013-02-07 10:05:53

moetunes
Member
From: A comfortable couch
Registered: 2010-10-09
Posts: 1,033

Re: Post your handy self made command line utilities

I wanted a light 'n easy way to serve a homepage to the comps on the lan and came up with what I believe is a pretty light solution. Way easier than configuring a web server:

while true; do ncat -l -p 1500 --send-only < ~/lanpage.http; done

To connect to it enter the ip address of the comp running it and the port:

192.168.0.40:1500

I have a static ip for the fileserver it runs on which makes it easy. wink

Last edited by moetunes (2013-02-07 10:09:34)


You're just jealous because the voices only talk to me.

Offline

#2020 2013-02-07 10:44:04

kaszak696
Member
Registered: 2009-05-26
Posts: 543

Re: Post your handy self made command line utilities

cd ~/somewhere; python -m http.server 1500

does a similar thing, requires it's own directory with index.html, but the command is shorter ;p

Last edited by kaszak696 (2013-02-07 10:48:44)


'What can be asserted without evidence can also be dismissed without evidence.' - Christopher Hitchens
'There's no such thing as addiction, there's only things that you enjoy doing more than life.' - Doug Stanhope
GitHub Junkyard

Offline

#2021 2013-02-07 19:50:02

moetunes
Member
From: A comfortable couch
Registered: 2010-10-09
Posts: 1,033

Re: Post your handy self made command line utilities

kaszak696 wrote:
cd ~/somewhere; python -m http.server 1500

does a similar thing, requires it's own directory with index.html, but the command is shorter ;p

I had a brief look at that and it can't just serve a webpage, also the syntax is different for python2 and python3 which is another added complication. Since it is python based I'd have to question its' resource use and speed too.
So the python command wins on command line length but loses on ease of use. wink

Last edited by moetunes (2013-02-07 19:51:24)


You're just jealous because the voices only talk to me.

Offline

#2022 2013-02-09 03:57:49

Datsundere
Member
Registered: 2013-02-09
Posts: 2

Re: Post your handy self made command line utilities

Offline

#2023 2013-02-09 11:23:42

MatejLach
Member
From: United Kingdom
Registered: 2011-06-22
Posts: 314
Website

Re: Post your handy self made command line utilities

I think, I am going to use this.
Thanks for sharing!

Offline

#2024 2013-02-09 12:04:17

theGunslinger
Member
Registered: 2011-05-20
Posts: 300

Re: Post your handy self made command line utilities

Wow just when I thought making something like this! Thank you sir.

Offline

#2025 2013-02-11 15:49:48

Steffo
Member
Registered: 2012-10-27
Posts: 34

Re: Post your handy self made command line utilities

I'm using this script for i3 wm in order to disable my notebook display and to set up the resolution of the external display.

#!/bin/bash

xrandr | grep "VGA1 connected" > /dev/null
[ $? -eq 0 ] && xrandr --output LVDS1 --off && xrandr --output VGA1 --auto

This script depends on xrandr.
If you want to use it, make this script executable and run it on startup.

Regards
Steffo

Offline

Board footer

Powered by FluxBB