You are not logged in.

#1976 2012-10-27 09:08:24

illusionist
Member
From: localhost
Registered: 2012-04-03
Posts: 498

Re: Post your handy self made command line utilities

@AronBP
Please edit your typo... tongue

#!/bin/dash

#!/bin/bash

  Never argue with stupid people,They will drag you down to their level and then beat you with experience.--Mark Twain
@github

Offline

#1977 2012-10-27 09:49:28

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

Re: Post your handy self made command line utilities

illusionist wrote:

@AronBP
Please edit your typo... tongue

#!/bin/dash

#!/bin/bash

Heh, not really a typo.

Still, I try to change it to /bin/sh when posting so everyone can use it, but I forgot. Sorry!

EDIT:

Here's V2, modified to work with multiple packages like I wanted it to.

#!/bin/sh

# Return n packages not found.
ret=0
for i in $@
do
	url=$(eval "expac '%u' "$i" || expac -S '%u' "$i"")
	if [ $? -eq 0 ]
	then
		xdg-open "$url"
	else
		echo "$i not found." 1>&2
		ret=$(expr $ret + 1) 
	fi
done

exit $ret

Last edited by AaronBP (2012-10-27 10:02:23)

Offline

#1978 2012-10-27 10:01:39

illusionist
Member
From: localhost
Registered: 2012-04-03
Posts: 498

Re: Post your handy self made command line utilities

@AronBP
Sorry I was not familiar with "dash" , It gave me error , so I thought it was a typo . neutral


  Never argue with stupid people,They will drag you down to their level and then beat you with experience.--Mark Twain
@github

Offline

#1979 2012-10-29 09:45:03

jurassicplayer
Member
Registered: 2012-10-29
Posts: 1

Re: Post your handy self made command line utilities

Well, I didn't really find anything like what I was hoping for, and so I attempted to make my own bash script for wallpaper changing. It's catered more towards openbox usage, but it could probably edited easily enough anyways.

I'm rather new at bash scripts, so there is a high chance that it is...messy or poorly implemented. If anyone can help me out with that, it would be nice.

#!/bin/bash
#--------------------------------------------------------------------
#                   Wallpaper Changer Script
#                            -------
# Allows for separate image directories for each virtual desktop
# and will change to random images within the directory when called.
# Calling with "c" is for an Openbox pipemenu allowing the user to
# manually change the current wallpaper to a different one within 
# the defined desktop image directory.
# Also, I have no idea how or why it works, but if you leave the 
# directories undefined, it still works but will use all images
# from the folders that were previously defined...
#                        Configurations
#                            -------
# Choose directory with images for each desktop
# Change command of wallpaper setting program (feh default)
#-------------------------------------------------------------------
DIR0='/home/jplayer/.config/openbox/wallpapers/light'
DIR1='/home/jplayer/.config/openbox/wallpapers/dark'
DIR2='/home/jplayer/.config/openbox/wallpapers/cute'

DESKTOP=$(xprop -root _NET_CURRENT_DESKTOP | awk '{print $3}')
DIRNAME=DIR$(xprop -root _NET_CURRENT_DESKTOP | awk '{print $3}')
eval DIR=\$$DIRNAME
if [ "$1" == "c" ]; then
     echo '<openbox_pipe_menu>'
     DESKTOP=$(($(xprop -root _NET_CURRENT_DESKTOP | awk '{print $3}')+3))
     DESKTOPID=$(xprop -root _NET_DESKTOP_NAMES | sed 's/"//g' | sed 's/,//g' | awk "{print \$$DESKTOP}")
     echo '<separator label="'$DESKTOPID'"/>'
     echo '<item label="Random">'
     echo '<action name="Execute">'
     echo '<execute>~/.config/openbox/pipemenus/wallpaper</execute>'
     echo "</action></item>"
# List files in corresponding desktop directory
     ls $DIR |
     (
     while read line
     do
     echo $line
     echo '<item label="'$line'">'
     echo '<action name="Execute">'
     FEH='feh --bg-fill '$DIR/$line
     echo '<execute>'$FEH'</execute>'
     echo "</action></item>"
     done
     )
# Close PipeMenu
     echo '</openbox_pipe_menu>'
# Handle wallpaper changing
else
     feh --bg-fill $(find $DIR -type l -iregex '.*\.\(bmp\|gif\|jpg\|png\)$' | sort -R | head -1)
     echo $DIR
fi

Offline

#1980 2012-11-01 17:01:30

Kleiny
Member
From: Paris, France
Registered: 2012-11-01
Posts: 5

Re: Post your handy self made command line utilities

Hi !
I made a backlight control script since I was unable to manage it with xbacklight. It may be useful for those who also experienced troubles with xbacklight (or other backlight manager) and get errors like this :

No outputs have backlight property

but are able to control the backlight by setting a value in the file "/sys/class/backlight/acpi_video0/brightness".
So the script intends to easily manage this value.

#!/bin/bash

# Backlight control
#
# Uses the file /sys/class/backlight/acpi_video0/brightness to
# set or get the backlight value.

FILE="/sys/class/backlight/acpi_video0/brightness"
FILE_MAX="/sys/class/backlight/acpi_video0/max_brightness"

option=$1
value=$2
max=

function write_value
{
	if [ -w $FILE ]; then
		echo $value > $FILE
		exit 0
	else
		echo "Permission denied. Make sure you have the permission to write in the file /sys/class/backlight/acpi_video0/brightness"
		exit 1
	fi
}

function set_bl
{
	if [ $value -lt 0 -o $value -gt $max ]; then
		echo "Invalid argument: value must be between 0 and $max."
		exit 1
	else
		write_value
	fi	
}

function inc_bl
{
	get_current_value
	if [ $currentValue = $max ]; then
		exit 0
	else
		value=$(($currentValue+1))
		write_value
	fi
}

function dec_bl
{
	get_current_value
	if [ $currentValue = 0 ]; then
		exit 0
	else
		value=$(($currentValue-1))
		write_value
	fi
}

function max_bl
{
	value=$max
	write_value
}

function current_bl
{
	get_current_value
	echo "$currentValue ($max is the maximum)"
}

function get_current_value
{
	while read line; do
		currentValue=$line
	done < $FILE		
}

function get_max_value
{
	while read line; do
		max=$line
	done < $FILE_MAX
}

function help_info
{
	echo -e "usage: backlight [options]\nwhere options are:"
	echo -e "\t=, -set <value [0,$max]>\tSet the backlight value"
	echo -e "\t--, -dec\t\tDecrease the backlight value"
	echo -e "\t++, -inc\t\tIncrease the backlight value"
	echo -e "\t-max\t\tSet the maximal backlight value"
	echo -e "\t-get\t\t\tGet the current and maximal backlight value"
	echo -e "\t-h, --help\t\tThis help"
	echo -e "\nNote: you must have the permission to write in the file /sys/class/backlight/acpi_video0/brightness"
}


### Main

get_max_value

case $option in
	= | -set )		set_bl
					;;
	-- | -dec)		dec_bl
					;;
	++ | -inc )		inc_bl
					;;
	-max )			max_bl
					;;
	-get )			current_bl
					;;
	-h | --help )	help_info
					;;
	* )				echo "Invalid argument: unknown option."
					;;
esac

Help is included. Root permission by default, but it's more convenient to disable password request (sudoers) for key bindings.
Hope it can help ! It's my very first script. smile

Offline

#1981 2012-11-05 02:56:08

Spoofing
Member
From: Russian Federation
Registered: 2012-11-05
Posts: 24

Re: Post your handy self made command line utilities

tmux is just convenient for the preservation of running programs

alias mcabber="tmux attach-session -t mcabber || tmux new-session -d -s mcabber mcabber \; set status off \; attach"
alias mutt="tmux attach-session -t mutt || tmux new-session -d -s mutt mutt \; set status off \; attach"
alias irssi="tmux attach-session -t irssi || tmux new-session -d -s irssi irssi \; set status off \; attach"

Offline

#1982 2012-11-05 12:29:44

Earnestly
Member
Registered: 2011-08-18
Posts: 805

Re: Post your handy self made command line utilities

If that's all you need tmux for have a look at dtach and reptyr combined. (dtach talks over a socket, so you just connect to that.)

Offline

#1983 2012-11-05 12:49:56

Runiq
Member
From: Germany
Registered: 2008-10-29
Posts: 1,053

Re: Post your handy self made command line utilities

Kaustic wrote:

If that's all you need tmux for have a look at dtach and reptyr combined. (dtach talks over a socket, so you just connect to that.)

Reptyr is seriously ooh, nice. Thanks for that!

Offline

#1984 2012-11-08 17:12:52

jakobcreutzfeldt
Member
Registered: 2011-05-12
Posts: 1,033

Re: Post your handy self made command line utilities

Here's "some", which uses source-highlight to colorize text files according to their syntax and then pipes them through less. So, it's basically less with syntax highlighting.

#!/bin/bash

if [ ! -x `which source-highlight` ]; then
    echo "GNU source-highlight is required" && exit 1
fi

if [[ $1 == "--help" ]]; then
    echo "some: it's like less but with more"
    echo ""
    echo "USAGE: some [FILE]"
    echo "       some - [LANGUAGE]"
    echo ""
    echo "To read from a pipe, use the second form. In this case, you"
    echo "must specify a language for the syntax coloring. See"
    echo "source-highlight(1) for more info"
    exit 0
fi

# source-highlight can autodetect many file extensions but it still
# misses some. If you use this and the output isn't properly colorized
# you should create your own lang.map file copying the system one and
# extend it as necessary. 
#
# Default: $HOME/.config/source-highlight/lang.map
if [ -e $XDG_CONFIG_HOME/source-highlight/lang.map ]; then
    LANG_MAP=$XDG_CONFIG_HOME/source-highlight/lang.map
else
    LANG_MAP=/usr/share/source-highlight/lang.map
fi

# Arguments to pass to source-highlight. You can add more arguments
# here, like '-n' to add line-numbering
S_H_ARGS="--failsafe --lang-map=${LANG_MAP} -f esc -o STDOUT"

OLD_IFS=$IFS
IFS=""
buf=""
if [[ $1 == "-" ]]; then
    while read line; do
	if [[ "x$line" == "x" ]]; then
	    line="\f"
	fi
        buf=`cat <(echo $buf) <(echo $line)`
    done
fi
IFS=$OLD_IFS

if [[ "x$buf" != "x" ]]; then
    echo -e "$buf" | source-highlight $S_H_ARGS -s $2 | less -r
    exit 0
fi

if [ ! -e $1 ]; then
    echo "$1: No such file or directory" && exit 1
fi

do_less()
{
    if [ $# -eq 2 ]; then
	source-highlight $S_H_ARGS -s $2 -i $1 | less -R
    else
	source-highlight $S_H_ARGS -i $1 | less -R
    fi
}


filename=`basename $1`
ext=${filename#*.}
base=`basename $filename .$ext`

# Use Bash highlighting for dotfiles
if [[ $filename == .$ext ]]; then
    do_less $1 bash
    exit 0
fi	
# Otherwise let source-highlight guess
do_less $1

I recommend copying /usr/share/source-highlight/lang.map to your home directory somewhere (I use .config/source-highlight/lang.map) and setting the LANG_MAP variable to that location in the script. Then, you can easily add new mappings. For example, to use Shell highlighting for PKGBUILDS, add this line to your lang.map:

pkgbuild = sh.lang

To use Makefile highlighting for suckless config.mk files, add:

mk = makefile.lang

edit: nevermind, I adapted it to work with stdin. If you read from stdin you must specify a language, i.e.:

$ cat .bashrc | some - bash

Whereas this will automatically use bash highlighting:

$ some .bashrc

Last edited by jakobcreutzfeldt (2012-11-08 22:13:11)

Offline

#1985 2012-11-08 19:31:37

Trilby
Forum Moderator
From: Massachusetts, USA
Registered: 2011-11-29
Posts: 14,019
Website

Re: Post your handy self made command line utilities

Have you tried this:

export LESSOPEN="|/usr/bin/src-hilite-lesspipe.sh %s"

I have this in my bashrc, and this makes less pass everything through source-highlight and if it matches any known format it is highlighted appropriately - otherwise it is displayed with vanilla less.


InterrobangSlider
• How's my coding? See this page.
• How's my moderating? Feel free to email any concerns, complaints, or objections.

Offline

#1986 2012-11-08 22:03:58

jakobcreutzfeldt
Member
Registered: 2011-05-12
Posts: 1,033

Re: Post your handy self made command line utilities

Ehhhh....heh. No. I didn't know about that. Well, that makes things easier...

Ok I tried it and I have two observatons: 1) mine includes opening dotfiles with Bash coloring (which is usually correct, like .bashrc and .xinitrc), but it lacks the ChangeLog one which is easy enough to add. 2) the LESSOPEN one doesn't seem to work with pipes whereas mine does.

Eh, anyway, I'm just happy to have colorized less. It's the little things in life. smile

Last edited by jakobcreutzfeldt (2012-11-08 22:12:52)

Offline

#1987 2012-11-09 23:19:44

oeufcoque
Member
Registered: 2012-11-09
Posts: 19
Website

Re: Post your handy self made command line utilities

Here is a snippet I'm using to monitor and control long running bash scripts launched from fcrontab.

#!/bin/bash
# Executes $0 (this script) within a detached screen sesssion if the $STY variable isn't set.
# $STY is a environment variable set by screen when a session is made.
if [ -z "$STY" ] ; then
   # The session name is the full path to $0, with "/" replaced with "-"
   SESSION="$(readlink -f "$0" | tr '/' '-')"

   # I don't want the initial dash in the session name
   SESSION="${SESSION:1}"

   # Launch a detached screen session
   screen -dmS "$SESSION" "$0" $@

   # Attach the screen session if this is a terminal
   if [ -t 0 ] ; then
      echo "screen -r \"$SESSION\""
      screen -r "$SESSION"
      echo "Screen session ended with exit status: $?"
      echo "Pausing for 10 seconds..."
      sleep 10
   fi
   exit 0
fi
echo "Screen session established: $STY"

Here is a example explaining its usage further:

#!/bin/bash
source the-above-screen-snippet.sh

# At this point this script is running in a screen session.

# A long running command that backs up my home directory
rsync --verbose --recursive $HOME/ /mnt/home/
EXIT_STATUS=$?

# If this was launced by fcrontab, you won't get a mail with the output of
# the commands, since this is inside a screen session.
#
# As far as fcron knows this script has already ended, and the only reason
# you would have received an mail at this point, would be because the screen
# session failed to be created.
#
# In order to get mails I'm adding the following to scripts:
{
   # sendmail needs a line beginning with "Subject: "
   echo "Subject: Home backup script"
   echo "The script ended with exit status: $EXIT_STATUS

   # Of course you could have the above rsync command right here, then
   # you get to see the output in the screen session, as well as getting
   # the output sent in a mail to you
} | sendmail $USER@localhost

# sendmail could also be replaced with mutt. In those cases you could even attach
# files in the mails sent to you, such as a compressed archive of a log file rsync
# created.

I hope someone finds this as useful as I do

Offline

#1988 2012-11-10 13:44:41

grufo
Member
Registered: 2012-08-09
Posts: 64

Re: Post your handy self made command line utilities

Massively replace text in all files of a directory:
https://bbs.archlinux.org/viewtopic.php?pid=1190759

Offline

#1989 2012-11-11 17:28:18

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

Re: Post your handy self made command line utilities

Restart all running systemd services. This will kill x b.t.w.

#!/bin/bash
# Restart all systemd services that have status 'running'
systemctl list-units --type=service  --no-pager --no-legend --full \
    | grep -Po '^\S+(?=\s+loaded\s+active running)' \
    | (while read var1 ; do
            strservices+=" ${var1}"
        done
        #restart in one transaction to let systemctl handle dependencies
        systemctl restart $strservices
    )

In my case I want to skip a service named 'autologin' so the regex becomes  '^(?!autologin)\S+(?=\s+loaded\s+active running)'

Last edited by rwd (2015-10-25 15:09:00)

Offline

#1990 2012-11-13 14:45:15

pilotkeller
Member
From: Canada
Registered: 2011-12-22
Posts: 513
Website

Re: Post your handy self made command line utilities

Recently went to a security conference to compete in a CTF. Ended up needing this little gem to find every SUID and SGUID bin on the system. Great just to see if there is anything that shouldn't be root-boosted on your system.

find / -type f -perm +6000 -exec ls -l {} \;

Offline

#1991 2012-11-15 20:21:52

illusionist
Member
From: localhost
Registered: 2012-04-03
Posts: 498

Re: Post your handy self made command line utilities

Since this is so long thread, I do not know if it has been posted or not...
One liner to see the files without comments:

alias nocomment='grep -Ev '\''^(#|$)'\'''

Use:

nocomment /etc/mkinitcpio.conf

  Never argue with stupid people,They will drag you down to their level and then beat you with experience.--Mark Twain
@github

Offline

#1992 2012-11-15 20:32:02

steve___
Member
Registered: 2008-02-24
Posts: 439

Re: Post your handy self made command line utilities

illusionist wrote:

Since this is so long thread, I do not know if it has been posted or not...
One liner to see the files without comments:

alias nocomment='grep -Ev '\''^(#|$)'\'''

Use:

nocomment /etc/mkinitcpio.conf

This should work as well:

alias nocomment='grep -Ev "^(#|$)"'

Offline

#1993 2012-11-24 14:53:56

Spoofing
Member
From: Russian Federation
Registered: 2012-11-05
Posts: 24

Re: Post your handy self made command line utilities

Simple alarm clock, just edit the mplayer's command;
Usage: alarm 7:00

noise() {
  case "$1" in
    "mute"|"unmute")
      amixer -q set Master "$1"
      ;;
    *"%")
      amixer -q set PCM "$1"
      ;;
  esac
}
alarm() {
  local n=$(date +"%s")
  local w=$(date -d "$1" +"%s")
  [ "$w" -gt "$n" ] || w=$(($w + 86400))

  noise mute
  sleep $(($w - $n))
  noise unmute

  for i in {10..42}; do
    noise ${i}%
    sleep 2
  done &

  mplayer ~/Music/lossless/Tarja\ Turunen/My\ Winter\ Storm/CD1/Damned\ And\ Divine.flac
}

Offline

#1994 2012-12-02 03:22:06

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

Re: Post your handy self made command line utilities

An easy way to pick a dvb station to play in mplayer

#!/bin/bash

## Select DVB channel and
## show with mplayer

## load some values
chan_file=~/.mplayer/channels.conf
butlabel=""
a=0
sel_chan="OOPS"

## set it up so there are the right num buttons
##  and they have the right label
while IFS=':' read -r channel line; do
    [ "$a" -lt "1" ] && butlabel="$channel:$channel" || \
        butlabel="$butlabel,$channel:$channel"
    ((a++))
done < "$chan_file"

sel_chan=`xmessage -center -print -buttons $butlabel "Select Channel"`
exec mplayer dvb://"$sel_chan" -demuxer mpegts

exit 0

Last edited by moetunes (2012-12-02 03:23:18)


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

Offline

#1995 2012-12-03 17:30:04

mpnordland
Member
Registered: 2011-11-29
Posts: 46

Re: Post your handy self made command line utilities

A handy python calculator, here's a thread I started on it:

https://bbs.archlinux.org/viewtopic.php?id=153837

Offline

#1996 2012-12-04 22:47:16

fsckd
Forum Moderator
Registered: 2009-06-15
Posts: 3,565

Re: Post your handy self made command line utilities

I want to preview issue files so I made this with help from man agetty,

#!/bin/bash

sed -e 's,\\\\,\\,g' \
    -e 's,\\b,'"9001,g" \
    -e 's,\\d,'"$(date '+%a %b %e %Y'),g" \
    -e 's,\\s,'"$(uname -s),g" \
    -e 's,\\l,'"vc/$XDG_VTNR,g" \
    -e 's,\\m,'"$(uname -m),g" \
    -e 's,\\n,'"$(uname -n),g" \
    -e 's,\\o,'"$(hostname -d),g" \
    -e 's,\\O,'"$(hostname -f),g" \
    -e 's,\\r,'"$(uname -r),g" \
    -e 's,\\t,'"$(date +%T),g" \
    -e 's,\\u,'"$(users | wc -w),g" \
    -e 's,\\U,'"$(users | wc -w) users,g" \
    -e 's,\\v,'"$(uname -v),g" \
< "$1"

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

Offline

#1997 2012-12-06 00:19:42

burninate
Member
Registered: 2012-07-28
Posts: 22

Re: Post your handy self made command line utilities

fsckd wrote:

I want to preview issue files so I made this with help from man agetty

Thank you! Simple and useful.

Offline

#1998 2012-12-07 21:22:42

Skoglar
Member
Registered: 2011-05-15
Posts: 2

Re: Post your handy self made command line utilities

Yesterday i was trying to change my terminal font using setfont, but i just wanted to try every font out there, like, in the actual terminal, so i did a little script.

It puts you through every font in your /usr/share/kbd/consolefonts/ folder, showing the tipical "The quick brown fox jumps over the lazy dog" sentence and displaying the alphabet, numbers and some other characters, you can always decide whether to continue or not,  letting you "save" those fonts you found interesting, after that you will once more go through a list of your "saved" fonts and finally choose one, the script will automatically update your vconsole.conf file (you can actually do this at any given time by typing "select" when previewing a font)

so there it is...
it can manage a few flags (-s/--select to go to your selected fonts list automatically (since it's saved into a file), -h/--help to display a small help message)

#!/bin/bash

interestingFontsList=('')
red='\033[31m'
green='\033[32m'
purple='\033[35m'
defaultColor='\033[0m'
savedFonts="selectedfonts.txt"
configFile="/etc/vconsole.conf"
localCopy="vconsole.conf"
fontOpt=$(cat $configFile|grep FONT=)
newFontOpt="FONT=/usr/share/kbd/consolefonts/"
exampleText1="\n\nThe quick brown fox jumps over the lazy dog\n\n"
exampleText2="\tabcdefghijklmnopqrstuvwxyz\n\tABCDEFGHIJKLMNOPQRSTUVWXYZ\n"
exampleText3="\t1234567890\t°!\"#$%&/()?¡\n"

#Gets the name of every system fonts and shows it to the user
viewSystemFonts(){
	fontsPath="/usr/share/kbd/consolefonts"
	exclusions="-e README -e ERRORS -e partialfonts"

	#get the console fonts list
	local systemFontArray=($(ls $fontsPath|grep -v $exclusions))
	#let the user test every each one of them
	showcast systemFontArray[@]
}

#this always recieves an array (of system console fonts names)
showcast(){
	#initialize the arrays an vars
	local fontArray=("${!1}")
	pos1=0
	local savedFontsArray=($(cat $savedFonts))
	pos2=0
	broke="false"

	if [ ${#fontArray[@]} -eq ${#savedFontsArray[@]} ];
	then
		options="(y/n/select)"
		listTitle="Selected Fonts"
		highlight="true"
	else
		options="(y/n/save)"
		listTitle="Previously Selected Fonts"
		highlight="false"
	fi
	#for every font in the array
	for font in ${fontArray[@]}
	do
		let pos1=($pos1+1)
		pos2=1
		#set the font as the system
		setfont $font
		#print an example text
		echo -e $exampleText1 $exampleText2 $exampleText3

		#let the user know which font is currently in use
		echo -e $red"currently looking at: "$font"\n"$defaultColor

		#list the fonts the user has saved
		echo -e $listTitle"\n"
		for savedfont in ${savedFontsArray[@]}
		do
			if [ $pos1 -eq $pos2 ] && [ "$highlight" == "true" ];
			then
				echo -e ">>"$green $savedfont $defaultColor
			else
				echo -e ">>"$purple $savedfont $defaultColor
			fi
			let pos2=($pos2+1)
		done

		#ask the user if he wants to keep going or save/select the font
		read -p "wanna look at the next font? "$options": " option
		case "$option" in
			"n") 
				broke="true"
				break;;
			#copies the font name into an array
			"save") savedFontsArray+=($font);;
			#re-writes the config file using the new font
			"select")
				#first backo the new file as vconsole.conf.backup
				echo "Backing up config file..";
				cp $configFile $localCopy".backup"
				#set the new FONT= line
				newFontOpt=$newFontOpt$font
				#remove any past local copies of vconsole.conf
				rm $localCopy
				#do the rewrite, show the user the new file
				echo -e "Writing new config file...\n"
				while read line
				do
					if [ "$line" != "$fontOpt" ]
					then
						echo $line
						echo $line >> $localCopy
					else
						echo -e $red$newFontOpt$defaultColor
						echo $newFontOpt >> $localCopy
					fi
				done < $localCopy".backup"
				echo -en "\nCopying the new config file please supply the "
				sudo cp $localCopy $configFile
				exit
				;;
			*)
				#by default: keep going
				;;
		esac
		#clear the screen and repeat
		clear
		#if break signal was sent from case then break here too
		if [ "$broke" == "true" ]
		then
			break
		fi
	done
	#saved the selected font names in a file before exiting
	saveSelectedFonts savedFontsArray[@]
	#reset the font
	setfont
	for savedfont in ${savedFontsArray[@]}
	do
		echo -e ">>"$purple $savedfont $defaultColor
	done
	read -p "you wanna select a font from this list?: " answer
	if [ "$answer" == "yes" ] || [ "$answer" == "y" ];
	then
		viewSelectedFonts
	fi
}

#Writes an array of fonts names into a file the script will use later
saveSelectedFonts(){ #always should recieve an array as argument
	#make rom for a savedfonts file if it doesnt exist already
	touch $savedFonts
	#get the font names from the array that was passed
	local fontArray=("${!1}")
	#check that no font in the array is already on the file
	for font in ${fontArray[@]}
	do
		echo -n "saving "$font"in fonts file"
		sleep 0.05
		checkRepeat=$(cat $savedFonts|grep $font)
		#if the font is not on the file then copy it
		if [ "$checkRepeat" == "" ]
		then
			#let the user know it was copied
			echo -e "\t["$green"OK"$defaultColor"]"
			echo $font >> $savedFonts
		else
			#if it's not there then don't copy and let the user know
			echo -e "\t["$red"DUPPLICATED"$defaultColor"]"
		fi
	done
}

#as viewSystemFonts but takes the font names file with the fonts the user selected
viewSelectedFonts(){
    local selectedFontsArray=($(cat $savedFonts))
    clear
    showcast selectedFontsArray[@]
}

help(){
	echo "Usage: vconview [OPTION]"
	echo -ne "Tests every console font letting the user choose which ones "
	echo -ne "are best, and which one to use\n"
	echo "Options"
	echo -ne "-s, --select \t lets you look through a selected fonts list "
	echo -e "generated by this very script"
	echo -e "-h, --help \t shows this message"
}


########################THIS IS WHERE THE EXECUTION STARTS##########################

#it will execute depending on the given argument
#or lack of one
case "$1" in
	#Look through the previously selected fonts
	"-s" | "--select")
		clear
		viewSelectedFonts;;
	#Show help dialoge
	"-h" | "--help")
		help;;
	#By Default clear the screen and test every systemFont
	* )
		clear
		viewSystemFonts;;
esac

Last edited by Skoglar (2012-12-07 21:33:25)

Offline

#1999 2012-12-07 23:18:58

JayCeeEhm
Member
Registered: 2012-02-29
Posts: 7

Re: Post your handy self made command line utilities

Needed a way to sync my music files from one directory to another randomly. I mount my phone via sshfs. Couldn't find a music player that supports this so wrote this script

 
#!/bin/bash

#clear the console

	clear

#create file

	touch songlist

#set the variables

	proceed=0
	dir=0

#create functions

	findfiles()
		{
			#create variables/files that need to be reset with each run of function

			filecount=0
			dirsize=0

			#find files in given directory and pipe the size and full path to nl to add a line number to each entry and create file test 

			find $dir -type f -printf "\\t%-16s%p\\n" | nl -nln > test;

			#cut the line number of the last line of file test and set it to variable file count

			filecount=$(cut -f1 test | tail -n1);

			#get the size of all the files in a directory

			cat test | tr -s " " | cut -f3 | cut -f1 -d " " > test1;
			while read file;
				do dirsize=$(($file+$dirsize));
				done < test1;
			rm test1
		}

	sizes()
		{
			echo
			echo "Total number of files in $dir:      $filecount";
			echo "Total size of files in   $dir:      $dirsize bytes"; 
		}

	listcreate()
		{
			#create variables/files that need to be reset with each run of function

			touch songlist
			nomorefiles=0
			entry=0
			songsize=0
			totalsync=0
			syncsong=0

			#create a loop to add songs until nomorefiles=1

			echo
			while [ $nomorefiles != "1" ]
				do

				#create a list of files to be transfered

					#generate a random number between 1 and the file count

					entry=$[ ($RANDOM % $filecount ) +1 ]

					#use entry to get a song from test file and output only song with full directory note:
					#m1 keeps it from getting more than one result. Not perfect though.

					syncsong=$(grep -w -m1 $entry test | cut -f3 | cut -b17-)

					#use entry to get size of song to be added to folder

					songsize=$(grep -w -m1 $entry test | cut -f3 | cut -b1-16)

					#check to see if the total size of sync is less than syncsize. If it is then add song to file. If not start copy/rm operation

					if [ $totalsync -le $syncsize ]; then

						#check to see if file has already been added

						grep -x "$syncsong" songlist | grep -qv grep
						if [ $? = "1" ];then

							#add song 

							echo $syncsong >> songlist
							echo -n "."

							#add songsize to total for files add so far

							totalsync=$(($totalsync+$songsize))

							#if song not added check to see if maybe there are no more files available to be added

							elif [ $filecount = $(grep -c "" songlist) ]; then
								nomorefiles=1
								echo "No more files to add."

							else
								echo -n ","

						fi

						#if sync size has been reached set exit status
						else
							nomorefiles=1
							echo
							echo
							echo "All songs have been added to list."
							echo

					fi

				done
		}

#request size of sync set to default if no input
	
	echo -n "How many megs would you like to sync? (default is 4000M) : "
	read askline;

		if [ -z "${askline}" ];
			then 
				askline=4000
		fi
 
		syncsize=$(($askline*1000000))
		echo $(($syncsize/1000000))"M will be synced"

#request source directory

	srcdir=/home/$(whoami)/documents/Music/

	echo
	echo "The default source directory is $srcdir"
	echo -n "If you would like to change this please provide the source directory: "
	read askdir;

		if [ -z "${askdir}" ];
			then
				askdir=$srcdir
		fi

		srcdir=$askdir
		echo
		echo "The source directory is set to: $srcdir"

#request destination directory

	destdir=/home/$(whoami)/phone/storage/sdcard1/Music/

	echo
	echo "The default destination directory is $destdir"
	echo -n "If you would like to change this please provide the source directory: "
	read askdir;

		if [ -z "${askdir}" ];
			then
				askdir=$destdir
		fi

	destdir=$askdir
	echo
	echo "The source directory is set to: $destdir"

#check to see if there are files in destdir and delete all or some of them based on input

	dir=$destdir
	findfiles
	sizes	

	#create loop to perform action based on user input

	while [ $proceed != "1" ]
		do

			echo
			echo -n "Would you like to delete some or all of these files (some/all/none): "	
			read inputline;
			if  [ -z "${inputline}" ];
				then
				echo -n "Pls enter some/all/none:"
			
			elif [ $inputline = "some" ];
			then
			echo -n "How many megabytes of files would you like to delete? "
			read delmegs;
			echo
			echo -n $delmegs"M will be deleted. This amount will also be the amount added back into folder."
			echo
			syncsize=$((delmegs * 1000000))
			listcreate
			while read file;
				do
					rm "$file";
					echo -n "-"
				done < songlist
			echo	
			proceed=1

			elif [ $inputline = "all" ];
			then
			echo
			echo "All files in $destdir will be deleted"
			rm -r "$destdir"
			mkdir $destdir
			echo
			echo "All songs in $destdir have been deleted"
			proceed=1

			else [ $inputline = "none" ];
			echo
			echo "Files will be left in place"
			proceed=1
		fi

	done

#clean up and reset for next stage

	rm test
	rm songlist

#find songs in srcdir and create files and variable for loop

	dir=$srcdir
	findfiles
	sizes
	listcreate

#copy files to destination folder

	#test to make sure destination directory has enough free space. can't use this on sshfs
	#if [ $[(($syncsize / 1000) - $(df $destdir | grep /dev/ | tr -s " " | cut -d " " -f4))] -gt "1000" ]; then
	#	echo "there is enough free space"
	#	else
	#		echo "there is not enough free space"
	#fi
	
	echo "Total songs that will be added: "$(grep -c "" songlist)
	echo
	while read file;
		do
			cp "$file" $destdir;
			echo -n "+"
		done < songlist

#echo the variables to keep track of what is going on
echo
echo
echo "Source Directory:                 $srcdir"
echo "Destination Directory:            $destdir"
echo "Requested size of sync:           "$(($syncsize/1000000))"M"
echo "Actual size of sync:              "$(($totalsync/1000000))"M"
#echo "Total files available for sync:   $filecount"
#echo "Current line entry being added:   $entry"
#echo "Current size of song being added: $songsize"
#echo "Current song being added:         $syncsong"
#echo "No more file exit status:         $nomorefiles"
#echo "File List:"
#cat songlist
#clean up our temp files

	rm songlist
	rm test
	exit

Offline

#2000 2012-12-08 12:42:24

balinbob
Member
From: North Carolina
Registered: 2010-03-07
Posts: 10

Re: Post your handy self made command line utilities

jakobcreutzfeldt wrote:

Here's "some", which uses source-highlight to colorize text files according to their syntax and then pipes them through less. So, it's basically less with syntax highlighting.

Thank You, I've been hoping to run across something like this for a long time (lazy!). 

Bob

Offline

Board footer

Powered by FluxBB