You are not logged in.

#2326 2014-03-02 13:04:43

kokoko3k
Member
Registered: 2008-11-14
Posts: 2,420

Re: Post your handy self made command line utilities

My netbook (n280 asus eeepc 1005ha) is becoming old and too slow to browse the internet nowdays.
The following would try to preserve battery life and giving it more speed by modifying FSB frequency (super hybrid engine) depending on the total cpu load.
Unfortunately i was unable to find a way to "trigger" the change, so i ended up by polling the cpu load every 0.5 sec, which seems a good tradeoff, the following takes 0.3% cpu load, not bad.

# cat /usr/local/bin/eeeshed.sh 
#!/bin/bash
#switch between normal and powersave fsb mode depending on the total cpu load
#$T is the threshold:

T=20
state="normal"

while true; do
        read cpu a b c previdle rest < /proc/stat
        prevtotal=$((a+b+c+previdle))
        sleep 0.5
        read cpu a b c idle rest < /proc/stat
        total=$((a+b+c+idle))
        CPU=$((100*( (total-prevtotal) - (idle-previdle) ) / (total-prevtotal) ))
        if [ "$CPU" -gt "$T" ]; then
                if [ "$state" = "powersave" ]; then
                        echo 1 > /sys/devices/platform/eeepc/cpufv
                        state="normal"
                        sleep 2
                fi
        else
                if [ "$state" = "normal" ]; then
                        echo 2 > /sys/devices/platform/eeepc/cpufv
                        state="powersave"
                fi
        fi
done

A service file as well:

# cat /etc/systemd/system/eeeshed.service
[Unit]
Description=eee-she based on cpu load

[Service]
ExecStart=/usr/local/bin/eeeshed.sh

[Install]
WantedBy=multi-user.target

Credits for the cpu load calculation part goes to procyon smile

-edit
Any suggestion to slim down the script is welcome!

Last edited by kokoko3k (2014-03-02 14:33:30)


Help me to improve ssh-rdp !
Retroarch User? Try my koko-aio shader !

Offline

#2327 2014-03-02 19:10:28

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

Re: Post your handy self made command line utilities

You could simplify it a bit by just having one read per loop.

prevtotal=0
previdle=0
while true; do
        read cpu a b c idle rest < /proc/stat
        total=$((a+b+c+idle))
        CPU=$((100*( (total-prevtotal) - (idle-previdle) ) / (total-prevtotal) ))
        if [ "$CPU" -gt "$T" ]; then
                if [ "$state" = "powersave" ]; then
                        echo 1 > /sys/devices/platform/eeepc/cpufv
                        state="normal"
                        sleep 2
                fi
        else
                if [ "$state" = "normal" ]; then
                        echo 2 > /sys/devices/platform/eeepc/cpufv
                        state="powersave"
                fi
        fi
        prevtotal=total
        previdle=idle
        sleep 0.5
done

Last edited by moetunes (2014-03-02 19:11:20)


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

Offline

#2328 2014-03-04 14:37:53

teckk
Member
Registered: 2013-02-21
Posts: 524

Re: Post your handy self made command line utilities

If anyone can use this. I made two different versions of a
time calculator.
The first will output in format 1:46:23
The second will output in format 1h 46m 23s

time_calc1.sh

#! /usr/bin/env bash

# A calculator to compute the difference between two
# clock times. ((hh:mm:ss) - (hh:mm:ss) = (hh:mm:ss))
# For editing video's or finding the exact difference
# between two clock times.

get() {
      read -r h m s <<< $(echo $1 | tr ':' ' ' )
      echo $(((h*60*60)+(m*60)+s))
      }

clear
echo "$(tput bold)$(tput setaf 2)Enter Time with \
format hh:mm:ss ex. 1:52:12 | 0:52:12 | 0:2:12 | 0:0:12"

echo "$(tput setaf 4)Enter Start time:"
read start_time
echo "$(tput setaf 1)Enter Stop time:"
read stop_time

DIFF=($(get $stop_time)-$(get $start_time))
HOUR=$((DIFF / 3600 ))h
MIN=$(((DIFF % 3600) / 60))m
SEC=$((DIFF % 60))s

echo "$(tput setaf 3)Difference is:"
echo "$HOUR:$MIN:$SEC" | sed 's/[hms]//g'
echo "$(tput sgr0)"

time_calc2.sh

#! /usr/bin/env bash

# A calculator to compute the difference between two
# clock times. ((hh:mm:ss) - (hh:mm:ss) = ($h $m $s))
# For editing video's or finding the exact difference
# between two clock times.

get() {
      read -r h m s <<< $(echo $1 | tr ':' ' ' )
      echo $(((h*60*60)+(m*60)+s))
      }

clear
echo "$(tput bold)$(tput setaf 2)Enter Time with \
format hh:mm:ss ex. 1:52:12 | 0:52:12 | 0:2:12 | 0:0:12"

echo "$(tput setaf 4)Enter Start time:"
read start_time
echo "$(tput setaf 1)Enter Stop time:"
read stop_time

DIFF=($(get $stop_time)-$(get $start_time))

echo "$(tput setaf 3)Difference is:"
echo "$((DIFF / 3600 ))h $(((DIFF % 3600) / 60))m $((DIFF % 60))s""$(tput sgr0)"

Example output:
Enter Time with format hh:mm:ss ex. 1:52:12 | 0:52:12 | 0:2:12 | 0:0:12
Enter Start time:
0:3:47

Enter Stop time:
1:26:43

Difference is:
1:22:56

Offline

#2329 2014-03-16 12:53:55

2Karl
Member
From: Daventry, UK
Registered: 2012-03-26
Posts: 62
Website

Re: Post your handy self made command line utilities

I wrote this when I was teaching myself bash, and because I was frustrated that the fan speed adjustments in nvidia-settings never actually seened to do anything:

#!/bin/bash

#nvautoadjust 
#periodically checks Nvidia GPU temperature and adjusts fan appropriately

#recommended invokation: nvautoadjust &
#run at startup to continually monitor temperature and adjust fan speed.

#sets the refresh interval in seconds
interval=5
#sets the threshold temperatures and fan speeds for the three levels of cooling
#threshold is in degrees c, speed is in percentage of maximum. Set a number between
#35 and 99.
min_threshold=45
max_threshold=60
min_speed=35
mid_speed=60
max_speed=100


# continually loop
while [ "1" -eq "1" ]; do
	#get current temperature and fan speed
	current_temp=`nvidia-smi -q -d TEMPERATURE | grep Gpu | sed 's/.*\([0-9]\{2\}\).*/\1/'`
	current_speed=`nvidia-smi -q | grep Fan | sed 's/.* \(1\?[0-9]\{2\}\) .*/\1/'`
	
	#check current temperature and adjust fan speed
	#only set the speed if it actually needs changing, as nvidia-settings eats CPU cycles
	if [[ $current_temp > $min_threshold ]]; then
		if [[ $current_temp > $max_threshold ]]; then
			#if temp greater than 60, set fan speed to max
			if [[ $current_speed != $max_speed ]]; then
				nvidia-settings -a [gpu:0]/GPUFanControlState=1 -a [fan:0]/GPUCurrentFanSpeed="$max_speed" > /dev/null
			fi
		fi
		#if temp greater than 45, set fan speed to mid
		if [[ $current_speed != $mid_speed ]]; then
			nvidia-settings -a [gpu:0]/GPUFanControlState=1 -a [fan:0]/GPUCurrentFanSpeed="$mid_speed" > /dev/null
		fi
	else
		#if temp below 45, set fan speed to minimum
		if [[ $current_speed != $min_speed ]]; then
			echo set
			nvidia-settings -a [gpu:0]/GPUFanControlState=1 -a [fan:0]/GPUCurrentFanSpeed="$min_speed" > /dev/null
		fi
	fi

	#wait until interval expires before rechecking
	sleep "$interval"
done

It's affine day for a new sig:
13XQLTXH?R%20GLVHDVB!1046210467104640201045B104731046F02010458104731045902
010450104681045B1046910462104681046F02E0201045A104731045102010458104750201
04780201046F1046A104510201046902010461104671045B1047202010458104671045102E

Offline

#2330 2014-03-16 17:30:35

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

Re: Post your handy self made command line utilities

Fwiw, you can replace every "grep | sed" with just awk.

Offline

#2331 2014-03-16 18:09:11

2Karl
Member
From: Daventry, UK
Registered: 2012-03-26
Posts: 62
Website

Re: Post your handy self made command line utilities

Yeah I know that now - as I said it was a learning exercise smile


It's affine day for a new sig:
13XQLTXH?R%20GLVHDVB!1046210467104640201045B104731046F02010458104731045902
010450104681045B1046910462104681046F02E0201045A104731045102010458104750201
04780201046F1046A104510201046902010461104671045B1047202010458104671045102E

Offline

#2332 2014-03-18 13:06:33

teckk
Member
Registered: 2013-02-21
Posts: 524

Re: Post your handy self made command line utilities

2 simple bash scripts to record TV streams. The first is manual start-stop,
the second is a programmable DVR. These are for my U.S. ATSC over the air broadcast's,
but can be modified for DVB-T,S,C. The scripts pause with a signal strength display so
you can adjust your antenna position in case you are using a small portable antenna sitting
by your computer. You must have a working tv tuner on your machine or they won't
do anything. That means have the USB device plugged in with working firmware. They don't
require X, gtk, qt, ncurses, python, java,....just bash.

Modify for your channels and broadcast type.
To run the scripts, make them executable, launch them, follow the prompts.

tvr.sh

#! /usr/bin/env bash

# Bash script to record TV stream to tv.ts
# Requires linuxtv-dvb-apps http://www.linuxtv.org/wiki/index.php/LinuxTV_dvb-apps
# and a TV tuner device that works. Does not require X.

# $PATH for recording.
if [ ! -e $HOME/tel ]; then
	mkdir $HOME/tel
fi
cd $HOME/tel

# Number all existing tv*.ts files in directory sequentially
# so that we don't overwrite previous recordings.
num=0
for i in tv*.ts; do 
	num=$(( $num + 1 ))
	mv $i tv$num.ts &> /dev/null
done
clear

# Function to zap a channel out of channels.conf.
# Look at http://www.linuxtv.org/wiki/index.php/Zap
chan() {
	azap -r -c $HOME/.mplayer/channels.conf $opt > /dev/null
}

# Function to display the signal strength of channel.
adj() {
	femon -H | cut -d "|" -f2
}

# Function to write the selected channel to file.
rec() {
	cat /dev/dvb/adapter0/dvr0 > tv.ts
}

echo -e "\nFirst lets check the antenna position for signal strength.\n"
echo -e "Enter a channel from list, adjust the antenna for 75% or better signal quality."
echo -e "Press (enter) again to record that channel.\n"

# Path to your channels.conf
chans=$(cat $HOME/.mplayer/channels.conf | sed 's/:.*//g')
select opt in $chans; do
	chan & adj &
	# Stop
	read
	pkill femon; pkill azap; sleep 2; clear
	echo "Press enter to stop recording. File is (tv.ts)"

	# Start recording.
	chan & rec &
	# Stop recording.
	read
	pkill azap; pkill cat
	clear
done
exit

dvr.sh

#! /usr/bin/env bash

# Bash programable DVR script to record TV stream to dvr.ts
# Will wake machine at $hh:mm, record for $hh:mm, return to sleep.
# Requires linuxtv-dvb-apps, rtcwake, and a TV tuner device that works.
# Does not require X.

if [ ! -e $HOME/tel ]; then
	mkdir $HOME/tel
fi
cd $HOME/tel

num=0
for i in dvr*.ts; do 
	num=$(( $num + 1 ))
	mv $i dvr$num.ts &> /dev/null
done
clear

chan() {
	azap -r -c $HOME/.mplayer/channels.conf $opt > /dev/null
}

adj() {
	femon -H | cut -d "|" -f2
}

rec() {
	cat /dev/dvb/adapter0/dvr0 > dvr.ts
}

echo -e "\nEnter start time. With format: 0300 | 1230 | 1600 | 'tomorrow 0300'"
read st
echo -e "\nLength of recording? With format: 30s | 30m | 1.5h"
read dur
echo -e "\nEnter a channel from list, adjust the antenna for 75% or better signal quality."
echo -e "Then press (enter) again to set DVR.\n"

chans=$(cat $HOME/.mplayer/channels.conf | sed 's/:.*//g')
select opt in $chans; do
	chan & adj &
	read
	pkill femon; pkill azap

	# Sleep now, wake up at $st
	sudo rtcwake -m mem -t $(date +%s -d $st)
	# Start recording.
	chan & rec &
	# Length of recording $dur
	sleep $dur

	#Stop recording, sleep
	pkill azap; pkill cat
	sudo systemctl suspend
done

If you want just a signal meter.
scan.sh

#! /usr/bin/env bash

clear
chan() {
	azap -r -c $HOME/.mplayer/channels.conf $opt > /dev/null
}

adj() {
	femon -H | cut -d "|" -f2
}

echo -e "\nEnter a channel from list\n"
a=$(cat $HOME/.mplayer/channels.conf | sed 's/:.*//g')

select opt in $a; do
	chan & adj &
	echo "Press enter to stop"
	read
	pkill azap; pkill femon
	clear
done

Related links:

pacman -Si linuxtv-dvb-apps

http://www.linuxtv.org/wiki/index.php/LinuxTV_dvb-apps
http://www.linuxtv.org/wiki/index.php/Zap
http://www.linuxtv.org/wiki/index.php/Scan
http://www.linuxtv.org/wiki/index.php/Dvbscan
http://www.linuxtv.org/wiki/index.php/W_scan
http://linuxtv.org/wiki/index.php/Hardw … nformation
http://www.linuxtv.org/wiki/index.php/T … DVB_device
http://www.linuxtv.org/wiki/index.php/DVB-T_USB_Devices
http://www.linuxtv.org/wiki/index.php/ATSC_USB_Devices
http://en.wikipedia.org/wiki/Digital_te … television
http://linux.die.net/man/8/rtcwake

Offline

#2333 2014-03-23 21:58:03

Slithery
Administrator
From: Norfolk, UK
Registered: 2013-12-01
Posts: 5,776

Re: Post your handy self made command line utilities

I thought it was about time to teach myself some bash scripting so I'm going to be creating a lot of new scripts in the near future.

Because of this the first one I've written is a script that creates scripts, I've called it bash-template.

bash-template -h

bash-template
v0.1 by Slithery

A bash script to create new bash scripts.

  USAGE:  bash-template [OPTIONS] filename

  OPTIONS:  -a     Script author (defaults to full name of current user).
            -d     Script description.
            -h     Display this help.
            -v     Script version (defaults to 0.1).
            -V     Show version.

In action

$ bash-template -d "My new bash script." ~/bin/new-script
New script /home/rob/bin/new-script created.

$ new-script -h

new-script
v0.1 by Slithery

My new bash script.

  USAGE:  new-script [OPTIONS] VAR1

  OPTIONS:  -h     Display this help.
            -V     Show version.

Created script

#!/bin/bash

SCRIPT_NAME="new-script"
SCRIPT_DESCRIPTION="My new bash script."
SCRIPT_VERSION="0.1"
SCRIPT_AUTHOR="Slithery"

# Script usage
#

usage () { cat <<-USAGETXT

	$SCRIPT_NAME
	v$SCRIPT_VERSION by $SCRIPT_AUTHOR
	
	$SCRIPT_DESCRIPTION
	
	  USAGE:  $SCRIPT_NAME [OPTIONS] VAR1
	
	  OPTIONS:  -h     Display this help.
	            -V     Show version.

USAGETXT
}


# Options
#

while getopts :hV flag
	do
    case "$flag" in
    (h) usage; exit 0;;
    (V) echo "$SCRIPT_VERSION"; exit 0;;
#   (e) EXAMPLE_OPTION_SWITCH=1;;			# Add e to getopts string.
#   (f) EXAMPLE_OPTION_VARIABLE="$OPTARG";;		# Add f: to getopts string.
    (*) echo "Invalid option, use -h for help."; exit 1;;
    esac
	done

shift $(($OPTIND - 1))


# Check for argument
#

if [ -n "$1" ]
then
  VAR1=$1
else echo "VAR1 not present, use -h for help."; exit 1
fi


# Main script.
#

echo "Main script here"
echo VAR1="$VAR1"
exit 0

Actual bash-template script

#!/bin/bash

SCRIPT_NAME=bash-template
SCRIPT_DESCRIPTION="A bash script to create new bash scripts."
SCRIPT_VERSION=0.1
SCRIPT_AUTHOR=Slithery


# Script usage
#

usage () { cat <<-USAGETXT

	$SCRIPT_NAME
	v$SCRIPT_VERSION by $SCRIPT_AUTHOR
	
	$SCRIPT_DESCRIPTION
	
	  USAGE:  $SCRIPT_NAME [OPTIONS] filename
	
	  OPTIONS:  -a     Script author (defaults to full name of current user).
	            -d     Script description.
	            -h     Display this help.
	            -v     Script version (defaults to 0.1).
	            -V     Show version.

USAGETXT
}


# Options
#

while getopts :a:d:hv:V flag
	do
    case "$flag" in
    (a) OPTION_A="$OPTARG";;
    (d) OPTION_D="$OPTARG";;
    (h) usage; exit 0;;
    (v) OPTION_V="$OPTARG";;
    (V) echo "$SCRIPT_VERSION"; exit 0;;
    (*) echo "Invalid option, use -h for help."; exit 1;;
    esac
	done

shift $(($OPTIND - 1))


# Check for filename argument.
#

if [ -n "$1" ]
then
  NEW_SCRIPT_FILENAME=$1
  NEW_SCRIPT_NAME=$(basename "$1")
  NEW_SCRIPT_DIR=$(dirname "$1")
else
  echo "Filename not specified, use -h for help."; exit 1
fi


# Set variables.
#

if [ -n "$OPTION_A" ]
then
  NEW_SCRIPT_AUTHOR=$OPTION_A
else
  NEW_SCRIPT_AUTHOR=$(getent passwd "$USER" | cut -d ':' -f 5 | cut -d ',' -f 1)
fi


if [ -n "$OPTION_D" ]
then
  NEW_SCRIPT_DESCRIPTION=$OPTION_D
else
  NEW_SCRIPT_DESCRIPTION=""
fi


if [ -n "$OPTION_V" ]
then
  NEW_SCRIPT_VERSION=$OPTION_V
else
  NEW_SCRIPT_VERSION="0.1"
fi


# Check target..
#

if [ ! -d $NEW_SCRIPT_DIR ]
then
  echo "Target directory doesn't exist."; exit 1
fi

if [ ! -w $NEW_SCRIPT_DIR ]
then
  echo "Target directory isn't writeable."; exit 1
fi

if [ -e $NEW_SCRIPT_FILENAME ]
then
  echo "Target already exists."; exit 1
fi


# Generate script
#

(
cat <<DEBUG_OUTPUT
#!/bin/bash

SCRIPT_NAME="$NEW_SCRIPT_NAME"
SCRIPT_DESCRIPTION="$NEW_SCRIPT_DESCRIPTION"
SCRIPT_VERSION="$NEW_SCRIPT_VERSION"
SCRIPT_AUTHOR="$NEW_SCRIPT_AUTHOR"

DEBUG_OUTPUT

cat <<'DEBUG_OUTPUT'
# Script usage
#

usage () { cat <<-USAGETXT

	$SCRIPT_NAME
	v$SCRIPT_VERSION by $SCRIPT_AUTHOR
	
	$SCRIPT_DESCRIPTION
	
	  USAGE:  $SCRIPT_NAME [OPTIONS] VAR1
	
	  OPTIONS:  -h     Display this help.
	            -V     Show version.

USAGETXT
}


# Options
#

while getopts :hV flag
	do
    case "$flag" in
    (h) usage; exit 0;;
    (V) echo "$SCRIPT_VERSION"; exit 0;;
#   (e) EXAMPLE_OPTION_SWITCH=1;;			# Add e to getopts string.
#   (f) EXAMPLE_OPTION_VARIABLE="$OPTARG";;		# Add f: to getopts string.
    (*) echo "Invalid option, use -h for help."; exit 1;;
    esac
	done

shift $(($OPTIND - 1))


# Check for argument
#

if [ -n "$1" ]
then
  VAR1=$1
else echo "VAR1 not present, use -h for help."; exit 1
fi


# Main script.
#

echo "Main script here"
echo VAR1="$VAR1"
exit 0

DEBUG_OUTPUT
) > $NEW_SCRIPT_FILENAME

chmod +x $NEW_SCRIPT_FILENAME
echo "New script $NEW_SCRIPT_FILENAME created."
exit 0

Any input would be gratefully received, either on the script itself or the template script it outputs.
Purely as a learning exercise I've also put the code up on github [1].

[1] https://github.com/slithery/bash-template

Last edited by Slithery (2014-03-23 22:00:29)


No, it didn't "fix" anything. It just shifted the brokeness one space to the right. - jasonwryan
Closing -- for deletion; Banning -- for muppetry. - jasonwryan

aur - dotfiles

Offline

#2334 2014-03-25 14:59:08

sekret
Member
Registered: 2013-07-22
Posts: 289

Re: Post your handy self made command line utilities

Easy encrypted chat with openssl and netcat

Server

#!/bin/bash
clear
echo -n "password > "
read passwd
echo -n "port > "
read port
while IFS= read -r userinput; do echo "$userinput" | openssl enc -aes-256-cbc -a -A -k "$passwd";echo;done | nc -l -p "$port" | while IFS= read -r serveroutput;do echo "Incoming: $(echo "$serveroutput" | openssl enc -d -a -A -aes-256-cbc -k "$passwd")";done

Client

#!/bin/bash
clear
echo -n "password > "
read passwd
echo -n "url/ip > "
read url
echo -n "port > "
read port
while IFS= read -r userinput;do echo "$userinput" | openssl enc -aes-256-cbc -a -A -k "$passwd";echo;done | nc "$url" "$port" | while IFS= read -r serveroutput;do echo "Incoming: $(echo "$serveroutput" | openssl enc -d -a -A -aes-256-cbc -k "$passwd")";done

(based on http://www.nixaid.com/encrypted-chat-with-netcat )

Offline

#2335 2014-03-25 22:53:17

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

Re: Post your handy self made command line utilities

#!/bin/sh
# Recursively find FLAC files starting in given directory 
# and convert them to ogg vorbis files
appname=${0##*/}
MAX_ARGS=2
# remove umlauts for FAT file systems
umlaut_cleaner() {
    echo "$1" | sed -e 's|ö|o|g' -e 's|ü|u|g' -e 's|ä|a|g'
}

fatfix() {
    umlaut_cleaner "$1" | sed -e 's|:||g' 
}
main() {
  find "$TARGET_DIR" -name \*.flac  | while read FLACFILE
    do
      # Grab the id3 tags from the FLAC file
      ARTIST=$(metaflac "$FLACFILE" --show-tag=ARTIST | sed s/.*=//g)
      TITLE=$(metaflac "$FLACFILE" --show-tag=TITLE | sed s/.*=//g)
      ALBUM=$(metaflac "$FLACFILE" --show-tag=ALBUM | sed s/.*=//g)
      GENRE=$(metaflac "$FLACFILE" --show-tag=GENRE | sed s/.*=//g)
      TRACKNUMBER=$(metaflac "$FLACFILE" --show-tag=TRACKNUMBER | sed s/.*=//g)
      DATE=$(metaflac "$FLACFILE" --show-tag=DATE | sed s/.*=//g)
      COVERART=$(metaflac --export-picture-to=- "$FLACFILE" | base64 --wrap=0 -)
      # A little shell globbing to get the filename
      # (everything after the rightmost "/")
      FILENAME=${FLACFILE##*/}
      # Build the output path and rename the file
      OGGFILE=$(echo "$DESTINATION_DIR/$ARTIST/$ALBUM/$FILENAME" | sed s/\.flac$/.ogg/g)
      if [ $fatsave ] ; then
	 OGGFILE=$(fatfix "$OGGFILE")
      fi
      # Convert to OGG at 320kbps (use -q6 for 192kbps)
      oggenc -q9 --discard-comments -a "$ARTIST" -t "$TITLE" -l "$ALBUM" -G "$GENRE" -N "$TRACKNUMBER" -d "$DATE" -o "$OGGFILE" "$FLACFILE"
      if [ $deprecovertag ] ; then
	  vorbiscomment -a -c "COVERTAG=$COVERTAG" "$OGGFILE"
      else
	  vorbiscomment -a  -t "METADATA_BLOCK_PICTURE=$COVERART" "$OGGFILE"
      fi
  done 
  
  if [ $coverd ] ; then
      printf "%s" "$COVERART" > "${OGGFILE##*/}"/cover.jpg
  fi
}

print_help() {
cat <<_HELP_MSG
  $appname - usage:
      $appname [options] <target_dir> <destination_dir>
options
  --fatfix           use fat save filenames
  --coverd           save cover.jpg file in album dir
  --depre-covertag   use depreacted COVERTAG comment in ogg file
_HELP_MSG
}
OPTS=h
LONG_OPTS=coverd,depre-covertag,fat-save,help
P_OPTS=$(getopt -o $OPTS -l $LONG_OPTS -n $appname -- $@ )
eval set -- $P_OPTS
while [ ! $# = 0 ] ; do
    case "$1" in
	--stub) echo stub ; shift ;;
	--fat-save) fatsave=True; shift ;;
	--coverd) coverd=True ; shift ;;
	--depre-covertag) deprecovertag=True; shift ;;
	-h|--help) print_help; exit ;;
	--) shift ; break ;;	
    esac
done
if [ $# -ge $MAX_ARGS ] ; then     
    TARGET_DIR=$1
    DESTINATION_DIR=$2
    shift 2
    main
else
    echo "no or to less arguments given" >&2
fi

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

Offline

#2336 2014-03-26 02:49:59

s0l1dsnak3123
Member
From: Scotland
Registered: 2008-06-26
Posts: 70
Website

Re: Post your handy self made command line utilities

I've written a quick-n-dirty ruby script for converting xdefaults colour schemes to termite colour configs: https://github.com/johnhamelink/xdefaults_to_termite

Offline

#2337 2014-03-26 11:16:56

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Because I was not happy with the new “arch-wiki-docs” structure,  created a way to get back the old situation, with 'index.html. I like the one file situation.

Since I run these on my own server(home), I decided to clean up anything I can't read.
So I created this tool. The only thing you really need to change is 'path1', the rest should happen on it's own.
The last 10 items in 'find' are not languages, but subjects like printer linguistics, etc. , since I can't read them, they're removed.

#!/bin/bash

# Offline-wiki 'cleaner', simple script to clean up the arch-wiki-docs and create 'index.html' placed in /srv/http/arch-wiki/html (change to your needs)

## If you want to clean the '/usr/share/doc/arch-wiki/html', remove comment 'path1'  (!!TESTED!!)
#path1='/usr/share/doc/arch-wiki/html'
path1='/srv/http/arch-wiki/html'
title='directory index'

# No real need to change anything below this line.
#------------------------------------------------#
langua=$(langua 2>/dev/null) || langua=/tmp/langua
trap 'rm -f /tmp/langua' 0 1 2 3 15

index="$(index 2>/dev/null)" || index=/tmp/index
trap 'rm -f "$index"' 0 1 2 3 15

DIALOG=${DIALOG=dialog}

$DIALOG --backtitle "Delete languages you don't need and keep your own && English." \
        --title "Language cleaner" --clear \
        --radiolist     "Check your language:" 36 34 30 \
        "العربية"  "" off \
        "Български" "" off \
        "Català" "" off \
        "简体中文" "" off \
        "正體中文" "" off \
        "Hrvatski" "" off \
        "Česky" "" off \
        "Dansk" "" off \
        "Nederlands" "" off \
        "Esperanto" "" off \
        "Suomi" "" off \
        "Ελληνικά" "" off \
        "עברית"  "" off \
        "Magyar" "" off \
        "Indonesia" "" off \
        "Italiano" "" off \
        "日本語" "" off \
        "한국어" "" off \
        "Lietuviškai" "" off \
        "Norsk_Bokmål" "" off \
        "Polski" "" off \
        "Português" "" off \
        "Portuguese" "" off \
        "Русский" "" off \
        "Српски" "" off \
        "Slovenský" "" off \
        "Español" "" off \
        "ไทย" "" off \
        "Українська" "" off \
        "none" "" on 2>/tmp/langua;

retval=$?

# Remove other languages.
#-----------------------#
case $retval in
  0)

  touch "$path1"/index.html
  LINGUI=$(cat "$langua")

    for lingui in $LINGUI; do
        if [ "$lingui" = "$(cat "$langua")" ]; then

        # Remove all other languages(files). info:https://wiki.archlinux.org/index.php/help:i18n
        find "$path1" -mindepth 1  \( -name "*العربية*"\
         -o -name "*Български*"\
         -o -name "*Català*"\
         -o -name "*简体中文*"\
         -o -name "*正體中文*"\
         -o -name "*Hrvatski*"\
         -o -name "*Česky*"\
         -o -name "*Dansk*"\
         -o -name "*Nederlands*"\
         -o -name "*Esperanto*"\
         -o -name "*Suomi*"\
         -o -name "*Ελληνικά*"\
         -o -name "*עברית*"\
         -o -name "*Magyar*"\
         -o -name "*Indonesia*"\
         -o -name "*Italiano*"\
         -o -name "*日本語*"\
         -o -name "*한국어*"\
         -o -name "*Lietuviškai*"\
         -o -name "*Norsk_Bokmål*"\
         -o -name "*Polski*"\
         -o -name "*Português*"\
         -o -name "*Portuguese*"\
         -o -name "*Русский*"\
         -o -name "*Српски*"\
         -o -name "*Slovenský*"\
         -o -name "*Español*"\
         -o -name "*ไทย*"\
         -o -name "*Українська*"\
         -o -name "*เครื่องพิมพ์*"\
         -o -name "*Відновлення_системи*"\
         -o -name "*Водичи_(српски)*"\
         -o -name "*Керування*"\
         -o -name "*Настройка_системи*"\
         -o -name "*Ήχος*"\
         -o -name "*Προγραμματισμός*"\
         -o -name "*Набавка_и_инсталација*"\
         -o -name "*Допомога_по*"\
         -o -name "*เครื่องพิมพ์*"\) ! -name "*$LINGUI*"  -exec rm -r {} \;

        fi
    done
    ;;
  1)
    echo 'Canceled.'
    ;;
  255)
    echo 'Escaped.'
    ;;
esac

# Index arch-wiki-docs, create a index.html.
#------------------------------------------#
cd "$path1"
touch "$path1"/index.html

# Create a HTML link for every file found.
find .|sort |sed 's/^.*/<P><A HREF="&">&<\/A>/' > "$index"

# Make the file we just created into a real HTML file.
sed -i '1i\<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\
<HTML>\
       <HEAD>' "$index"
sed -i "4i\               <TITLE>'$title'</TITLE>" "$index"
sed -i '5i\               <META http-equiv="content-type" content="text/html; charset=utf-8"/>\
       </HEAD>\
<BODY>' "$index"
# Content wil be between these two HTML tags.
sed -i '$ a\</BODY>\
</HTML>' "$index"

# Get and place file into the 'root' of the arch-wiki-docs directory.
cat "$index" > "$path1"/index.html


# Clean up and exit.
#------------------#
trap 'rm -f "$langua" "$index"' 0 1 2 3 15

exit 0

Last edited by qinohe (2014-04-14 09:23:47)

Offline

#2338 2014-04-03 15:16:09

mzneverdies
Member
Registered: 2012-02-04
Posts: 147

Re: Post your handy self made command line utilities

Installing community/subdl and adding the following script, allows you to auto search-and-download subtitles for current folder. I find this extremly useful, maybe someone likes it too

community/subdl 1.0.3-2
    A command-line tool for downloading subtitles from opensubtitles.org
#!/bin/bash
subdls() {
subdl --lang=eng "$@"
}
for file in "`pwd`/"*; do
 if [ -f "$file" ] ; then
  subdls "$file"
 fi;
done

Of course the script can be improved, but it meets my needs, so I never dug any further smile

Offline

#2339 2014-04-03 17:17:27

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

Re: Post your handy self made command line utilities

You should use $() instead of `backticks` and, if you are using bash, use [[ instead of [...


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#2340 2014-04-08 19:43:33

pierregermain
Member
From: Mty - Par - Mad - Fra
Registered: 2013-11-28
Posts: 10
Website

Re: Post your handy self made command line utilities

I made this mini-script to change the genre of the song that is playing on Quod Libet. If somebody can need this perfect. I did not find a single page using these kind of scripts.

#bin/bash
echo "dirname"
dirname=`quodlibet --print-playing "<~dirname>"`
cd "$dirname"
pwd
filename=`quodlibet --print-playing "<~filename>"`
echo "$fileName:"
operon list "$filename"
read -p "set genre: " genre
echo "$genre"
operon set genre "$genre" "$filename"
operon list "$filename"

Offline

#2341 2014-04-14 09:28:03

qinohe
Member
From: Netherlands
Registered: 2012-06-20
Posts: 1,494

Re: Post your handy self made command line utilities

Hi all, I have completely rewritten the  tool in post #2337 it now uses dialog so you can hold back your own language.

The last 10 items in the first 'find' are not languages, they are subjects, but since I can't read it, I remove it.

I would gladly accept rants, thoughts, kind words would make me happy.
The reason I place it here, is to get some feedback, thanks.

Offline

#2342 2014-04-24 19:01:48

BradPJ
Member
Registered: 2013-06-05
Posts: 25

Re: Post your handy self made command line utilities

So following on from my last post I have massively updated my script.  I followed the advice of Awebb to define variables in my script.

A lot has also changed since then. I now use an encrypted external hard drive which utilise BTRFS subvolumes. I also have a lot of script output going to my log. This is so I can discover which stage of the script it fails, if it does. It is also helpful to me when I add to or change the script. Some silly scripting errors which were hard to find, but were very easy to pin point after checking my log.

########################################
# RSync Backup
########################################

#!/bin/bash

########################################
# Configuration
########################################

output_log="/path/to/output/file" 
UUID="UUID OF DRIVE"
key_file="/path/to/keyfile
mapper="MAPPER NAME"
decrypt_path="/dev/mapper/$mapper"
root_part="ROOT PARTITION" # If one partition then $decrypt_path
root_options="ROOT MOUNT OPTIONS"
root_path="ROOT PARTITION MOUNT PATH"
home_part="HOME PARTITION" #If one partition then $decrypt_path
home_options="HOME MOUNT OPTIONSl" 
home_path="HOME PARTITION MOUNT PATH" 

########################################
# Functions 
########################################

start_log () {
	echo " " >> $output_log
	echo "Backup Started on $(date)" >> $output_log
}

########################################

hardrive_check () {
	if [ ! -e /dev/disk/by-uuid/$UUID ] ;
		then echo "Hardrive not connected on $(date)" >> $output_log ;
		exit ;
		else echo "Hardrive Connected" >> $output_log ; 
		fi 
}

########################################

decrypt_drive () {
	cryptsetup --key-file $key_file luksOpen /dev/disk/by-uuid/$UUID $mapper &&  
	echo "Drive decrypted" >> $output_log
}

########################################

mount_root () {
	mount -o $root_options $root_part $root_path
	if mountpoint $root_path ; 
		then echo "Root successfully mounted" >> $output_log ; 
		else echo "Root failed to mount on $(date)" >> $output_log ;
		exit ; 
		fi 
}

########################################

backup_root () {
	rsync -aAXv --delete  /* $root_path --exclude={/dev/*,/home/*,/proc/*,/sys/*,/tmp/*,/run/*,/mnt/*,/media/*,/lost+found}
	echo "Root backup complete" >> $output_log
}

########################################

umount_root () {
	umount $root_path
	if mountpoint $root_path ;
		then echo "Root unsuccessfully mounted on $(date)" >> $output_log ;
		exit ;
		else echo "Root successfully unmounted" >> $output_log ;
		fi 
}

########################################

mount_home () {
	mount -o $home_options $home_part $home_path
	if mountpoint $home_path ;
		then echo "Home successfully mounted" >> $output_log ;
		else echo "Home unsuccessfully mounted on $(date)" >> $output_log ;
		exit ; 
		fi 
}

########################################

backup_home () {
	rsync -aAXv --delete /home/* $home_path
	echo "Home backup complete" >> $output_log
}

########################################

umount_home () {
	umount $home_path
	if mountpoint $home_path ; 
		then echo "Home unsuccessfully unmounted on $(date)" >> $output_log ; 
		exit ; 
		else echo "Home successfully unmounted" >> $output_log ; 
		fi 
}

########################################

encrypt_drive () {
	cryptsetup luksClose $mapper &&
	echo "Encrypted drive closed" >> $output_log
}
########################################


finish_log () {
	echo "Backup complete on $(date)" >> $output_log
} 

########################################
# Script Run
########################################

start_log &&
hardrive_check &&
decrypt_drive &&
mount_root && 
backup_root && 
umount_root && 
mount_home && 
backup_home && 
umount_home &&
encrypt_drive && 
finish_log || echo "Script failed to complete on $(date)" >> $output_log
exit

Here is my configuration part, incase anybody wants to use this script and got a bit confused, I know I haven't named the variables the best. I named them what makes most sense to me.

output_log="/home/brad/Scripts/Output/Log.txt" 
UUID="UUID Here"
key_file="/path/to/keyfile"
mapper="backup"
decrypt_path="/dev/mapper/$mapper"
root_part="$decrypt_path"
root_options="compress=lzo,subvol=rootvol"
root_path="/mnt/root"
home_part="$decrypt_path"
home_options="compress=lzo,subvol=homevol" 
home_path="/mnt/home/" 

I know that I probably shouldn't of used so many '#' lines but I wanted to clearly seperate each function. I started getting too confused when I didn't include them and as I'm still trying to learn I wanted to keep it simple to read. I'm happy with the result and have tested the back-up many times. Especially when I was setting up encryption on my main laptop drive for the first time.

The $root_part and $home_part variable is left over from when I used seperate partitions and again from when I used an encrypted LVM. I could of just used $decrypt_path now that I'm using one partition and just BTRFS subvolumes but it seemed best to keep them in. I believe this script could be quite flexible, considering the amount of options and then parts are easily commented out to be disabled (e.g. Decryption can easily be turned off), although of course I have only tested my use case. I'm posting this because I'm actually proud of where this has come from and what I have learned. Hopefully I can do some more interesting scripts next.

Offline

#2343 2014-04-24 19:05:40

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

Re: Post your handy self made command line utilities

The shebang should be on the first line of your script...


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#2344 2014-04-24 19:12:25

BradPJ
Member
Registered: 2013-06-05
Posts: 25

Re: Post your handy self made command line utilities

jasonwryan wrote:

The shebang should be on the first line of your script...

I figured that since the rest was all '#' it wouldn't have any effect. Just read up on how a shebang works now, didn't know what it was called previously. I honestly just saw that other people included it when I had the previous version so included it myself and since my script always just worked I have never looked any further into it like I have with variables and functions since then. Feel quite silly now. Oh well, live and learn. Thanks a lot!

Last edited by BradPJ (2014-04-24 19:43:06)

Offline

#2345 2014-04-25 22:21:14

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

Re: Post your handy self made command line utilities

BradPJ wrote:

I figured that since the rest was all '#' it wouldn't have any effect.

See: binfmt_script.c:25

Last edited by Earnestly (2014-04-25 22:22:01)

Offline

#2346 2014-04-26 16:27:33

Saint0fCloud
Member
Registered: 2009-03-31
Posts: 137

Re: Post your handy self made command line utilities

Don't know if someone's already written this, but I got tired of having to reload my terminal settings just to check out other people's terminal colors so I wrote an (ugly) bash script to preview color schemes without having to edit ~/.Xresources. It automatically restores your previous colors and works with both xdefaults and termite color formats.

https://gist.github.com/jsks/11323851

Offline

#2347 2014-04-27 16:05:30

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

Re: Post your handy self made command line utilities

Not my own concept but found this while browsing. http://plankenau.com/blog/post-10/gaussianlock
All credits to original post.

I am using below with alock.

#!/usr/bin/bash
#
# v-k 2014
#
###
# set -x

FILE="/tmp/sshot.png"

scrot $FILE
convert $FILE -blur 2x9 $FILE
alock -bg image:file=$FILE:scale -auth pam

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

Offline

#2348 2014-04-27 18:56:27

drcouzelis
Member
From: Connecticut, USA
Registered: 2009-11-09
Posts: 4,092
Website

Re: Post your handy self made command line utilities

vik_k wrote:

Not my own concept but found this while browsing. http://plankenau.com/blog/post-10/gaussianlock

That's a neat idea and a neat effect. smile

It takes about 3 - 5 seconds to create that blurred image on my computer. Does it take that long to lock your screen?

Offline

#2349 2014-04-27 19:10:51

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

Re: Post your handy self made command line utilities

Not exactly, it takes usually a second (I have a decent laptop). It actually also depends on the blur radius and bias. I have found 0x2 quite okay and fast. smile


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

Offline

#2350 2014-04-27 20:59:16

drcouzelis
Member
From: Connecticut, USA
Registered: 2009-11-09
Posts: 4,092
Website

Re: Post your handy self made command line utilities

vik_k wrote:

Not exactly, it takes usually a second (I have a decent laptop). It actually also depends on the blur radius and bias. I have found 0x2 quite okay and fast. smile

*sigh* That means my computer is really starting to show its age. sad ...or that I have an amazingly HUGE screen resolution! smile

Offline

Board footer

Powered by FluxBB