You are not logged in.

#2076 2013-04-23 20:40:08

ResXaoC
Member
From: Nibiru
Registered: 2011-07-17
Posts: 15

Re: Post your handy self made command line utilities

jgreen1tc wrote:

Ah man, if only Ratpoison had support for wmctrl... this is exactly what I need. I might use it for when I tmpwm into Openbox.

Write it.

Offline

#2077 2013-04-24 14:09:58

ibrunton
Member
From: Canada
Registered: 2011-05-05
Posts: 270

Re: Post your handy self made command line utilities

I wrote a script to create new files based on my custom templates, so that I just have to type "new html index.htm", for example.  The original was in bash, but I recently redid it in Perl to add more functionality (and I'm much more familiar with Perl than bash).

Usage: new FILETYPE [FILENAME] [-- optional arguments]

The first argument is mandatory and is one of the files in the template folder (~/Dropbox/templates).  The 2nd argument is an optional name for the new file; if it's not given, then the filename will be taken from a directive in the template file; if that doesn't exist, the filename of the template will be used.

The script looks for the strings '#DATE#', '#PROJECT#', '#FILENAME#', '#UC_FILENAME#', and '#ARGS#', and replaces them with, respectively, the date and time, the current working directory, the filename, the filename in uppercase (I use this in my template for C header files), and optional arguments that can be anything, really.

If the file starts with this:

# default filename: main.c
# --

the script uses that filename to create the new file, and strips those first 2 lines from the new fil.

This is the script:

#!/usr/bin/env perl

# new
# 2013-04-15 15:04
# by Ian D Brunton <iandbrunton at gmail dawt com>

use Cwd;
use Modern::Perl;

my $filesdir = $ENV{HOME} . "/Dropbox/templates/";

my $filetype = $ARGV[0] or die ("usage: new TYPE [FILENAME] [-- arguments]");
my $filename = $ARGV[1] // "";
my $arg = "";
if ($filename eq "--") {
    $arg = join (" ", splice (@ARGV, 2));
    $filename = "";
}

open (FILE, "<", $filesdir . $filetype) or die ("No template for type `$filetype'.");
my @lines = <FILE>;
close (FILE);

my $i;
my $flag = 0;

for ($i = 0; $i < $#lines; $i++) {
    if ($lines[$i] =~ /^# --$/) {
	$flag = 1;
	last;
    }
    if ($lines[$i] =~ /^# default file name: (.+)$/i && !$filename) {
	$filename = $1;
    }
}

if (length ($filename) < 1) { $filename = $filetype }

if (-e $filename) {
    print "File `$filename' already exists.  Overwrite? y/n: ";
    my $r = <STDIN>;
    chomp ($r);
    if ($r !~ /^y$/i) { exit (1) }
}

my $ucfilename = uc ($filename);
my $project = cwd();
$project =~ s|.*?/([^/]+?)$|$1|;
my @t = localtime (time);
my $date = $t[5] + 1900 .'-'. $t[4] .'-'. $t[3] .' '. sprintf ("%02d", $t[2]) .':'. sprintf ("%02d", $t[1]);

if ($flag == 1) { splice (@lines, 0, ++$i) }

foreach (@lines) {
    $_ =~ s/#PROJECT#/$project/g;
    $_ =~ s/#FILENAME#/$filename/g;
    $_ =~ s/#UC_FILENAME#/$ucfilename/g;
    $_ =~ s/#DATE#/$date/g;
    if ($arg) { $_ =~ s/#ARG#/$arg/g }
}

open (FILE, ">", $filename) or die ("Cannot open file `$filename': $!");
foreach (@lines) {
    print FILE $_;
}
close (FILE);

exit (0);

Offline

#2078 2013-04-24 15:02:56

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

Re: Post your handy self made command line utilities

https://gist.github.com/milo64/5452770

A time-saving approach to mounting devices via cmd-line.
gvfs seems to take to much GNOME dependencies and 'mount' is just really annoying. I decided to make this. Hope it also suits you.

Just put the script in one of your $PATH.


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

Offline

#2079 2013-04-25 21:29:05

deepsoul
Member
From: Earth
Registered: 2012-12-23
Posts: 67
Website

Re: Post your handy self made command line utilities

Back before I had heard of rlwrap, I wrote the following simple shell function for having a readline input line with programs that do not support that natively:

rline () {
	socat READLINE EXEC:"$*",pty
}

Its usage is simply "rline <program>".  Socat takes input via the readline library and passes it to the stdin of the given program.  The ",pty" option makes it simulate a pseudo-TTY for programs that don't want to read from pipes.  I still use this wrapper function because I have known it to work when rlwrap didn't.  On the downside, it does not treat passwords specially, i.e. displays them in plain text.  Also, the input text is echo'd when it is passed to the program.


Officer, I had to drive home - I was way too drunk to teleport!

Offline

#2080 2013-04-29 16:56:38

xr4y
Member
Registered: 2011-05-06
Posts: 33

Re: Post your handy self made command line utilities

I started doing pull-ups about a year ago. I was in the worst shape of my life, always sitting infront of a computer both at home and at work and decided that my belly had to go. Initially I could not even do one proper pull-up but I kept doing them at least 3 times per week and now I am up to 10 in a row and have lost 12kg's.

I wrote this script based on "Pavel's Ladder Pull-ups" to keep myself going forward. I really recommend this excercise to all you archers/geeks/nerds/hackers that spend too much time infront of your computers and no time exercising. Pull-ups is the ultimate upper body exercise and can get you ripped with just 3 times/week * 15min, so having little time is no excuse. Consistency is the key!

Good luck!

#!/bin/bash

welcome() {
	clear
	echo '          "WELCOME TO LADDER PULL-UPS"'
	echo
	cat << "EOF"
______________OOOOo__________oOOOO______________   
----------------(`,----------\`,----------------
              )  (            )  (       
              /  |            |  \       
              |  |  \\\\\\//  |  |
              \  /  | -  - |  \  /
              /  \ (  a  a  ) /  \
              |   | |  L   | |   |
              |   | \  ==  / |   |
              |   /_.\____/._\   |
               \   ||      ||   /
                \  | '-..-' |  /
                |  ;        |
                | /          \ |
                 \            /
                  |          |
                  |    __    |
                  |===[LI]===|
                  )"""`""`"""(
                 /            \
                /    ,____,    \
               /'-._ .'  '. _.-'\
              /     /      \     \
              |    /        \    |
              (_  /          \  _)
               |  `\        /`  |
               |___|        |___|
               |===/        \===|
             _/\._(          )_./\_
           /`      |         |    _`\
           `""""`""           ""`"""`
EOF
	echo
	sleep 3
}

status() {
	case $(uname) in
		Darwin) voice=say    ;;
		Linux)	voice=espeak ;;
		*)      voice=:      ;;
	esac
	if [ ! -e $state ]; then
		clear
		echo -n "How many pull-ups can you perform? "
		read max
		if [ $max -lt 5 ]; then
			clear
			echo -n "Please come back when you can perfom at least 5 strict pull-ups."
			sleep 5
			clear
			exit 1
		fi
		echo $max > $state
		echo 0 >> $state
	fi
}

rest() {
	for (( countdown = $1; countdown > 0; countdown-- )); do
		clear
		echo -n "Countdown to next rep: $countdown"
		sleep 1
	done
	clear
}

ready() {
	echo
	echo -n "Hit ENTER when ready!"
	read
}

save() {
	echo $max > $state
	echo $day >> $state
}

RM() {
	clear
	for (( pullups = $max; reps >= 1; pullups = pullups - $1 )); do
		if [ $reps -le $day ]; then
			clear
			echo "Complete $(echo $(expr $pullups + $1)) pull-ups"
			$voice $(echo $(expr $pullups + $1)) > /dev/null 2>&1
			ready
			[[ $reps = 1 ]] && break
			rest $2
			let reps--
		else
			clear
			echo "Complete $(echo $pullups) pull-ups"
			$voice $(echo $pullups) > /dev/null 2>&1
			ready
			[[ $reps = 1 ]] && break
			rest $2
			let reps--
		fi
	done
}

state="$HOME/.pull-ups.txt"
welcome
status
reps=5
max=$(head -n 1 $state)
day=$(tail -n 1 $state)

[[ $max -lt 12 ]] && RM 1 120
[[ $max -gt 11 ]] && [[ $max -lt 20 ]] && RM 2 180
[[ $max -gt 19 ]] && RM 4 240

answer=''
while [ "$answer" != "Y|y" ] || [ "$answer" != "N|n" ]; do
	clear
	echo -n "Did you successfully complete todays reps? (Y/N) "
	read answer
	case $answer in
		Y|y)
			if [ $day = 4 ] && [ $max -lt 12 ]; then
				let max++
				day=0
				save
				clear
				echo -n "Congratulations! Moving up to ladder -=${max}=-"
				sleep 3
			elif [ $day = 4 ] && [ $max -gt 11 ]; then
				let max=max+2
				day=0
				save
				clear
				echo -n "Congratulations! Moving up to ladder -=${max}=-"
				sleep 3
			else
				let day++
				save
			fi
			clear
			break
			;;
		
		N|n)
			clear
			break
			;;
	esac
done

Last edited by xr4y (2013-05-02 08:51:14)

Offline

#2081 2013-04-30 04:34:22

Thme
Member
From: Raleigh NC
Registered: 2012-01-22
Posts: 105

Re: Post your handy self made command line utilities

Wasn't good at trying to remember my pacman aliases in zsh so I wrote this function in my zshrc for most cases which just makes all the common pacman actions a shorthand style command where it can be typed with "pac" followed by any command arguments without "-" (caps don't matter in the first positional parameter, it converts the initial letter to uppercase anyways). It should work in bash as well.). No need for error handling when pacman can do that. Simple and eliminated my long list of unused aliases... It was lot easier to remember just "pac" and any arguments i wanted to pass to it.....
"pac syu", "pac Syu", "pac u package.tar.xz" and "pac s package"  will all translate to their appropriate commands. It works for all actions I use, long ones as well under most conditions (if they're really complex they probably need to be typed out normally...)

#pacman shorthand function for .zshrc or bashrc...
pac() {
	ARG=$1
	ARGS=( ${*[*]:1:${#*[*]}} )
	IN="-$(tr '[:lower:]' '[:upper:]' <<<${1:0:1})${1:1}"
	# uncomment line below if using bash
     # [[ -n ${ARGS[0]} ]] && unset ARGS[0]	
    #comment out the line below if using bash.
	[[ -n ${ARGS[1]} ]] && unset ARGS[1]
	pacexec() {
		if [[ $USER == root && -z ${ARGS[*]} ]] ; then 
			pacman $IN
		elif [[ $USER == root && -n ${ARGS[*]} ]] ; then 
			pacman $IN ${ARGS[*]}
		elif [[ $USER != root && -z ${ARGS[*]} ]] ; then
			sudo pacman $IN
		elif [[ $USER != root && -n ${ARGS[*]} ]] ; then
			sudo pacman $IN ${ARGS[*]}
		fi
	}
pacexec
}

Last edited by Thme (2013-04-30 18:48:51)


"Hidden are the ways for those who pass by, for light is perished and darkness comes into being." Nephthys:
Ancient Egyptian Coffin Texts

Offline

#2082 2013-05-04 20:44:54

mios
Member
Registered: 2013-05-02
Posts: 3

Re: Post your handy self made command line utilities

I wrote a little script to search magnets from piratebay:

#!/bin/bash
# where to put torrent files
watch=$HOME/.rtorrent/watch/

# this function change the actual directory
# to the one we configure and converts the
# magnet link into a torrent file
magn() {
  cd $watch
  [[ "$1" =~ xt=urn:btih:([^&/]+) ]] || exit;
  echo "d10:magnet-uri${#1}:${1}e" > "meta-${BASH_REMATCH[1]}.torrent"
}

# read all the parameters to
# search using a for
for x in "$@"
do
  # replace spaces with squares
  x=$(echo $x | sed 's/\ /+/g')
  # get the base url with the text to search
  url="http://thepiratebay.sx/search/$x/0/7/0"
  # get the magnet with curl and a regex
  magnet=$(curl -s $url | grep -m1 'magnet:' | sed -r 's/.*(magnet:.*3A80).*/\1/')
  # get the name of the magnet with curl and a regex
  name=$(curl -s $url | grep -m1 'Details' | sed -r 's/.*>(.*)<\/a>$/\1/')
  # check if find anything
  if [ -z $magnet ]
    then
      # warn message if dont find anything
      echo "magnet: $x not found"
    else
echo "downloading magnet: $name"
      # convert the magnet into a torrent
      # file using the magn function
      magn $magnet
  fi
done

Last edited by mios (2013-05-04 20:51:08)

Offline

#2083 2013-05-04 22:01:39

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

Re: Post your handy self made command line utilities

Not much to this one except a creative name:

alias dog='src-hilite-lesspipe.sh'

Dog: like a `cat`, but more fun.

Use it to 'cat' highlighted files assuming you have src-highlight installed.


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#2084 2013-05-05 18:54:15

dodo3773
Member
Registered: 2011-03-17
Posts: 818

Re: Post your handy self made command line utilities

I found this great script to lower cpu frequency based on temperature:

https://github.com/Sepero/temp-throttle … hrottle.sh


I edited it to use cpupower and to use a static temperature (you have to give it your actual min cpu frequency in the cpupower line):

#!/bin/bash
# temp_throttle.sh max_temp

# USE CELSIUS TEMPERATURES.

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root" 1>&2
   exit 1
fi


#if [ $# -ne 1 ]; then
	# If temperature wasn't given, then print a message and exit.
#	echo "Please supply a maximum desired temperature in Celsius." 1>&2
#	echo "For example:  ${0} 60" 1>&2
#	exit 2
#else
	#Set the first argument as the maximum desired temperature.
	MAX_TEMP=85
#fi

# The frequency will increase when low temperature is reached.
let LOW_TEMP=$MAX_TEMP-5

CORES=$(nproc) # Get number of CPU cores.
echo -e "Number of CPU cores detected: $CORES\n"

# Temperatures internally are calculated to the thousandth.
MAX_TEMP=${MAX_TEMP}000
LOW_TEMP=${LOW_TEMP}000

# FREQ_LIST is a list (array) of all available cpu frequencies the system allows.
declare -a FREQ_LIST=($(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies))
# CURRENT_FREQ relates to the FREQ_LIST by keeping record of the currently set frequency.
let CURRENT_FREQ=1

function set_freq {
	echo ${FREQ_LIST[$1]}
		cpupower frequency-set -g "ondemand" -d "800MHz" -u ${FREQ_LIST[$1]}
}

function throttle {
	if [ $CURRENT_FREQ -ne $((${#FREQ_LIST[@]}-1)) ]; then
		let CURRENT_FREQ+=1
		echo -n "throttle "
		set_freq $CURRENT_FREQ
	fi
}

function unthrottle {
	if [ $CURRENT_FREQ -ne 0 ]; then
		let CURRENT_FREQ-=1
		echo -n "unthrottle "
		set_freq $CURRENT_FREQ
	fi
}

function get_temp {
	# Get the system temperature.
	# If one of these doesn't work, the try uncommenting another.
	
	TEMP=$(cat /sys/class/thermal/thermal_zone0/temp)
	#TEMP=$(cat /sys/class/hwmon/hwmon0/temp1_input) 
	#TEMP=$(cat /sys/class/hwmon/hwmon1/device/temp1_input)
}

while true; do
	get_temp
	if   [ $TEMP -gt $MAX_TEMP ]; then # Throttle if too hot.
		throttle
	elif [ $TEMP -le $LOW_TEMP ]; then # Unthrottle if cool.
		unthrottle
	fi
	sleep 3
done

 


So the original is not mine but figured I'd share my version with you guys anyways.

Offline

#2085 2013-05-06 08:31:03

Roken
Member
From: South Wales, UK
Registered: 2012-01-16
Posts: 1,281

Re: Post your handy self made command line utilities

dodo3773 wrote:

I found this great script to lower cpu frequency based on temperature:

https://github.com/Sepero/temp-throttle … hrottle.sh


I edited it to use cpupower and to use a static temperature (you have to give it your actual min cpu frequency in the cpupower line):


So the original is not mine but figured I'd share my version with you guys anyways.

I like this. I wrote a script a long time ago using zenity to manually change CPU freq on the fly, but this is better. However, none of the temperature reading lines works here. The following does, using sensors:

TEMP=$(echo $(sensors | grep temp3 | awk '{print $2}' | sed 's/\+//' | sed 's/\..*//')*1000 | bc)

You do, of course, need to know which sensor is your CPU and substitute that in the grep.

systemd service created to autostart at boot for a complete "fire and forget" option smile

Last edited by Roken (2013-05-06 08:31:44)


Ryzen 5900X 12 core/24 thread - RTX 3090 FE 24 Gb, Asus Prime B450 Plus, 32Gb Corsair DDR4, Cooler Master N300 chassis, 5 HD (1 NvME PCI, 4SSD) + 1 x optical.
Linux user #545703

/ is the root of all problems.

Offline

#2086 2013-05-08 10:55:51

kriz
Member
Registered: 2009-06-29
Posts: 96

Re: Post your handy self made command line utilities

put this in .bashrc (or .bash_aliases (if defined))

alias update='sudo reflector -l 5 --sort rate ;sudo pacman -Sy ;sudo powerpill-light -u ; yaourt -Su --aur'

gets 5 updated mirrors sorted by speed -> repo refresh -> parralelized downloading and installation -> aur package update

requires following packages

pacman2aria2 yaourt reflector

„Je verdinglichter die Welt, je dichter das Netz, das der Natur überworfen wurde, desto mehr beansprucht ideologisch das Denken, das jenes Netz spinnt, seinerseits Natur, Urerfahrung zu sein." Theodor W. Adorno [aus: Wozu noch Philosopie]

Offline

#2087 2013-05-08 12:43:51

fsckd
Forum Fellow
Registered: 2009-06-15
Posts: 4,173

Re: Post your handy self made command line utilities

Merged kriz's thread from Community Contributions. Title was "fast update alias".


aur S & M :: forum rules :: Community Ethos
Resources for Women, POC, LGBT*, and allies

Offline

#2088 2013-05-08 13:17:31

Awebb
Member
Registered: 2010-05-06
Posts: 6,602

Re: Post your handy self made command line utilities

#!/bin/bash
echo "$1" >> ~/.newsbeuter/urls
sed "s/feed:/http:/g" ~/.newsbeuter/urls > /tmp/newsbeuterurltmp
cp /tmp/newsbeuterurltmp ~/.newsbeuter/urls

I know, it's ugly. It found the way to life last night, when I was frustrated about the fact, that I cannot automatically add feeds from firefox to newsbeuter. Call me stupid, but I forgot how to use sed to change some lines in a file and write it back to that file, hence the ugly tempfile approach. Did I forget how to do my job over night, or does sed not accept simple text input? Do I really have to echo $1 | sed...?

*doing some research and experiments*

#!/bin/bash
sed "s/feed:/http:/g" <(echo "$1") >> ~/.newsbeuter/urls

Yeah, ok. Looks better.

Cownose, the cat: You can have firefox give the feed-URI to the script and it will append it to the newsbeuter urls file. It will also replace the ugly "feed://" by a nice "http://".

Last edited by Awebb (2013-05-08 13:23:17)

Offline

#2089 2013-05-08 13:22:14

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

Re: Post your handy self made command line utilities

Awebb wrote:

Call me stupid, but I forgot how to use sed to change some lines in a file and write it back to that file

`sed -i /pattern/ file` though with the revision it's irrelevant.  Sed seems like overkill though

echo ${1/feed:/html:} >> ~/.newsbeuter/urls

EDIT: if relevant "echo ${@/feed:/html}" would allow for passing any arbitrary number of feeds on the command line - though, without some adjustment, they would not be separated by newlines.

Last edited by Trilby (2013-05-08 13:30:29)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#2090 2013-05-08 13:24:43

Awebb
Member
Registered: 2010-05-06
Posts: 6,602

Re: Post your handy self made command line utilities

Trilby wrote:
Awebb wrote:

Call me stupid, but I forgot how to use sed to change some lines in a file and write it back to that file

`sed -i /pattern/ file` though with the revision it's irrelevant.  Sed seems like overkill though

echo ${1/feed:/html:} >> ~/.newsbeuter/urls

Holy cow. I have once made my living doing virtually nothing else but working with bash scripts for a while and I still know nothing. Thanks!

Offline

#2091 2013-05-09 21:27:19

Baryon
Member
Registered: 2011-08-12
Posts: 72

Re: Post your handy self made command line utilities

My most useful one-liner:

dwb "$(echo -e "d\nfr2en\nsp2en\nbeo\nde2fa\nen2fr\nen2sp" | dmenu) $(xclip -o)"

This interacts with dwb and yubnub to allow me to highlight a word and then search for it in various different online dictionaries.

ID=your-dropbox-id
convert "$1" -resize 800 "/home/user/Dropbox/Public/photospublic/$(basename "$1")"
echo "https://dl.dropboxusercontent.com/u/$ID/photospublic/$(basename "$1")" | xclip -i

This downsizes an image, copies it to a public Dropbox folder and then puts the public link into the clipboard (using xclip).

ibrunton wrote:

I wrote a script to create new files based on my custom templates, so that I just have to type "new html index.htm", for example.

Great idea... I ought to have done something like that by now.

Offline

#2092 2013-05-10 11:42:01

graph
Member
Registered: 2010-12-21
Posts: 105

Re: Post your handy self made command line utilities

I got bored and made a password-generator in bash. Not the first to do so, but it has support for different ascii classes, statistics and can make a password based on required bits. Comments on how to improve my bash scripting is encouraged.

options can be viewed by issuing "-help" as argument (or looking at the script)

#!/bin/bash
# Generate random passwords
# Usage: genpass [OPTIONS]

#-------------------------------------------------------------------------------
#  Variables
#-------------------------------------------------------------------------------

# DEFAULT VARIABLES
default_length="20"                 # Password length to use as default
default_count="1"                   # Number of passwords to generate as default
default_charset="[:graph:]"         # Character set to use as default
default_source="/dev/urandom"       # Random source to use as default
default_stats="yes"                 # Print statistics?
default_highlight_pass="no"         # Higlight capitals in passwords?
default_color_stats="yes"           # Color on statistics?

# Text formatting
underline=$(echo -e "\033[4m")
reset=$(echo -e "\033[0m")
black=$(echo -e "\033[30m")
red=$(echo -e "\033[31m")
green=$(echo -e "\033[32m")
yellow=$(echo -e "\033[33m")
blue=$(echo -e "\033[34m")
purple=$(echo -e "\033[35m")
lblue=$(echo -e "\033[36m")
white=$(echo -e "\033[37m")

#-------------------------------------------------------------------------------
#  Functions
#-------------------------------------------------------------------------------

print_help(){
	echo -e "$(basename $0) [OPTIONS]\n" >&2
	echo "OPTIONS:" >&2
	echo -e "-l, -length\tLength of password" >&2
	echo -e "-c, -charset\tCharacterset to use, in form \"[:charset:]\"" >&2
	echo -e "-n, -count\tNumber of passwords to generate" >&2
	echo -e "-b, -bits\tGenerate password with this number of bits" >&2
	echo -e "-s, -source\tSource of random entropy" >&2
	echo -e "-a, -highlight\tHighlight capitals in generated password" >&2
	echo -e "-q, -quiet\tDo not print statistics after generation" >&2
	echo -e "-h, -help\tPrint this help text" >&2
	echo -e "\nDEFAULTS:" >&2
	echo "$(basename $0) -l ${default_length} -c ${default_charset} -s ${default_source} -n ${default_count}" >&2
}

get_charset(){
    # Set charset & character-range
    case ${@} in
        graph|"[:graph:]")
            charset="[:graph:]"
            range=93
            ;;
        print|"[:print:]")
            charset="[:print:]"
            range=94
            ;;
        alnum|"[:alnum:]"|alphanumeric)
            charset="[:alnum:]"
            range=63
            ;;
        alpha|"[:alpha:]"|"[a-zA-Z]")
            charset="[:alpha:]"
            range=52
            ;;
        punct|"[:punct:]")
            charset="[:punct:]"
            range=32
            ;;
        lower|"[:lower:]"|lowercase|"[a-z]")
            charset="[:lower:]"
            range=26
            ;;
        upper|"[:upper:]"|uppercase|"[A-Z]")
            charset="[:upper:]"
            range=26
            ;;
        xdigit|"[:xdigit:]"|hex)
            charset="[:xdigit:]"
            range=22
            ;;
        digit|"[:digit:]"|digits|"[0-9]")
            charset="[:digit:]"
            range=10
            ;;
        bin|"[:bin:]"|binary)
            charset="01"
            range=2
            ;;
        *)
            echo "Error: Character set \"${@}\" could not be recognized." >&2
            exit 1 ;;
    esac

}

calc_possibilities(){
	# Calculate possibilities as one long number
	raw_possibilities=$(echo ""${range}"^"${length}"" | bc -l | paste -sd "" | sed 's/\\//g')
	# Print possibilities as a power of 10
	echo "$(printf "%3.3e\n" $raw_possibilities | sed 's/e+/\*10^/g') possibilities" >&2
}

#-------------------------------------------------------------------------------
#  Script
#-------------------------------------------------------------------------------

# Get options and act accordingly
# NB: ":" means options required, hence no ":" with help/quiet
while getopts l:c:n:s:b:aqh option; do
	case "${option}" in
		l|length) 	
			length="${OPTARG}" ;;
		c|charset)
            get_charset "${OPTARG}" ;;
		n|count) 	
			count="${OPTARG}" ;;
		s|source)
			source="${OPTARG}" ;;
		b|bits)
			bits="${OPTARG}" ;;
		a|highlight)
			highlight_pass="yes" ;;
		q|quiet) 	
			stats="no" ;;
		h|help)
			print_help ${OPTARG}
			exit 0
			;;
	esac
done

# Make sure that -l and -b are not used together
# Since specifying $bits calculates $length, and vice-versa
# NB: This needs to be executed before applying default settings
if [[ -n ${bits} ]] && [[ -n ${length} ]]; then
	echo "Error: Option \"-l\" cannot be used together with option \"-b\"" >&2
	exit 1
fi

# Set defaults if not set already
: ${length:="$default_length"}
: ${charset:="$default_charset"}
: ${count:="$default_count"}
: ${source:="$default_source"}
: ${stats:="$default_stats"}
: ${highlight_pass:="$default_highlight"}
: ${color_stats:="$default_color_stats"}

# Run get_charset again if default_charset is used, to get proper range
[[ "${charset}" = "${default_charset}" ]] && get_charset "${charset}"

# Make password length from desired number of bits,
# if $bits is set by the -b flag
# Needs to be after charset case-statement, and before setting of defaults
# NB: Since bc truncates decimals, we are adding 1 character to the length to be sure
if [[ -n ${bits} ]]; then
	# Equation: Length = Bits / ( log(Range) / log(2) )
	length=$(echo "scale=2;((${bits})/(l(${range})/l(2)))+1" | bc -l | cut -d. -f1)
fi

# Generate passwords
# Check if highlighting is on (-a)
if [ "${highlight_pass}" = "yes" ]; then
    # Highlight stuff
	while [ "${count}" -gt 0 ]; do
        echo $(<${source} tr -dc "${charset}" | head -c${length}) | \
            sed \
                -e "s/[0-9]/${lblue}&${reset}/g" \
                -e "s/[A-Z]/${yellow}&${reset}/g"
        count=$((${count} - 1))
	done
else
    # No highlighting
	while [ "${count}" -gt 0 ]; do
		echo $(<${source} tr -dc "${charset}" | head -c${length})
		count=$((${count} - 1))
	done
fi

# If quiet is not invoked (-q), print statistics
if [ ${stats} = "yes" ]; then
    if [ ${color_stats} != "yes" ]; then
        purple=""
        reset=""
    fi
    echo "${purple}--- Statistics ---"	
	# Print length if $bits is set
	[[ -n ${bits} ]] && echo "${length} characters"
    
	# Calculate possibilities
	calc_possibilities
	    
    # Calculate bits of security
	# Bits = Length * ( log(Range) / log(2) )
    echo "$(echo 'scale=2;'${length}'*(l('${range}')/l(2))' | bc -l) bits${reset}"
fi

exit 0

Last edited by graph (2013-09-20 09:53:57)

Offline

#2093 2013-05-10 23:30:54

ResXaoC
Member
From: Nibiru
Registered: 2011-07-17
Posts: 15

Re: Post your handy self made command line utilities

graph wrote:

I got bored and made a password-generator in bash. Not the first to do so, but it has support for different ascii classes, statistics and can make a password based on required bits. Comments on how to improve my bash scripting is encouraged.

Use \e[*m instread of tput.

\e[0m - default
\e[1m - bold
\e[3*m - foreground
\e[4*m - background
\e[*0m - black
\e[*1m - red
\e[*2m - green
\e[*3m - yelow
\e[*4m - blue
\e[*5m - purple
\e[*6m - light blue
\e[*7m - white
\e[33;1m - yellow foreground; bold
\e[34;41;1m - blue foreground; red background; bold
\e[45;1m - purple backgorund; bold
\e[37;42m - white foreground; green background
Check this with printf or echo -e: "\e[1mS\033[0;34m\e[0;45ma\e[31mm\033[44;1mp\e[0ml\e[30;46;1me\e[0m"
\e equals \033 

Offline

#2094 2013-05-10 23:33:52

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

Re: Post your handy self made command line utilities

I've never tracked down details on this, but \003[ has proven much more 'portable' or reliable under varied conditions than \e[.  I'm guessing (just guessing at this point) that the later is an optional feature of some terminals or terminfo settings.

Unfortunately these are rather difficult terms to google for to learn more.

Last edited by Trilby (2013-05-10 23:34:55)


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#2095 2013-05-11 05:46:27

ResXaoC
Member
From: Nibiru
Registered: 2011-07-17
Posts: 15

Re: Post your handy self made command line utilities

Trilby wrote:

I've never tracked down details on this, but \003[ has proven much more 'portable' or reliable under varied conditions than \e[.  I'm guessing (just guessing at this point) that the later is an optional feature of some terminals or terminfo settings.

Unfortunately these are rather difficult terms to google for to learn more.

033 is octal and e is hexademical representation. No?

Offline

#2096 2013-05-11 11:06:37

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

Re: Post your handy self made command line utilities

No.  The equivalent of e (hex) in octal would be  16, or 33 (octal) un hex would be 1b.  I think e just stands for "escape", but what they represent is not particularly relevant - I'm just speaking from my experience about whether or not they work - and \e[ does not work consistently (for me).


"UNIX is simple and coherent" - Dennis Ritchie; "GNU's Not Unix" - Richard Stallman

Offline

#2097 2013-05-11 12:57:59

ResXaoC
Member
From: Nibiru
Registered: 2011-07-17
Posts: 15

Re: Post your handy self made command line utilities

Understood.

Offline

#2098 2013-05-12 11:17:14

graph
Member
Registered: 2010-12-21
Posts: 105

Re: Post your handy self made command line utilities

ResXaoC wrote:

Use \e[*m instread of tput.

Thanks for your input. Why is this better than tput? Because it is native where tput is a dependency?

Trilby wrote:

I've never tracked down details on this, but \003[ has proven much more 'portable' or reliable under varied conditions than \e[

I've edited my script to use \003[ just in case, so thanks for the heads up.

Last edited by graph (2013-05-12 12:03:01)

Offline

#2099 2013-05-12 18:45:31

Vain
Member
Registered: 2008-10-19
Posts: 179
Website

Re: Post your handy self made command line utilities

A launcher for sxiv named "i":

#!/bin/bash

[[ -z $1 ]] && sel=(.) || sel=("$@")
imgs=()
for i in "${sel[@]}"
do
	[[ -d "$i" ]] && imgs+=("$i"/*) || imgs+=("$i")
done
sxiv -qt "${imgs[@]}"

Show all images in the current directory:
$ i

Show images in the selected directories:
$ i ~/gfx/Fotos ~/gfx/Wallpapers

Show selected images and images in the selected directories:
$ i foo.png bar.png ~/gfx/Fotos

It only shows what's directly inside a directory -- no recursion. When I want recursion, I use "ir":

#!/bin/bash

[[ -z $1 ]] && sel=(.) || sel=("$@")
sxiv -qtr "${sel[@]}"

Recursively show all images in those two directories:
$ ir ~/gfx/Fotos ~/gfx/Wallpapers

Recursively show all images in the current directory:
$ ir

They always put me in thumbnail mode. Before zooming in on single images, I want to get a rough overview.

Offline

#2100 2013-05-12 19:01:37

Piki
Member
From: Cyberspace
Registered: 2012-03-13
Posts: 12

Re: Post your handy self made command line utilities

For thos that are used to the old 'service' command on some other distros, or who use tab-completion and find it annoying how many sys* commands there are:

#!/bin/bash
if [ $1 == "start" -o $1 == "restart" -o $1 == "stop" -o $1 == "status" ] ; then
	systemctl $1 $2
elif [ $2 == "start" -o $2 == "restart" -o $2 == "stop" -o $2 == "status" ] ; then
	systemctl $2 $1
else
	echo "Incorrect syntax. Please use either:"
	echo "service {start|stop|restart|status} {service_name}"
	echo "service {service_name} {start|stop|restart|status}"
fi

As is obvious to those experienced with shell scripts, it can accept the arguments in either order (e.g. "service something start" and "service start something" are both valid).


--
Piki
"Many people have died for their beliefs. The real courage is in living and suffering for what you believe in." Brom, character in 'Eragon' by Christopher Paolini

Offline

Board footer

Powered by FluxBB