The usefulness of bash scripting.

##  One of the software engineers in our company 
##  spent the better part of a day writing a C++ program
##  that would look through the directories of all the users 
##  and add up the space they were using and make a listing of the results. 
##  Three lines of code in bash do the same\!

^ I don’t know where I read this once upon a time and in all likelihood I’ve already mentioned or written about this script before …!?

Anyway! :lol:

Here’s the script:

#!/bin/bash
# Modified: Today by E.L.F.
#
## Licensed as:
## http://www.opensource.org/licenses/mit-license.php
#
## Script-name - space.report.sh
#
##  One of the software engineers in our company 
##  spent the better part of a day writing a C++ program
##  that would look through the directories of all the users 
##  and add up the space they were using and make a listing of the results. 
##  Three lines of code in bash do the same\!
#
##  Root check / Sanity check.  You decide.  >-)
##  Just in case someone calls this script with sudo -s,
##  or has cd'ed into his/her path.
#
set -e
echo
if [ "$USER" = root ];then echo -e "\tError: \""$USER"\" isn't allowed to use this script!";exit 0
else echo -e "\t${USER} may proceed.\n\tMay peace be with you.\n";fi
## ^ Comment the above 2 lines out, if root is required!
if [ -n "$Color_Test" ];then echo -e ${Magenta}"\tOk, colors are defined."${Nc}
else
Black="\033[0;30m"
Red="\033[0;31m"
Green="\033[0;32m"
Yellow="\033[1;33m"
Blue="\033[1;34m"
Magenta="\033[1;35m"
Cyan="\033[1;36m"
White="\033[1;37m"
Nc="\033[0m" # No Color
echo -e ${White}"\tIf they weren't, then now they are."${Nc}
fi
clear
Date=$(date +"%F") # Renders for me as yyyy-mm-dd\!
SR=space.report_"$Date".txt
du -sh * | sort -nr > "$SR"
echo "" >> "$SR"
du -sh ./.* | sort -nr >> "$SR"
echo "" >> "$SR"
df -h >> "$SR"
echo "" >> "$SR"
echo "This space report was made on: "$Date"" >> "$SR"
exit 0

Now for the astute among you, who saw all these ${color} codes in the script.

And here’s today’s result, it took about 5 seconds to complete! :lol:

962M	Pictures
435M	Pictures - GT-N7000
173M	Documents
159M	Downloads
129G	Videos
110M	Ubuntu One
64K	bookmarks.html
20G	Music
8.0K	Desktop
5.4M	Public
4.0K	Templates
0	*.tor-relay.thruhere.net
0	space.report_2012-12-18.txt
0	PDF
0	learned_words.txt
0	ignored_words.txt

748M	./.cache
712K	./.gstreamer-0.10
616K	./.dvdcss
596K	./.compiz
536K	./.recently-used.xbel
324K	./.xsession-errors
317M	./.thumbnails
260K	./.icedteaplugin
247M	./.electricsheep
223M	./.kde
209M	./.mozilla
207M	./.local
195M	./.usr
192M	./.config
168K	./.pulse
159G	./..
159G	./.
152K	./.omegat
152K	./.macromedia
148K	./.dvdrip
120K	./.athena.face
112K	./.config-2.6.32-25-generic
96K	./.icedtea
92K	./.cddb
88K	./.face.png
68K	./.xine
68K	./.audacity-data
60K	./.avidemux
56K	./.ICEauthority
52K	./.pki
52K	./.k3d
48K	./.subversion
40K	./.filezilla
36K	./.sudoku
36K	./.qmmp
32K	./.openshot
32K	./.FBReader
32K	./.evolution
32K	./.dvdriprc
28K	./.winff
24K	./.ssh
24K	./.Molon.Labe
21M	./.themes
21M	./.openoffice.org
20K	./.adobe
16K	./.gegl-0.0
16K	./.gconfd
16K	./.dbus
16K	./.bash_functions
12K	./.torrc
12K	./.qt
12K	./.netx
12K	./.mission-control
12K	./.bash_aliases
8.0K	./.update-notifier
8.0K	./.synaptic
8.0K	./.putty
8.0K	./.mplayer
8.0K	./.lyrics
8.0K	./.hplip
8.0K	./.DontDoWindows.png
8.0K	./.bashrc.jic
8.0K	./.bashrc
7.3M	./.icons
5.1G	./.bitcoin
4.2M	./.Skype
4.0K	./.xscreensaver-getimage.cache
4.0K	./.xinput.d
4.0K	./.Xauthority
4.0K	./.windows-serial
4.0K	./.wifi.txt
4.0K	./.thunderbird
4.0K	./.TarBalls
4.0K	./.selected_editor
4.0K	./.rnd
4.0K	./.recently-used
4.0K	./.pulse-cookie
4.0K	./.profile
4.0K	./.printer-groups.xml
4.0K	./.nautilus
4.0K	./.nano_history
4.0K	./.mkvmergeGUI
4.0K	./.kderc
4.0K	./.htoprc
4.0K	./.gtk-recordmydesktop
4.0K	./.gtkrc-2.0-kde4
4.0K	./.gtk-bookmarks.R3Q1CW
4.0K	./.gtk-bookmarks
4.0K	./.gnome2_private
4.0K	./.fonts.conf
4.0K	./.exclude.txt
4.0K	./.examples.desktop
4.0K	./.esd_auth
4.0K	./.dmrc
4.0K	./.directory
4.0K	./.btrfs
4.0K	./.BOINC Manager
4.0K	./.bash_logout
4.0K	./.bash_history
3.2M	./.gnupg
2.4M	./.fonts
2.0M	./.gconf
2.0M	./.fontconfig
1.5M	./.gimp-2.6
1.4M	./.xsession-errors.old
1.4M	./.recently-used.xbel.RYNEBW
1.1M	./.gnome2
0	./.www.kiwix.org
0	./.sudo_as_admin_successful
0	./.mozilla-thunderbird
0	./.gvfs
0	./.gksu.lock

Filesystem            Size  Used Avail Use% Mounted on
/dev/sdb3              16G  8.5G  7.2G  55% /
none                  2.0G  380K  2.0G   1% /dev
tmpfs                 2.0G  7.0M  2.0G   1% /dev/shm
none                  2.0G  212K  2.0G   1% /var/run
none                  2.0G     0  2.0G   0% /var/lock
none                  2.0G     0  2.0G   0% /lib/init/rw
/dev/mapper/vg-home   9.2G  4.4G  4.8G  48% /home
/dev/mapper/vg-var    3.8G  1.5G  2.3G  41% /var
/dev/mapper/vg-linkedin
                      263G  205G   56G  79% /vault
/dev/mapper/cryptotmp
                     1012M  7.5M  953M   1% /tmp

This space report was made on: 2012-12-18

SoftwareZ used (If applicable, then this is in regards to “ remixed ” images. :lol: ):

That’s all folks!

Kindest regards,

Alex

♫ d(。◕‿◕。)b ♪♪

PS: My words are my own, my actions are my own. Everything I wrote and did in this post are my own responsibility.

All I’m offering is: YAP! ;-)

« Everything we do (in life) is meaningless, without the appropriate conviction. »

Before you comment!?

Back to top.

I think we all agree…


UPDATED! (04082012)
(The main reason: I provided some extra comments in the source.)

That Facebook is a pretty cool social media site..

But there are a few things I don’t like. For one: the way Facebook handles its outbound links. I.e. I’m used to see the link displayed (on hover) in clear text. But when I choose to copy the link address instead, a feat I often use, I get this junk:

http://www.facebook.com/l.php?u="The urlencoded link"&h=Random-gibberish-etc._et/al

Well I sought to end this madness by writing a little script which removes all the unnecessary junk and gives me back my transparent Internet, the way I like it. So while I can understand why Facebook uses this strategy, for one it’s a nice way to keep track of its users. I feel it interferes too much with the way how I use Facebook.

So here is the script:

strip()
{
## We might not want to run this as root!?
if [ $USER = root ]; then
echo -e ${Red}"\tAre you Insane!\n${Cyan}\tError: In order to use this script, one must NOT be $USER.\n${Yellow}\tExiting..."${Nc}
## The following will kick you out from a 'root-session', i.e. you used 'sudo -s' to become root.
## The '-s' flag implies that you can use (ifdef) your aliases and functions in the new env.
exit 0
else
echo -e ${Blue}"\t${USER} may proceed.\n${Cyan}\tMay peace be with you."${Nc}
fi
clear
## I use the following folder/directory for convenience's sake.
## E.g. the file used by sed is placed here.
if [ ! -d "$HOME/.usr/etc" ];then mkdir -p "$HOME"/.usr/etc;fi
## Let's define the following file then.
sed_txt="$HOME/.usr/etc/sed.txt"
## And create it, if necessary.
if [ ! -f "$sed_txt" ];then
cat >>"$sed_txt"<<_EOF_
s_\(.*\)?url=__
s_\(.*\)&url=__
s_\(.*\)l.php?u=__
s_&domain=\(.*\)__
s_&ei=\(.*\)__
s_\(.*\)&rl=NONE&u=__
s_&rid=\(.*\)__
s_&h=\(.*\)__
s_?fb\_\(.*\)__
s_%20__g
s_%23_#_
s_%26_\&_g
s_%2B_+_
s_%2C_,_g
s_%2F_/_g
s_%3A_:_
s_%3B_;_g
s_%3D_=_g
s_%3F_?_g
s_%5B_[_g
s_%5D_]_g
s_%7B_{_g
s_%7D_}_g
s_\ __g
_EOF_
fi
if [ -z "$1" ];then
echo -e ${Blue}"\t(Hit \"${Yellow}ctrl+shift+v${Blue}\" to paste.)\n"${Nc}
echo -en ${Yellow}"\tPlease enter your url: "${Nc}
read Name
  if [ -z "$Name" ];then echo -e ${Red}"\tPlease provide me with a string to work on."${Nc}
  else 
  [ -n "$Name" ];Name="$Name"
  fi
fi
## If 'Name' is not zero or null then...
if [ -n "$1" ];then Name="$1";fi
## Echo 'Name' to sed and remove the bollocks.
Name=$(echo "$Name" | sed -f "$sed_txt")
## If the links are pasted into a file, then...
## Replace previously mentioned bollocks 'in place' (the '-i' flag)
if [ -f "$1" ];then Name="$1";sed -f "$sed_txt" -i "$1";fi
## I'm only interested in the 'watch?v=blablablala' part,
## when it comes to youtube.
if [ -n "$(echo "$Name" |grep 'youtube')" ];then
echo -e ${Magenta}"\t${Name%%&*}"
## Also interested when it's a link pointing to facebook.
elif [ -n "$(echo "$Name" |grep 'facebook')" ];then
echo -e ${Blue}"\t"$Name""${Nc}
else echo -e ${Cyan}"\t"$Name""${Nc}
fi
}

Usage:

## Usage:
## 'interactive'
# 1.
strip
## paste in url after being prompted.
# 2.
strip 'your.url'
## Don't forget to 'quote' your url.
## Though "..." will work too I recommend you to use '...'
## 'non-interactive'
## You've pasted in a lot of links in somefile.txt and then...
# 3.
strip somefile.txt

For convenience sake I’ve put this one in my ‘$HOME/.bash_functions‘, as evidenced by the screenshots. I’m sharing this with you. Because: You might find it {amusing,useful,helpful,entertaining,*}!? Or because I’m just a nice guy who feels that sharing means caring. ;-)

Here are the colors.

## Insert a new line into '$HOME/.bashrc'
echo >> $HOME/.bashrc
## Or simply hit 'ctrl+d' instead of using '<<_EOF_' here.
cat >> $HOME/.bashrc<<_EOF_
# Define some colors first:
# 30=black 31=red 32=green 33=yellow 34=blue 35=magenta 36=cyan 37=white
export Black="\033[0;30m"
export Red="\033[0;31m"
export Green="\033[0;32m"
export Yellow="\033[1;33m"
export Blue="\033[1;34m"
export Magenta="\033[1;35m"
export Cyan="\033[1;36m"
export White="\033[1;37m"
export Nc="\033[0m" # No Color
# --> Nice. Has the same effect as using "ansi.sys" in DOS.
_EOF_

And here's once again the how to enable the '$HOME/.bash_functions' thingy.

## Insert a new line into '$HOME/.bashrc'
echo >> $HOME/.bashrc
## Or simply hit 'ctrl+d' instead of using '<<_EOF_' here.
## The following will enable to use the function as described below.
cat >> $HOME/.bashrc<<_EOF_
# Functions: check for a separate function file, and if we find one
# source it.
if [ -f ~/.bash_functions ]; then
    . ~/.bash_functions
fi
_EOF_

Anyway!

Examples:

“Interactively”

http://www.mixcloud.com/DJSe7en/dj-se7en-mix-the-planet-vol15/


(As taken just this evening from facebook and added a few extras today.)
(24032012)
Before:


http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.playboymisssocial.com%2F&h=RAQFvsC_-AQFRx55SPqil_JYHPWEW4nytMsksW3fOFX0Ypg


http://www.facebook.com/l.php?u=http%3A%2F%2Fow.ly%2F9PP0F&h=kAQEiTaSGAQG02htRNOvwQocRMZqb6Lvvw21eTTFSGUd8XA


http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhDHSKcmVV68&h=yAQFKRwBG


http://www.facebook.com/l.php?u=http%3A%2F%2Fyoutu.be%2FDbB1xCF0YOw&h=_AQHBSUYyAQG7l3donnX4LDeIAxtXDT-bRqSkCtpjmHbrww


http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKU194KNl1II&h=_AQHBSUYyAQHf7mlqIUoTQlACI-jW9U4fz_7K-7RizSVquw


http://www.facebook.com/l.php?u=http%3A%2F%2Floudwire.com%2Fmarch-metal-madness-devil-horn-region-round-2%2F&h=yAQFKRwBGAQEhb5YfMtp7t_20knbYQCmBIiqgyeEha-jEww


http://www.facebook.com/l.php?u=http%3A%2F%2Fwww.globalresearch.ca%2Findex.php%3Fcontext%3Dva%26aid%3D29835&h=-AQEk02rLAQGHTETth6he4NRwboeWSKY0vnxIiLQgCMdevg


http://www.google.nl/url?sa=t&rct=j&q=police%20state%20usa%3A%20new%20obama%20executive%20order%20seizes%20u.s.%20infrastructure%20and%20citizens%20for%20military%20preparedness&source=web&cd=4&ved=0CD0QFjAD&url=http%3A%2F%2Fbreakthematrix.com%2Fenergy%2Fobama-executive-order-seizes-infrastructure-citizens-military-preparedness%2F&ei=eKVtT7WaG4ntOajVkfYF&usg=AFQjCNEatlPmGYQvhkHn7s7z8n2fhZTLaQ


http://www.google.nl/url?sa=t&rct=j&q=police%20state%20usa%3A%20new%20obama%20executive%20order%20seizes%20u.s.%20infrastructure%20and%20citizens%20for%20military%20preparedness&source=web&cd=5&ved=0CEMQFjAE&url=http%3A%2F%2Fozhouse.org%2F2012%2F03%2F20%2Fnew-obama-executive-order-seizes-u-s-infrastructure-and-citizens-for-military-preparedness%2F&ei=eKVtT7WaG4ntOajVkfYF&usg=AFQjCNHJNmUjLJPxB6HtqL4uepb7vxlzEg


https://encrypted.google.com/url?sa=t&rct=j&q=police%20state%20usa%3A%20new%20obama%20executive%20order%20seizes%20u.s.%20infrastructure%20and%20citizens%20for%20military%20preparedness&source=web&cd=3&ved=0CDUQFjAC&url=http%3A%2F%2Fwww.infowars.com%2Fnew-obama-executive-order-seizes-u-s-infrastructure-and-citizens-for-military-preparedness%2F&ei=q6VtT9ZDgoQ6j67p-wU&usg=AFQjCNFqlF-CwBgp8ei2IBmZSE13oATJPA

Now run the sed function as described up above.

Et voila, c’est tout. ;-) :


http://www.playboymisssocial.com/


http://ow.ly/9PP0F











http://loudwire.com/march-metal-madness-devil-horn-region-round-2/


http://www.globalresearch.ca/index.php?context=va&aid=29835


http://breakthematrix.com/energy/obama-executive-order-seizes-infrastructure-citizens-military-preparedness/


http://ozhouse.org/2012/03/20/new-obama-executive-order-seizes-u-s-infrastructure-and-citizens-for-military-preparedness/


http://www.infowars.com/new-obama-executive-order-seizes-u-s-infrastructure-and-citizens-for-military-preparedness/

Now how to make scripts executable in Ubuntu.

And for the astute reader: Yes I write my posts and comments in a text-editor before I publish them on Facebook, because this has at least two major benefits.
1. I’ve got spell check enabled. ;-) I know many English words by heart sure, but a ‘failsafe’ like this comes in quite handy.
2. I can order and format my text more properly!!!

That’s all folks!

Kindest regards,

Alex

♫ d(。◕‿◕。)b ♪♪

PS: My words are my own, my actions are my own. Everything I wrote and did in this post are my own responsibility. All I’m offering is: YAP! ;-)

«Everything we do (in life) is meaningless, without the appropriate conviction

Before you comment!?

Back to top.

So you want to browse anonymously and help others to achieve the same goal!?

Updated today: Thursday, November 17, 2011
Reason: Script should be near perfect, i.e. bulletproof and foolproof. If not? Then I’m only an email away. ;-)

Republished again today: Wednesday, November 09, 2011 <– Thus qualifies as a *bump*
The MAIN reason.

The title also refers to making relays better accessible.

The simplest and best solution I can think of is: For you to visit their website https://www.torproject.org/ and read up on what Tor can and can not do for you!

When you’re convinced of the benefits of anonymous browsing, then…

Click on the Download Tor link, select your platform and be off on your merry way! :lol: Yes folks that is all there is to it.


But

While the info above is useful for the above average tor user. I however felt the need to write out a script for those of us who wish to make an ‘advanced’ use of Tor’s capabilities while at the same time making sure that our Relay actually can be reached by those who need it the most!

Advanced‘ refers to being able to change your sources.list: in either Debian or Ubuntu and thus being able to either configure a relay in a graphical fashion or the manual “hard” way on your own.

I got my info from here and I wanted to simplify matters.
HowcanImakemyrelayaccessibletopeoplestuckbehindrestrictivefirewalls

Based on my platform of preference, this will only work for G.Linux but feel free to add your own (ask nicely and I’ll add it in.) This script can be used in conjunction with the iptables howto I wrote earlier. If NOT, then be sure to replace the ‘tobesortedout’ chain with ‘INPUT’ (default) or your own (if defined?).

Modified: Today (20 Nov. 2011) by E.L.F.
Reason: Completely rewritten and should proof to be satisfactory. If not!? ;-)

The Port forwarding Script goes here:
Available as a Demo only, on this page.

#!/bin/bash
# Modified: Today by E.L.F.
#
## Licensed as:
## http://www.opensource.org/licenses/mit-license.php
#
## Script-name - Pf.Tor.sh
#
## Define some colors first:
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m" # No Color
## --> Nice. Has the same effect as using "ansi.sys" in DOS.
set -e
#if [ ! "$USER" = root ];then
#  echo -e ${RED}"\tError:${CYAN} \""$USER"\"${YELLOW} isn't allowed to use this script!"${NC};exit 0
#else
#  echo -e ${BLUE}"\t"$USER" may proceed.\n\t${CYAN}May peace be with you."${NC}
#  echo
#fi
clear
SCRIPT=$(basename "$0")
## Trying to be "standard compliant here".
if [ ! -f /etc/iptables.rules ]
then
echo -e ${YELLOW}"\tYou haven't created a firewall as per the author's instructions."${NC}
echo -e ${YELLOW}"\tPlease create the file mentioned or point this script to the right one."${NC}
echo -e ${YELLOW}"\tOr point this script to the one you use instead."${NC}
exit 0
else
echo
echo -e ${BLUE}"\tEverything's OK."${NC}
fi
clear
## It is always useful to know one's internal ipaddress.
echo -e "*-------------------------------${CYAN}${SCRIPT}${NC}----------------------------------*"
WAN=$(netstat -r -n | sed -e "s/^0\.0\.0\.0 *\([0-9.]*\).*/\1/p" -e d )
echo -e ${BLUE}"\tYour router's IP address is: "${NC}
echo -e ${CYAN}"\t$WAN"${NC}
LAN=$(ifconfig $(netstat -r -n | sed -e "s/^0\.0\.0\.0 *.* \([^ ]*\)/\1/p" -e d ) | sed -e 's/ *inet addr:\([0-9.]*\).*/\1/p' -e d )
echo -e ${BLUE}"\tYour IP address is: "${NC}
echo -e ${CYAN}"\t$LAN"${NC}
echo "*--------------------------------------------------------------------------*"
echo
MIN=2
MAX=4
if [ "$#" -eq "0" -o "$#" -eq "1" -o "$#" -eq "3" -o "$#" -gt "$MAX" ]
  then echo -e ${YELLOW}"\tThe ${CYAN}"$SCRIPT"${YELLOW} script needs at least 2 and at most 4 options."${NC}
  echo -e ${YELLOW}"\tUsage:${CYAN} "$SCRIPT" 443 9001${YELLOW} or ${CYAN}"$(basename "$0")" 443 9001 80 9030"${NC}
  echo -e ${RED}"\tWARNING${YELLOW}: For any port chosen under 20 this script will${CYAN} EXIT${YELLOW}!"${NC}
  exit 0
## Assume BOTH.
elif [ "$#" -eq "$MAX" ];then
  if [[ "$1" =~ [^0-9]+ ]] || [[ "$2" =~ [^0-9]+ ]] || [[ "$3" =~ [^0-9]+ ]] || [[ "$4" =~ [^0-9]+ ]]
  then echo -e ${YELLOW}"\tOnly numerical input is allowed.\n\tE.g.:${CYAN} 443 9001 80 9030"${NC};exit 0;fi
  if [ "$1" -le 20 -o "$3" -le 20 ];then echo -e ${YELLOW}"\tPorts can't be less than 20!"${NC};exit 0;fi
  if [ "$1" -ge 1025 -o "$2" -le 1024 -o "$3" -ge 1025 -o "$4" -le 1024 ];then exit 0
  else [ "$1" -le 1024 -a "$2" -ge 1025 -a "$3" -le 1024 -a "$4" -ge 1025 ];fi
  RELAY="$1";ORPORT="$2";DIR="$3";DIRPORT="$4";NODIR=NO
## Assume ORPORT only.
elif [ "$#" -eq "$MIN" ];then
  if [[ "$1" =~ [^0-9]+ ]] || [[ "$2" =~ [^0-9]+ ]];then echo -e ${YELLOW}"\tOnly numerical input is allowed.\n\tE.g.:${CYAN} 443 9001"${NC};exit 0;fi
  if [ "$1" -le 20 ];then echo -e ${YELLOW}"\tPorts can't be less than 20!"${NC};exit 0;fi
  if [ "$1" -ge 1025 -o "$2" -le 1024 ];then exit 0;else [ "$1" -le 1024 -a "$2" -ge 1025 ];fi
  RELAY="$1";ORPORT="$2";NODIR=YES
else
  exit 0
fi
if [ "$NODIR" = YES ];then
  echo -e ${CYAN}"iptables -I tobesortedout 3 -i eth0 -p tcp -m tcp --dport "$ORPORT" --tcp-flags FIN,SYN,RST,ACK SYN -m connlimit --connlimit-above 16 --connlimit-mask 24 -j REJECT --reject-with tcp-reset"${NC}
  echo -e ${CYAN}"iptables -I tobesortedout 4 -i eth0 -p tcp -m tcp --dport "$ORPORT" -m state --state NEW -m limit --limit 20/sec --limit-burst 40 -j ACCEPT"${NC}
  echo -e ${CYAN}"iptables -t nat -A PREROUTING -p tcp -d "$LAN" --dport "$RELAY" -j DNAT --to-destination "$LAN":"$ORPORT""${NC}
  echo -e ${CYAN}"iptables -t nat -A OUTPUT -p tcp -d "$WAN" --dport "$RELAY" -j DNAT --to-destination "$LAN":"$ORPORT""${NC}
else [ "$NODIR" = NO ]
  echo -e ${CYAN}"iptables -I tobesortedout 3 -i eth0 -p tcp -m tcp --dport "$ORPORT" --tcp-flags FIN,SYN,RST,ACK SYN -m connlimit --connlimit-above 16 --connlimit-mask 24 -j REJECT --reject-with tcp-reset"${NC}
  echo -e ${CYAN}"iptables -I tobesortedout 4 -i eth0 -p tcp -m tcp --dport "$ORPORT" -m state --state NEW -m limit --limit 20/sec --limit-burst 40 -j ACCEPT"${NC}
  echo -e ${CYAN}"iptables -t nat -A PREROUTING -p tcp -d "$LAN" --dport "$RELAY" -j DNAT --to-destination "$LAN":"$ORPORT""${NC}
  echo -e ${CYAN}"iptables -t nat -A OUTPUT -p tcp -d "$WAN" --dport "$RELAY" -j DNAT --to-destination "$LAN":"$ORPORT""${NC}
  echo -e ${CYAN}"iptables -I tobesortedout 5 -i eth0 -p tcp -m tcp --dport "$DIRPORT" --tcp-flags FIN,SYN,RST,ACK SYN -m connlimit --connlimit-above 16 --connlimit-mask 24 -j REJECT --reject-with tcp-reset"${NC}
  echo -e ${CYAN}"iptables -I tobesortedout 6 -i eth0 -p tcp -m tcp --dport "$DIRPORT" -m state --state NEW -m limit --limit 20/sec --limit-burst 40 -j ACCEPT"${NC}
  echo -e ${CYAN}"iptables -t nat -A PREROUTING -p tcp -d "$LAN" --dport "$DIR" -j DNAT --to-destination "$LAN":"$DIRPORT""${NC}
fi
exit 0

Usage: Only numerical input is allowed!
(Don’t choose a port under 20 it will make this script exit.)

## Usage: Only numerical input is allowed!
## Don't choose a port under 20 it will make this script exit.
# Pf.tor.sh "relay" "orport" "dir" "dirport"
# Standalone to see its usage.
./Pf.tor.sh
# Or-port only.
# Therefore only two arguments.
./Pf.tor.sh 443 9001
# Both Or and Dir-port
# Therefore only four arguments.
./Pf.tor.sh 443 9001 80 9030
#

Now about those color definitions used in the script above:
(These start around line 10)

## For these colors to work either keep the next 5 lines.
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"              # No Color
#
## OR...
#
## Paste the following lines in your ~/.bashrc file for a more 'global feel'. ; - )
## (At the bottom is recommended.)
## Do uncomment those first before resourcing your ~/.bashrc file. ; - )
## http://tldp.org/LDP/abs/html/sample-bashrc.html
## Define some colors first:
RED="\033[0;31m"
export RED
BLUE="\033[1;34m"
export BLUE
CYAN="\033[1;36m"
export CYAN
YELLOW="\033[1;33m"
export YELLOW
NC="\033[0m"              # No Color
export NC
# --> Nice. Has the same effect as using "ansi.sys" in DOS.
## Don't forget to resource your bashrc file!

This script can easily be edited for other “port-forwarding” purposes of course (Which for now is to set up your iptables to function properly as a Tor Relay only.). And yes, you have to uncomment all featured commands for them to work.

Why? Because scripts that have to be run as root equals writing demos only to me! Or... you can take a look here for a live version. ;-)

Please also note the “Pf.tor.sh.txt.asc” file. It means that you can verify that I made this script:

How?

gpg --verify Pf.tor.sh.txt.asc Pf.tor.sh.txt

But remember!
Despite my efforts to code properly!
(When in doubt always shout...) :lol:

## What I've written:
## IS PROVIDED "AS IS",
## WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
## INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
## IN NO EVENT SHALL THE AUTHOR(S) OR COPYRIGHT HOLDER(S)
## BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
## WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
## ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
## OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## For more: http://www.opensource.org/licenses/mit-license.php

See the gallery for a visual representation of the above mentioned script.
(Hiding my internal ip as I did NOT in these pictures, would merely constitute "a security through obscurity" trick.)

For a working example of what one could accomplish with this script, can be seen here.

Also I might or might not enhance my script even further by automatically adding/editing the appropriate stanzas in the 'torrc' file. So one only has to run this script once, restart Tor and then be off with a good start. <-- Maybe!?

Introducing… *drum rollz*

The One Script to rule them all… :lol:

Updated today Nov. 17, 2011

This post will be the natural successor to this one.

## Source of inspiration.
/etc/init.d/SCRIPT -> /lib/init/upstart-job

I took the liberty to recombine my three most used scripts into one. ;-)
Its usage is simple:

## The scale and quote scripts take additional parameter(s).
## For 'scale': 4cif, pal or hd are the only options at the moment.
## But feel free to add your own.
## All others: script.name file.name
you@somewhere:~$ ./scale.avi name-of-your-movie.avi (4cif, pal, hd)
e.g.: ./scale.avi name-of-your-movie.avi hd # Upscale file to "$HD" i.e. 1280x720
you@somewhere:~$ ./quote.avi name-of-your-movie.avi (Start End (Either in whole seconds or HH:MM:SS.MSS))
e.g.: ./quote.avi name-of-your-movie.avi 30 60 # Starts at 30s and has a duration of 60s.
e.g.: ./quote.avi name-of-your-movie.avi 60 # Starts at 0s and has a duration of 60s.
you@somewhere:~$ ./xtract.z.avi name-of-your-movie.avi
## Or: (if the script is within your "$PATH"?
scale.avi name-of-your-movie.avi hd # Upscale file to "$HD" i.e. 1280x720
quote.avi name-of-your-movie.avi 30 60 # Starts at 30s and has a duration of 60s.
quote.avi name-of-your-movie.avi 59,04 # Starts at 0s and has a duration of 59.040s.
xtract.z.avi name-of-your-movie.avi
xtract.z.flv name-of-your-movie.flv # I.e. Youtube or equiv. ; - )
## 'z'? equals 'from' ; - )

As for one’s “$PATH”.

# http://linuxcommand.org/wss0010.php
## His Pah is very strong. : - )
## Insert the following in your ~/.bashrc
## Preferably at the end!
## What I use.
# PATH=$PATH:$HOME/.usr/bin
PATH=$PATH:$HOME/your/folder/of/choice
export PATH
## Then all scripts you create and which are placed in "$PATH"
## Can be executed from anywhere you have permission to execute those.
#
## Otherwise you'll have to 'cd' to the folder where your script lives and
## do: ./your-script with-whatever-options-you-have-concocted with-file.ext
## Oh, don't forget to do: chmod u+x on your script first.

In my enthusiasm to post this asap I forgot to mention that for one this script allows you to copy and paste directly from e.g. nautilus. :-)

But (what I as well forgot to mention):
Your folders and files will be RENAMED if either of those contains space(s)!!! If you don’t want that to happen then simply renaming your file(s), and if applicable your folder(s), before running this script should do the trick. ;-)

## When copied from nautilus:
## From:
file:///your/file/at%20some%20where/with%20nasty%20spaces.ext
## To:
/your/file/at.some.where/with.nasty.spaces.ext
## When using tab completion in your shell.
## Type and, if exist, tab until completion.
## From:
/your/file/at\ some\ where/with\ nasty\ spaces.ext
## To:
/your/file/at.some.where/with.nasty.spaces.ext

You might just want to save the following few lines just below for posterity’s sake!? ;-) Why? Well… In order for the script posted on this page to work you’ll have to embrace the concept of linking!

## You might just want to save the following few lines just below for posterity's sake. ; - )
SCRIPT="$(basename "$0")"
for FILE in quote.o{ga,gg,gm} quote.flac quote.avi quote.m{p2,p3,p4,pe,peg,pg,kv} quote.w{mv,av};do ln -s -T "${SCRIPT}" "$(echo "${FILE}")";done
for FILE in scale.o{gg,gm} scale.flac scale.avi scale.m{p4,pe,peg,pg,kv} scale.wmv;do ln -s -T "${SCRIPT}" "$(echo "${FILE}")";done
for FILE in xtract.z.o{gg,gm} xtract.z.avi xtract.z.flv xtract.z.m{p4,pe,peg,pg,kv} xtract.z.wmv;do ln -s -T "${SCRIPT}" "$(echo "${FILE}")";done

Part 1. Its head.

#!/bin/bash
# Modified: Today by E.L.F.
#
## Licensed as:
## http://www.opensource.org/licenses/mit-license.php
#
## Script-name - skel.sh
#
set -e
if [ "$USER" = root ];then
  echo -e ${RED}"Are you Insane!"${NC}
  echo -e ${RED}"Error: In order to use this script, one must NOT be "$USER""${NC}
  echo -e ${YELLOW}"Exiting..."${NC}
  exit 0
else
  echo ""
  echo -e ${BLUE}"    "$USER" may proceed."${NC}
  echo -e ${CYAN}"    May peace be with you."${NC}
fi
clear
for COMMAND in mencoder ffmpeg oggenc cat
do COMMAND=$(which "$COMMAND")
if [ ! -x "$COMMAND" ];then RESULT=NO
echo -e ${YELLOW}"    Please install "${COMMAND}" first before continuing.${NC}
${CYAN}sudo apt-get install "$(basename "${COMMAND}")""${NC};fi
done
if [ "$RESULT" = NO ]; then echo -e ${BLUE}"See (for example):${NC}${YELLOW} http://ubuntuforums.org/showthread.php?t=766683${NC}${BLUE} for more info on the matter."${NC};exit 0;fi
## Variables for the 'scale' command.
date="$(date +"%A, %B %-d, %Y")"
copy=$(echo "Up to you.")
publisher=$(echo "Up to you.")
UPS_EXT=.mkv
HD=1280x720
PAL=720x576
_4CIF=704x576
## Variables for the 'quote' command.
## If 'START' is 'empty' then.
ZERO=00:00:00.000
## If 'END' is 'empty' then.
HALF=00:00:30.000
## Variables for the 'xtract.z' command.
## Print working directory.
PWD=$(pwd)
## Scriptname.
SCRIPT="$(basename "$0")"
## 'basename' of the script.
BASE="$(basename ${SCRIPT%.*})"
## Its 'extension'.
EXT="${SCRIPT/${BASE}/}"
## End variables!
## What would you have your 'arbiter' do.
for OPTION in "${BASE}";do OPTION="${OPTION}";done
for CHOICE in "${EXT}";do CHOICE="${CHOICE}";done
#  ## When no argument is given, print its usage.
  if [ "$BASE" = scale ];then USAGE=$(echo "Usage: "${SCRIPT}" yourfile"${EXT}" 4cif, pal, hd")
  elif [ "$BASE" = quote ];then USAGE=$(echo "Usage: "${SCRIPT}" yourfile"${EXT}" Start End (Either in whole seconds or HH:MM:SS.MSS)")
  else USAGE="Usage: "${SCRIPT}" yourfile"${EXT}"";fi
  if [ "$#" == "0" ];then echo -e ${YELLOW}"$USAGE"${NC};exit 0;fi

Part 2. Its body part 1.

case "$OPTION" in
"cat" | "create")
  if [ "$#" == 1 ];then OUTPUT="$1";OUTPUT+="${EXT}";else echo -n "Enter filename: ";read OUTPUT;OUTPUT+="${EXT}";fi
  echo "$OUTPUT"
  case "$OPTION" in
  "cat")
    case "$CHOICE" in
    ".avi" | ".vob" | ".wmv")
    # LS=$(ls *.{avi,mp{e,eg,g},wmv} 2>/dev/null)
    LS=$(ls *"${EXT}" 2>/dev/null)
    echo "$LS"
    mencoder -forceidx -oac copy -ovc copy $(ls *.avi | sort -n) -o "$OUTPUT"
    mv "$OUTPUT" ../"$OUTPUT"
    \rm *"${EXT}" 2>/dev/null
    mv ../"$OUTPUT" .
    ;;
    ".mpg")
    VAR="mpg-files.txt"
    ls *.mp{e,eg,g} 2>/dev/null | sort > $VAR
    cat $VAR | while read line; do
    INPUT=$(echo ${line})
    cat "$INPUT" >> "$OUTPUT"
    done
    \rm $VAR
    mv "$OUTPUT" ../"$OUTPUT"
    \rm *.mp{e,eg,g} 2>/dev/null
    mv ../"$OUTPUT" .
    ;;
    esac
  ;;
  "create")
    echo "#EXTM3U" > "$OUTPUT"
    find -iname '*.ogg' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mp2' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mp3' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mp4' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mpg' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.wma' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.flv' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.f4v' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.avi' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mkv' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.wmv' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    ;;
  esac
;;

Part 3. Its body part 2 (Ah, IT has no tail :lol: ).

"scale" | "quote" | "xtract.z")
  ## Does the filename contain spaces.
  URLENC=$(echo "$1" | sed -e "s_%20_\\ _g")
  if [ -n "${URLENC}" ];then DIR=${URLENC/file:\/\//};else DIR="${DIR}";fi
  ## If so, then move the file into a more 'workable' state.
  MOVED=$(echo "${DIR}" | sed -e "s_\\ _._g")
  if [ -f "${MOVED}" ];then DIR="${DIR}";else mv "${DIR}" "${MOVED}";DIR=${MOVED};fi
  ## Filename. <-- Everything is a 'file' or should I say 'object'.
  FILE=$(basename "${DIR}")
  ## Its 'basename'.
  BASEF=$(basename ${FILE%.*})
  ## Its 'extension'.
  EXTF="${FILE/${BASEF}/}"
  ## Name of out-file.
  OUTPUT=$(basename ${DIR%.*})
  ## Uh oh! 'Error' time.
  if [ ! -f "$DIR" ];then echo -e ${YELLOW}"    The file: "$DIR" doesn't exist!${NC}\n${RED}    Exiting...!!!"${NC}; exit 0;fi
  if [ ! "$EXT" = "$EXTF" ];then
  echo -e ${YELLOW}"  You made a typo!?${NC} ${CYAN}*auto-correcting*${NC}\n
  ${BLUE}From:${NC} ${YELLOW}"$SCRIPT" "${DIR}"${NC}\n
  ${BLUE}To:${NC} ${YELLOW}  "$BASE""$EXTF" "${DIR}""${NC}
  echo
  SCRIPT="$BASE""$EXTF"
  unset EXT
  EXT="${SCRIPT/${BASE}/}"
  sleep 1
  fi
  case "$OPTION" in
  "scale")
    if [ -f "$DIR" ];then
    if [ "$#" == "1" ];then DIR="$DIR";RES=pal;else
    for RES in "$2";do RES=${RES};done
    case "${RES}" in
      "4cif" )
      RES="$HD"
      ;;
      "pal" )
      RES="$PAL"
      ;;
      "pal" )
      RES="$_4CIF"
      ;;
      *)
      echo -e ${YELLOW}"    Please choose a valid option!"${NC}
      echo -e ${BLUE}"    "Usage:"${NC} ${CYAN}"$SCRIPT" "$DIR"${NC} |${CYAN}"4cif"${NC}|${CYAN}"pal"${NC}|${CYAN}"hd"${NC}|"
      exit 0
      ;;
    esac
    fi
    OUTPUT+="$UPS_EXT"
    ffmpeg -y -i "$DIR" \
    -acodec copy \
    -alang eng \
    -vlang eng \
    -metadata title=""$(basename "$OUTPUT" "$UPS_EXT")". ®" \
    -metadata artist=""$USER"" \
    -metadata date="$date" \
    -metadata publisher="$publisher" \
    -metadata copyright="$copy" \
    -vcodec libx264 -vpre lossless_ultrafast -crf 18 \
    -s "$RES" \
    "$OUTPUT"
    fi
  ;;
  "quote")
    if [ -f "$1" ];then
      if [ "$#" == "3" ];then START="$2" && DUR="$3"
      elif [ "$#" == "2" ];then START="${ZERO}" && DUR="$2"
      else [ "$#" == "1" ]
        echo -e ${BLUE}"\tEither in seconds or...,"${NC}
        echo -e ${BLUE}"\tHH:MM:SS.MSS or...,"${NC}
        echo -e ${BLUE}"\tPress enter for starts at 0."${NC}
        echo -en "\tEnter Start Position : "
        read START
        echo -e ${BLUE}"\tEither in seconds or...,"${NC}
        echo -e ${BLUE}"\tHH:MM:SS.MSS"${NC}
        echo -e ${BLUE}"\tPress enter for lasts 30 seconds."${NC}        
        echo -en "\tEnter Duration : "
        read DUR
      fi
      if [ -z "$START" ];then START="${ZERO}";fi
      if [ -z "$DUR" ];then DUR="${HALF}";fi
      for DIGITS in "$START" "$DUR";do
      if [[ "$DIGITS" =~ [^\ 0-9.,:]+ ]];then exit 0;fi
      done
      ## Arg "$2" NEEDS TO BE "QUOTED", e.g. "00 01 30.200"! But at least it works now. ; - )
      SPACE=$(echo "$START" | sed -e "s_\\ _:_g")
      if [ -n "$SPACE" ];then START="$SPACE"
      else start=${START%[ .,_-]*};end=${START/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        START="$start"."$end"
      fi
      ## My num pad doesn't have a dot but uses comma instead.
      COMMA=$(echo "$START" | sed -e "s_,_._g")      
      if [ "$COMMA" = . ];then COMMA="${ZERO}";fi
      if [ -n "$COMMA" ];then START="$COMMA"
      else start=${START%[ .,_-]*};end=${START/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        START="$start"."$end"
      fi
      SPACE=$(echo "$DUR" | sed -e "s_\\ _:_g")
      if [ -n "$SPACE" ];then DUR="$SPACE"
      else start=${DUR%[ .,_-]*};end=${DUR/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        DUR="$start"."$end"
      fi
      COMMA=$(echo "$DUR" | sed -e "s_,_._g")
      if [ "$COMMA" = . ];then COMMA="${HALF}";fi      
      if [ -n "$COMMA" ];then DUR="$COMMA"
      else start=${DUR%[ .,_-]*};end=${DUR/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        DUR="$start"."$end"
      fi
      echo -e ${YELLOW}""${START}""${NC}
      echo -e ${YELLOW}""${DUR}""${NC}      
    OUTPUT+=.quote"$EXT"
    if [ "$EXT" = .oga ] || [ "$EXT" = .ogg ] || [ "$EXT" = .flac ] || [ "$EXT" = .wav ] || [ "$EXT" = .mp3 ];then Choice=AUDIO;else Choice=VIDEO;fi
      case "$Choice" in
      "AUDIO")
      echo -e ${BLUE}"\tffmpeg -y -i "$1" -ss "${START}" -t "${DUR}" -acodec copy -vn "${OUTPUT}""${NC}
      ;;
      "VIDEO")
      echo -e ${BLUE}"\tmencoder -ss "${START}" -endpos "${DUR}" -oac copy -ovc copy "$1" -o "${OUTPUT}""${NC}
      ;;
      esac
    fi
  ;;
  "xtract.z")
    if [ -f "$DIR" ];then WD=ripped/"${BASEF}";OUTPUT=${PWD}"/"${WD}"/"${BASEF};[ ! -d "${WD}" ] && mkdir -p "${WD}"
    ffmpeg -y -threads 2 -i "${DIR}" -vn -acodec pcm_s16le -ac 2 "${WD}"/${BASEF}.wav
    ffmpeg -y -threads 2 -i "${WD}"/${BASEF}.wav -f mp3 -acodec libmp3lame -ac 2 -ab 320k "${WD}"/${BASEF}.mp3
    oggenc "${WD}"/${BASEF}.wav -q 9
    ffmpeg -y -threads 2 -i "${DIR}" -an -vcodec copy "${WD}"/${BASEF}.rip.avi
    fi
  ;;
  esac
;;
esac
exit 0

Part 4. Its “tail” (Well sort of. :lol: ).

Questions, suggestions, bugs found!? Feel free to let me know at this address: http://wp.me/PNJrg-p. Will I answer? That depends entirely upon you. ; - ) If you found a flaw/bug and you want me to point you out for that on here, then just say so. Otherwise all other email will be processed confidentially.

The actual script live and for the taking.

#!/bin/bash
# Modified: Today by E.L.F.
#
## Licensed as:
## http://www.opensource.org/licenses/mit-license.php
#
## Script-name - skel.sh
#
set -e
if [ "$USER" = root ];then
  echo -e ${RED}"\tError:${CYAN} \""$USER"\"${YELLOW} isn't allowed to use this script!"${NC};exit 0
else
  echo -e ${BLUE}"\t"$USER" may proceed.\n\t${CYAN}May peace be with you."${NC}
  echo
fi
clear
if [ "$(basename "$0")" = skel.sh ];then
  echo -e "${YELLOW}\tIf the${CYAN} \"Van\"${YELLOW} is${CYAN} Rockin'
  ${YELLOW}\tThen Don't Come a${CYAN} Knockin'"${NC};exit 0
fi
for COMMAND in mencoder ffmpeg oggenc cat
do COMMAND=$(which "$COMMAND")
if [ ! -x "$COMMAND" ];then RESULT=NO
echo -e ${YELLOW}"\tPlease install "${COMMAND}" first before continuing.${NC}
${CYAN}\tsudo apt-get install "$(basename "${COMMAND}")""${NC};fi
done
if [ "$RESULT" = NO ]; then echo -e ${BLUE}"\tSee (for example):${YELLOW} http://ubuntuforums.org/showthread.php?t=766683${BLUE} for more info on the matter."${NC};exit 0;fi
## Variables for the 'scale' command.
date="$(date +"%A, %B %-d, %Y")"
copy=$(echo "Up to you.")
publisher=$(echo "Up to you.")
UPS_EXT=.mkv
HD=1280x720
PAL=720x576
_4CIF=704x576
## Variables for the 'quote' command.
## If 'START' is 'empty' then.
ZERO=00:00:00.000
## If 'END' is 'empty' then.
HALF=00:00:30.000
## Variables for the 'xtract.z' command.
## Print working directory.
PWD=$(pwd)
## Scriptname.
SCRIPT="$(basename "$0")"
## 'basename' of the script.
BASE="$(basename ${SCRIPT%.*})"
## Its 'extension'.
EXT="${SCRIPT/${BASE}/}"
## End variables!
## What would you have your 'arbiter' do.
for OPTION in "${BASE}";do OPTION="${OPTION}";done
for CHOICE in "${EXT}";do CHOICE="${CHOICE}";done
#  ## When no argument is given, print its usage.
  if [ "$BASE" = scale ];then USAGE=$(echo "Usage: "${SCRIPT}" yourfile"${EXT}" 4cif, pal, hd")
  elif [ "$BASE" = quote ];then USAGE=$(echo "Usage: "${SCRIPT}" yourfile"${EXT}" Start End (Either in whole seconds or HH:MM:SS.MSS)")
  elif [ "$BASE" = clean.up ];then USAGE=$(echo "Usage: "${SCRIPT}" yourfile"${EXT}" norm, clean, rev, flash")
  else USAGE="Usage: "${SCRIPT}" yourfile"${EXT}"";fi
  if [ "$#" == "0" ];then echo -e ${YELLOW}"$USAGE"${NC};exit 0;fi
case "$OPTION" in
"cat" | "create")
  if [ "$#" == 1 ];then OUTPUT="$1";OUTPUT+="${EXT}";else echo -en "Enter filename: ";read OUTPUT;OUTPUT+="${EXT}";fi
  echo "$OUTPUT"
  case "$OPTION" in
  "cat")
    case "$CHOICE" in
    ".avi" | ".vob" | ".wmv")
    # LS=$(ls *.{avi,mp{e,eg,g},wmv} 2>/dev/null)
    LS=$(ls *"${EXT}" 2>/dev/null)
    echo "$LS"
    mencoder -forceidx -oac copy -ovc copy $(ls *"$EXT" | sort -n) -o "$OUTPUT"
    mv "$OUTPUT" ../"$OUTPUT"
    \rm *"${EXT}" 2>/dev/null
    mv ../"$OUTPUT" .
    ;;
    ".mpg")
    VAR="mpg-files.txt"
    ls *.mp{e,eg,g} 2>/dev/null | sort > $VAR
    cat $VAR | while read line; do
    INPUT=$(echo ${line})
    cat "$INPUT" >> "$OUTPUT"
    done
    \rm $VAR
    mv "$OUTPUT" ../"$OUTPUT"
    \rm *.mp{e,eg,g} 2>/dev/null
    mv ../"$OUTPUT" .
    ;;
    esac
  ;;
  "create")
    echo "#EXTM3U" > "$OUTPUT"
    find -iname '*.ogg' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mp2' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mp3' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mp4' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mpg' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.wma' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.flv' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.f4v' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.avi' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.mkv' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    find -iname '*.wmv' -exec ls "{}" \; | sort -n >> "$OUTPUT"
    ;;
  esac
;;
"scale" | "quote" | "xtract.z")
  ## Does the filename contain spaces.
  URLENC=$(echo "$1" | sed -e "s_%20_\\ _g")
  if [ -n "${URLENC}" ];then DIR=${URLENC/file:\/\//};else DIR="${DIR}";fi
  ## If so, then move the file into a more 'workable' state.
  MOVED=$(echo "${DIR}" | sed -e "s_\\ _._g")
  if [ -f "${MOVED}" ];then DIR="${DIR}";else mv "${DIR}" "${MOVED}";DIR=${MOVED};fi
  ## Filename. <-- Everything is a 'file' or should I say 'object'.
  FILE=$(basename "${DIR}")
  ## Its 'basename'.
  BASEF=$(basename ${FILE%.*})
  ## Its 'extension'.
  EXTF="${FILE/${BASEF}/}"
  ## Name of out-file.
  OUTPUT=$(basename ${DIR%.*})
  ## Uh oh! 'Error' time.
  if [ ! -f "$DIR" ];then echo -e ${YELLOW}"\tThe file: "$DIR" doesn't exist!\n${RED}    Exiting...!!!"${NC}; exit 0;fi
  if [ ! "$EXT" = "$EXTF" ];then
  echo -e ${YELLOW}"\tYou made a typo!? ${CYAN}*auto-correcting*\n
  ${BLUE}\tFrom: ${YELLOW}"$SCRIPT" "${DIR}"\n
  ${BLUE}\tTo: ${YELLOW}  "$BASE""$EXTF" "${DIR}""${NC}
  echo
  SCRIPT="$BASE""$EXTF"
  unset EXT
  EXT="${SCRIPT/${BASE}/}"
  sleep 1
  fi
  case "$OPTION" in
  "scale")
    if [ -f "$DIR" ];then
    if [ "$#" == "1" ];then DIR="$DIR";RES=pal;else
    for RES in "$2";do RES=${RES};done
    case "${RES}" in
      "4cif" )
      RES="$HD"
      ;;
      "pal" )
      RES="$PAL"
      ;;
      "pal" )
      RES="$_4CIF"
      ;;
      *)
      echo -e ${YELLOW}"\tPlease choose a valid option!"${NC}
      echo -e ${BLUE}"\t"Usage:" ${CYAN}"$SCRIPT" "$DIR" |${CYAN}"4cif"|${CYAN}"pal"|${CYAN}"hd"${NC}|"
      exit 0
      ;;
    esac
    fi
    OUTPUT+="$UPS_EXT"
    ffmpeg -y -i "$DIR" \
    -acodec copy \
    -alang eng \
    -vlang eng \
    -metadata title=""$(basename "$OUTPUT" "$UPS_EXT")". ®" \
    -metadata artist=""$USER"" \
    -metadata date="$date" \
    -metadata publisher="$publisher" \
    -metadata copyright="$copy" \
    -vcodec libx264 -vpre lossless_ultrafast -crf 18 \
    -s "$RES" \
    "$OUTPUT"
    fi
  ;;
  "quote")
    if [ -f "$DIR" ];then
      if [ "$#" == "3" ];then START="$2" && DUR="$3"
      elif [ "$#" == "2" ];then START="${ZERO}" && DUR="$2"
      else [ "$#" == "1" ]
        echo -e ${BLUE}"\tEither in seconds or...,"${NC}
        echo -e ${BLUE}"\tHH:MM:SS.MSS or...,"${NC}
        echo -e ${BLUE}"\tPress enter for starts at 0."${NC}
        echo -en "\tEnter Start Position : "
        read START
        echo -e ${BLUE}"\tEither in seconds or...,"${NC}
        echo -e ${BLUE}"\tHH:MM:SS.MSS"${NC}
        echo -e ${BLUE}"\tPress enter for lasts 30 seconds."${NC}
        echo -en "\tEnter Duration : "
        read DUR
      fi
      if [ -z "$START" ];then START="${ZERO}";fi
      if [ -z "$DUR" ];then DUR="${HALF}";fi
      for DIGITS in "$START" "$DUR";do
      if [[ "$DIGITS" =~ [^\ 0-9.,:]+ ]];then exit 0;fi
      done
      ## Arg "$2" NEEDS TO BE "QUOTED", e.g. "00 01 30.200"! But at least it works now. ; - )
      SPACE=$(echo "$START" | sed -e "s_\\ _:_g")
      if [ -n "$SPACE" ];then START="$SPACE"
      else start=${START%[ .,_-]*};end=${START/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        START="$start"."$end"
      fi
      ## My num pad doesn't have a dot but uses comma instead.
      COMMA=$(echo "$START" | sed -e "s_,_._g")
      if [ "$COMMA" = . ];then COMMA="${ZERO}";fi
      if [ -n "$COMMA" ];then START="$COMMA"
      else start=${START%[ .,_-]*};end=${START/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        START="$start"."$end"
      fi
      SPACE=$(echo "$DUR" | sed -e "s_\\ _:_g")
      if [ -n "$SPACE" ];then DUR="$SPACE"
      else start=${DUR%[ .,_-]*};end=${DUR/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        DUR="$start"."$end"
      fi
      COMMA=$(echo "$DUR" | sed -e "s_,_._g")
      if [ "$COMMA" = . ];then COMMA="${HALF}";fi
      if [ -n "$COMMA" ];then DUR="$COMMA"
      else start=${DUR%[ .,_-]*};end=${DUR/${start}[ .,_-]/}
        if [ "${start}" = "${end}" ];then end=000;else end="$end";fi
        DUR="$start"."$end"
      fi
    OUTPUT+=.quote"$EXT"
    if [ "$EXT" = .oga ] || [ "$EXT" = .ogg ] || [ "$EXT" = .flac ] || [ "$EXT" = .wav ] || [ "$EXT" = .mp3 ];then Choice=AUDIO;else Choice=VIDEO;fi
      case "$Choice" in
      "AUDIO")
      ffmpeg -y -i "${DIR}" -ss "${START}" -t "${DUR}" -acodec copy -vn "${OUTPUT}"
      ;;
      "VIDEO")
      mencoder -ss "${START}" -endpos "${DUR}" -oac copy -ovc copy "${DIR}" -o "${OUTPUT}"
      ;;
      esac
    fi
  "xtract.z")
    if [ -f "$DIR" ];then WD=ripped/"${BASEF}";OUTPUT=${PWD}"/"${WD}"/"${BASEF};[ ! -d "${WD}" ] && mkdir -p "${WD}"
    ffmpeg -y -threads 2 -i "${DIR}" -vn -acodec pcm_s16le -ac 2 "${WD}"/${BASEF}.wav
    ffmpeg -y -threads 2 -i "${WD}"/${BASEF}.wav -f mp3 -acodec libmp3lame -ac 2 -ab 320k "${WD}"/${BASEF}.mp3
    oggenc "${WD}"/${BASEF}.wav -q 9
    ffmpeg -y -threads 2 -i "${DIR}" -an -vcodec copy "${WD}"/${BASEF}.rip.avi
    fi
  ;;
  esac
;;
esac
exit 0

How to quote from your media.

Just a friendly notice: This post will frequently be updated and at the discretion of the user ‘republished’.
“…under the premise that the only way to really learn scripting is to write scripts.” ;-)

This post is yet another follow up on:
Conversions.

Updated today: Sunday, November 6, 2011
The main reason: I’ve combined both scripts, who were once mentioned on this page. ;-)

BUT… In order for it all to work, one has to do the following:

alias link='ln -s -T'
## Assuming here ~/bin to be the user's personal script folder.
## As it usually is on Ubuntu
## (that would be ~/.usr/bin in my case. ; - )
## And assuming here that you saved the script,
## provided on this page as: 'scale.sh'
## Otherwise change 'scale.sh' to whatever has your fancy.
cd ~/bin
## This will give you the scaling abilities of the previous 'upscale.sh' script.
link scale.sh scale.avi
link scale.sh scale.mkv
link scale.sh scale.mp4
link scale.sh scale.mpg
link scale.sh scale.ogg
link scale.sh scale.ogm
link scale.sh scale.ogv
link scale.sh scale.wmv
## And this will provide you with the quoting abilities of the previous 'quote.sh' script.
link scale.sh quote.avi
link scale.sh quote.flac
link scale.sh quote.mkv
link scale.sh quote.mp3
link scale.sh quote.mp4
link scale.sh quote.mpg
link scale.sh quote.oga
link scale.sh quote.ogg
link scale.sh quote.ogm
link scale.sh quote.ogv
link scale.sh quote.wav
link scale.sh quote.wmv
## And now you have one script that you can invoke in many ways. ; - )
## But at the moment only as a demo.
## It's up to you to remove those few remaining echo statements,
## Those who do the actual work, see it as an exercise.

Also before we dive into the script, this post originally referred to, I wanted to point out a Very Nice Tool that I’ve recently discovered!

Here is a slightly altered ‘plist’ (xml based) I frequently use to for example convert my personal DVD collection. The ‘preference list’ I obtained from here: http://ubuntuforums.org/showthread.php?t=1350522

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
	<dict>
		<key>AudioList</key>
		<array>
			<dict>
				<key>AudioBitrate</key>
				<string>160</string>
				<key>AudioEncoder</key>
				<string>AAC (faac)</string>
				<key>AudioMixdown</key>
				<string>Dolby Pro Logic II</string>
				<key>AudioSamplerate</key>
				<string>48</string>
				<key>AudioTrack</key>
				<integer>1</integer>
				<key>AudioTrackDRCSlider</key>
				<real>0</real>
				<key>AudioTrackDescription</key>
				<string>English (AC3) (5.1 ch)</string>
			</dict>
		</array>
		<key>ChapterMarkers</key>
		<false />
		<key>Default</key>
		<false />
		<key>FileFormat</key>
		<string>MP4 file</string>
		<key>Folder</key>
		<false />
		<key>Mp4HttpOptimize</key>
		<false />
		<key>Mp4LargeFile</key>
		<false />
		<key>Mp4iPodCompatible</key>
		<false />
		<key>PictureAutoCrop</key>
		<true />
		<key>PictureBottomCrop</key>
		<integer>0</integer>
		<key>PictureDeblock</key>
		<integer>4</integer>
		<key>PictureDecomb</key>
		<integer>2</integer>
		<key>PictureDecombCustom</key>
		<string></string>
		<key>PictureDecombDeinterlace</key>
		<true />
		<key>PictureDeinterlace</key>
		<integer>0</integer>
		<key>PictureDeinterlaceCustom</key>
		<string></string>
		<key>PictureDenoise</key>
		<integer>0</integer>
		<key>PictureDenoiseCustom</key>
		<string></string>
		<key>PictureDetelecine</key>
		<integer>2</integer>
		<key>PictureDetelecineCustom</key>
		<string></string>
		<key>PictureHeight</key>
		<integer>0</integer>
		<key>PictureKeepRatio</key>
		<true />
		<key>PictureLeftCrop</key>
		<integer>8</integer>
		<key>PictureLooseCrop</key>
		<true />
		<key>PictureModulus</key>
		<integer>1</integer>
		<key>PicturePAR</key>
		<string>1</string>
		<key>PicturePARHeight</key>
		<integer>15</integer>
		<key>PicturePARWidth</key>
		<integer>16</integer>
		<key>PictureRightCrop</key>
		<integer>6</integer>
		<key>PictureTopCrop</key>
		<integer>0</integer>
		<key>PictureWidth</key>
		<integer>0</integer>
		<key>PresetBuildNumber</key>
		<integer>2009112300</integer>
		<key>PresetDescription</key>
		<string>HandBrake&apos;s general-purpose preset for High Profile H.264 video, with all the bells and whistles.</string>
		<key>PresetName</key>
		<string>PS3</string>
		<key>SubtitleList</key>
		<array>
		</array>
		<key>Type</key>
		<integer>1</integer>
		<key>UsesPictureFilters</key>
		<integer>1</integer>
		<key>UsesPictureSettings</key>
		<integer>2</integer>
		<key>VideoAvgBitrate</key>
		<integer>2500</integer>
		<key>VideoEncoder</key>
		<string>H.264 (x264)</string>
		<key>VideoFramerate</key>
		<string>Same as source</string>
		<key>VideoGrayScale</key>
		<false />
		<key>VideoQualitySlider</key>
		<real>20</real>
		<key>VideoQualityType</key>
		<integer>1</integer>
		<key>VideoTargetSize</key>
		<integer>700</integer>
		<key>VideoTurboTwoPass</key>
		<false />
		<key>VideoTwoPass</key>
		<false />
		<key>anamorphic</key>
		<true />
		<key>par_height</key>
		<integer>0</integer>
		<key>par_width</key>
		<integer>0</integer>
		<key>x264Option</key>
		<string>rc-lookahead=50:ref=1:bframes=0:subme=6:trellis=0:analyse=none</string>
	</dict>
</array>
</plist>

^^ I hope this helps!?

The following applies to the following script!

## Either invoke as:
you@somewhere:~$ ./scale.avi name-of-your-movie.avi
you@somewhere:~$ ./quote.avi name-of-your-movie.avi
## Or: (if the script is within your "$PATH"?
you@somewhere:~$ scale.avi name-of-your-movie.avi
you@somewhere:~$ quote.avi name-of-your-movie.avi

The newly combined script goes here:
[It's only 185 lines long now, this includes comments. ;-) ]

What does it do? It either “quotes from” or “(up)scales” the media it is presented with by the user. By passing the filename (w/- or w/o (assumes pwd = wd)) its full path to the script (and yes the script does strip off the “file:///” thingy when copied from within nautilus or eq.)

Scriptname: scale.sh:

#!/bin/bash
# Modified: Today by E.L.F.
#
## http://www.gnu.org/copyleft/gpl.html
#
## Script-name - scale.sh
#
UPS_EXT=.mkv
HD=1280x720
PAL=720x576
_4CIF=704x576
PWD=$(pwd)
export PWD
NOPARAMS=0
MINPARAMS=1
MAXPARAMS=2
date="$(date +"%A, %B %-d, %Y")"
copy=$(echo "Whatever you like!?")
SCRIPT=$(basename "$0")
BASE=$(basename ${SCRIPT%.*})
if [ "$BASE" = scale ]; then REPLACE=scale;OPTION=_1;else [ "$BASE" = quote ]; REPLACE=quote;OPTION=_2;fi
EXT=${SCRIPT#${REPLACE}}
export EXT
export OPTION
FILE=$(basename "$1")
BASEF=$(basename ${FILE%.*})
EXTF=${FILE#${BASEF}}
export EXTF
if [ "$USER" = root ]; then
  echo -e ${RED}"Are you Insane!"${NC}
  echo -e ${RED}"Error: In order to use this script, one must NOT be "$USER""${NC}
  echo -e ${YELLOW}"Exiting..."${NC}
  exit 0
else
  echo ""
  echo -e ${BLUE}"    "$USER" may proceed."${NC}
  echo -e ${CYAN}"    May peace be with you."${NC}
fi
clear
## http://tor-relay.thruhere.net/abs-guide/
## ^^ Always learning! ; - )
echo
  if [ "$#" -eq "$MAXPARAMS" ];then DIR="$1" && RES="$2";fi
  if [ "$#" -eq "$MINPARAMS" ];then DIR="$1";RES=pal;fi
  if [ -n "$1" ]; then DIR=${DIR/file:\/\//};else DIR="$DIR";fi
  if [ -n "$2" ];then RES="$RES"; else RES="$RES";fi
  if [ "$RES" = hd ];then RES="$HD";else RES="$RES";fi
  if [ "$RES" = pal ];then RES="$PAL";else RES="$RES";fi
  if [ "$RES" = 4cif ];then RES="$_4CIF";else RES="$RES";fi
  if [ ! -f "$DIR" ]; then echo -e ${YELLOW}"    The file: "$DIR" doesn't exist! Or you didn't provide one?${NC}\n${RED}    Exiting...!!!"${NC}; exit 0;fi
  if [ ! "$EXT" = "$EXTF" ]; then
  echo -e ${YELLOW}"      You probably invoked this script the wrong way:\n
      E.g.:${NC} ${BLUE}"$BASE""$EXTF" "$FILE"${NC} ${YELLOW}is correct.\n\
      ${YELLOW}However:${NC} ${BLUE}"$SCRIPT" "$FILE"${NC} ${YELLOW}is NOT."${NC}
  exit 0
  fi
if [ "$OPTION" = _1 ]; then CHOICE=SCALE;else CHOICE=QUOTE;fi
case "$CHOICE" in
"SCALE")
  if [ -f "$DIR" ]; then
  echo -e ${CYAN}" Extension:    "$EXT""${NC}
  echo -e ${CYAN}"   In file:    "$DIR""${NC}
  OUTPUT=$(basename ${DIR%.*})
  OUTPUT+="$UPS_EXT"
  echo -e ${CYAN}"  Out file:    "$PWD"/"$OUTPUT""${NC}
  echo -e ${CYAN}"Resolution:    "$RES""${NC}
  ffmpeg -y -i "$DIR" \
  -acodec copy \
  -alang eng \
  -vlang eng \
  -metadata title=""$(basename "$OUTPUT" "$UPS_EXT")". ®" \
  -metadata artist=""$USER"" \
  -metadata date="$date" \
  -metadata publisher="Whatever you like!?" \
  -metadata copyright="$copy" \
  -vcodec libx264 -vpre lossless_ultrafast -crf 18 \
  -s "$RES" \
  "$OUTPUT"
  fi
;;
"QUOTE")
  if [ -f "$DIR" ]; then
  echo -e ${CYAN}" Extension:    "$EXT""${NC}
  echo -e ${CYAN}"   In file:    "$DIR""${NC}
  OUTPUT=$(basename ${DIR%.*})
  OUTPUT+=.quoted"$EXT"
  echo -e ${CYAN}"  Out file:    "$PWD"/"$OUTPUT""${NC}
  if [ "$EXT" = .oga ] || [ "$EXT" = .ogg ] || [ "$EXT" = .flac ] || [ "$EXT" = .wav ] || [ "$EXT" = .mp3 ]; then Choice=AUDIO;else Choice=VIDEO;fi
  echo -e ${BLUE}"    Either in seconds or...,"${NC}
  echo -e ${BLUE}"    HH:MM:SS.MSS or...,"${NC}
  echo -e ${BLUE}"    Press enter for starts at 0"${NC}
  echo -n "Enter Start Position : "
  read START
  if [ -z "$START" ]; then START=00:00:00.000;fi
  if [[ "$START" =~ [A-Za-z]+ ]];then echo -e ${RED}"    Input MUST be numerical."${NC};echo -e ${YELLOW}"    Exiting..."${NC};exit 0;fi
  start=${START%[ .,_-]*}
  end=${START/${start}[ .,_-]/}
  if [ "${start}" = "${end}" ]; then end=000;else end="$end";fi
  START="$start"."$end"
  echo -e ${BLUE}"    Either in seconds or...,"${NC}
  echo -e ${BLUE}"    HH:MM:SS.MSS"${NC}
  echo -n "Enter Duration : "
  read DUR
  if [ -z "$DUR" ]; then echo -e ${RED}"    Duration can't be zero!."${NC};echo -e ${YELLOW}"Exiting..."${NC};exit 0;fi
  if [[ "$DUR" =~ [A-Za-z]+ ]];then echo -e ${RED}"    Input MUST be numerical."${NC};echo -e ${YELLOW}"    Exiting..."${NC};exit 0;fi
  start=${DUR%[ .,_-]*}
  end=${DUR/${start}[ .,_-]/}
  if [ "${start}" = "${end}" ]; then end=000;else end="$end";fi
  DUR="$start"."$end"
    case "$Choice" in
    "AUDIO")
    echo -e ${CYAN}"ffmpeg -y -i "${DIR}" -ss "${START}" -t "${DUR}" -acodec copy -vn "${OUTPUT}""${NC}
    ffmpeg -y -i "${DIR}" -ss "${START}" -t "${DUR}" -acodec copy -vn "${OUTPUT}"
    ;;
    "VIDEO")
    mencoder -ss "${START}" -endpos "${DUR}" -oac copy -ovc copy "${DIR}" -o "${OUTPUT}"
    ;;
    *)
    echo
    echo -e ${YELLOW}"    Please try again?"${NC} ${BLUE}"Possible reason: unsupported filetype?"${NC}
    echo -e ${CYAN}"    The file used was: "$DIR"."${NC}
    ;;
    esac
  fi
;;
*)
  echo
  echo -e ${YELLOW}"    Please try again?"${NC} ${BLUE}"Possible reason: unsupported filetype?"${NC}
  echo -e ${CYAN}"    The file used was: "$DIR"."${NC}
;;
esac
exit 0

Now about those color definitions used in the script above:
(Oh noes they’re not there anymore! Did I do that on purpose!? :lol: )

## For these colors to work either insert the next 5 lines in the script above.
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"              # No Color
#
## OR...
#
## Paste the following lines in your ~/.bashrc file for a more 'global feel'. ; - )
## (At the bottom is recommended.)
## http://tldp.org/LDP/abs/html/sample-bashrc.html
## Define some colors first:
RED="\033[0;31m"
export RED
BLUE="\033[1;34m"
export BLUE
CYAN="\033[1;36m"
export CYAN
YELLOW="\033[1;33m"
export YELLOW
NC="\033[0m"              # No Color
export NC
# --> Nice. Has the same effect as using "ansi.sys" in DOS.
## Don't forget to resource your ~/.bashrc file!

Still code efficiency is everything. . <-- So while I managed to greatly reduce the amount of lines used and inserted a check for numeric input only. It still doesn't meet my standards for “Elegance”. :-(

Less is (still) more!

To do: It would be nice if I could specify my input:
e.g. HH:MM:SS.MSS as HH MM SS MSS instead.

The astute reader will for instance see that the script already allows for this format:
SEC MSS to specify either the start or end of a quote.
That would be:

[ .,_-]

To be exact (for a change :lol: )!

To do as well: To make it possible to copy and paste in URLs with spaces in both the filename as well as the folder path(s)! I might want to have a look at:

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

Which is a string I found here!

Next assignment: Write a nautilus script to make it easier for a user to just select his/her files and do the “conversion” (if any) from there.


^^ Or: Simply make your terminal transparent, so you can see what you’re affecting. ;-)

Samples:

More free goodies? – Yes!!! :lol:

## This is from my $HOME/.bash_functions
## The mandatory: "Hello World" ; - )
hello()
{
    echo "Hello, "$1""
}
## Tidy up any html file with 'tidy'
mtidy()
{
config=$(echo "$HOME/.usr/bin/etc/config.txt")
tidy -config $config $1
}
## Extract all media from flash.
## I do all possible outcomes, just in case. ; - )
xtract.z.flv()
{
WD=./ripped
FOLDER="$WD"/$(basename "$1" .flv)
[ ! -d "$FOLDER" ] && mkdir -p "$FOLDER"
ffmpeg -y -threads 2 -i "$1" -vn -acodec pcm_s16le -ac 2 "$FOLDER"/$(basename "$1" .flv).wav # <-- Rip audio from flv to wav.
ffmpeg -y -threads 2 -i "$FOLDER"/$(basename "$1" .flv).wav -f mp3 -acodec libmp3lame -ac 2 -ab 320k "$FOLDER"/$(basename "$1" .flv).mp3 # <-- Rip to mp3.
oggenc "$FOLDER"/$(basename "$1" .flv).wav -q 9 # <-- Rip to ogg.
ffmpeg -y -threads 2 -i "$1" -an -vcodec copy "$FOLDER"/$(basename "$1" .flv).rip.avi # <-- Rip the video only.
\rm "$FOLDER"/$(basename "$1" .flv).wav
}
## Extract all media from avi.
xtract.z.avi()
{
WD=./ripped
FOLDER="$WD"/$(basename "$1" .avi)
[ ! -d "$FOLDER" ] && mkdir -p "$FOLDER"
ffmpeg -y -threads 2 -i "$1" -vn -acodec pcm_s16le -ac 2 "$FOLDER"/$(basename "$1" .avi).wav # <-- Rip audio from flv to wav.
ffmpeg -y -threads 2 -i "$FOLDER"/$(basename "$1" .avi).wav -f mp3 -acodec libmp3lame -ac 2 -ab 320k "$FOLDER"/$(basename "$1" .avi).mp3 # <-- Rip to mp3.
oggenc "$FOLDER"/$(basename "$1" .avi).wav -q 9 # <-- Rip to ogg.
ffmpeg -y -threads 2 -i "$1" -an -vcodec copy "$FOLDER"/$(basename "$1" .avi).rip.avi # <-- Rip the video only.
\rm "$FOLDER"/$(basename "$1" .avi).wav
}
## Extract all media from mpg.
xtract.z.mpg()
{
WD=./ripped
FOLDER="$WD"/$(basename "$1" .mpg)
[ ! -d "$FOLDER" ] && mkdir -p "$FOLDER"
ffmpeg -y -threads 2 -i "$1" -vn -acodec pcm_s16le -ac 2 "$FOLDER"/$(basename "$1" .mpg).wav # <-- Rip audio from flv to wav.
ffmpeg -y -threads 2 -i "$FOLDER"/$(basename "$1" .mpg).wav -f mp3 -acodec libmp3lame -ac 2 -ab 320k "$FOLDER"/$(basename "$1" .mpg).mp3 # <-- Rip to mp3.
oggenc "$FOLDER"/$(basename "$1" .mpg).wav -q 9 # <-- Rip to ogg.
ffmpeg -y -threads 2 -i "$1" -an -vcodec copy "$FOLDER"/$(basename "$1" .mpg).rip.avi # <-- Rip the video only.
\rm "$FOLDER"/$(basename "$1" .mpg).wav
}
## Extract all media from mp4.
xtract.z.mp4()
{
WD=./ripped
FOLDER="$WD"/$(basename "$1" .mp4)
[ ! -d "$FOLDER" ] && mkdir -p "$FOLDER"
ffmpeg -y -threads 2 -i "$1" -vn -acodec pcm_s16le -ac 2 "$FOLDER"/$(basename "$1" .mp4).wav # <-- Rip audio from flv to wav.
ffmpeg -y -threads 2 -i "$FOLDER"/$(basename "$1" .mp4).wav -f mp3 -acodec libmp3lame -ac 2 -ab 320k "$FOLDER"/$(basename "$1" .mp4).mp3 # <-- Rip to mp3.
oggenc "$FOLDER"/$(basename "$1" .mp4).wav -q 9 # <-- Rip to ogg.
ffmpeg -y -threads 2 -i "$1" -an -vcodec copy "$FOLDER"/$(basename "$1" .mp4).rip.avi # <-- Rip the video only.
\rm "$FOLDER"/$(basename "$1" .mp4).wav
}
## Extract all media from wmv.
xtract.z.wmv()
{
WD=./ripped
FOLDER="$WD"/$(basename "$1" .wmv)
[ ! -d "$FOLDER" ] && mkdir -p "$FOLDER"
ffmpeg -y -threads 2 -i "$1" -vn -acodec pcm_s16le -ac 2 "$FOLDER"/$(basename "$1" .wmv).wav # <-- Rip audio from flv to wav.
ffmpeg -y -threads 2 -i "$FOLDER"/$(basename "$1" .wmv).wav -f mp3 -acodec libmp3lame -ac 2 -ab 320k "$FOLDER"/$(basename "$1" .wmv).mp3 # <-- Rip to mp3.
oggenc "$FOLDER"/$(basename "$1" .wmv).wav -q 9 # <-- Rip to ogg.
ffmpeg -y -threads 2 -i "$1" -an -vcodec copy "$FOLDER"/$(basename "$1" .wmv).rip.avi # <-- Rip the video only.
\rm "$FOLDER"/$(basename "$1" .wmv).wav
}
## Rip from wmv to xvid in avi container directly.
## Please note amongst things the -s switch here!
## I.e.: Please, do a...
# ffmpeg -i "$YOUR.INPUT" to show you the resolution, rate, aspect ratio and other useful telltale signs. ; - )
wmv2xvid.hd720()
{
WD=./ripped
FOLDER="$WD"/$(basename "$1" .wmv)
[ ! -d "$FOLDER" ] && mkdir -p "$FOLDER"
ffmpeg -y -threads 2 -i "$1" -f avi -r 25 -vcodec libxvid -vtag XVID -s hd720 -aspect 16:9 -maxrate 1800k -b 1400kb -qmin 3 -qmax 5 -bufsize 4096 -mbd 2 -bf 2 -flags +4mv -trellis -aic -cmp 2 -subcmp 2 -g 300 -an $(basename "$1" .wmv).xvid.avi
}
## Rip from wav to mp3.
wav2mp3()
{
ffmpeg -y -threads 2 -i "$1" -f mp3 -acodec libmp3lame -ac 2 -ab 320k $(basename "$1" .wav).mp3 # <-- Rip to mp3.
}
## Rip from wav to ogg.
wav2ogg()
{
oggenc "$1" -q 9
}
## "panavision" : - )
upscale()
{
mencoder "$1" -endpos 00:00:20 -oac copy -ovc xvid -xvidencopts \
chroma_opt:vhq=4:bvhq=1:quant_type=mpeg:bitrate=1400 \
-vf scale=1280:544,expand=1280:720 \
-o $(basename "$1" .avi).HD.men.avi
}
## Evolvotron specific.
evolve()
{
evolvotron_render -f 96 -r 8 -j -a -m 4 -s 720 576 -spheremap "$1".ppm < $HOME/Downloads/vid.edit/evolved0.xml
}
evolvehd()
{
ffmpeg -y -b 3000k -r 8 -f image2 -i "$1".f%6d.ppm -qscale 4 -qblur 1.0 -aspect 16:9 -g 300 -s hd720 "$1".avi
}
evolvepal()
{
ffmpeg -y -b 3000k -r 8 -f image2 -i "$1".f%6d.ppm -qscale 4 -qblur 1.0 -aspect 16:9 -g 300 "$1".avi
}
## This function will simulate the effect the "mod_deflate" module for Apache has, for the same named files.
## Only to be used with a server who understands the .gz format out of the box: I.e. thttpd
## Also works in a chroot'ed environment. ; - )
massedit()
{
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"
if [ $USER = root ]; then
  echo -e $RED"   Are you Insane!"
  echo -e $CYAN"    Error: In order to use this script, one must NOT be $USER"
  echo -e $YELLOW"    Exiting..."$NC
  exit 0
else
  echo ""
  echo -e $BLUE"    $USER may proceed."
  echo -e $CYAN"    May peace be with you."$NC
fi
clear # Clear the screen.
  case "$1" in
  "HTML" | "Html" | "html")
  if [ ! "$(ls *.html 2>/dev/null)" ]
  then
  echo -e $YELLOW"$1 does not exist."$NC; echo
  else
  echo -e $BLUE"    You've chosen \"$(ls *.html | wc -l)\" file(s) to work on."$NC
  echo -e $RED"Executing..."$NC
  for i in *.html; do gzip -c --best $i > $i.gz;done
  for i in *.html; do \rm $i;done
  for i in *.html.gz; do ln -s -T "$i" $(basename "$i" .gz);done
  fi
  ;;
  "TXT" | "Txt" | "txt" | "TEXT" | "Text" | "text")
  if [ ! "$(ls *.txt 2>/dev/null)" ]
  then
  echo -e $YELLOW"$1 does not exist."$NC; echo
  else
  echo -e $BLUE"    You've chosen \"$(ls *.txt | wc -l)\" file(s) to work on."$NC
  echo -e $RED"Executing..."$NC
  for i in *.txt; do gzip -c --best $i > $i.gz;done
  for i in *.txt; do \rm $i;done
  for i in *.txt.gz; do ln -s -T "$i" $(basename "$i" .gz);done
  fi
  ;;
  "CSS" | "Css" | "css")
  if [ ! "$(ls *.css 2>/dev/null)" ]
  then
  echo -e $YELLOW"$1 does not exist."$NC; echo
  else
  echo -e $BLUE"    You've chosen \"$(ls *.css | wc -l)\" file(s) to work on."$NC
  echo -e $RED"Executing..."$NC
  for i in *.css; do gzip -c --best $i > $i.gz;done
  for i in *.css; do \rm $i;done
  for i in *.css.gz; do ln -s -T "$i" $(basename "$i" .gz);done
  fi
  ;;
  "XML" | "Xml" | "xml")
  if [ ! "$(ls *.xml 2>/dev/null)" ]
  then
  echo -e $YELLOW"$1 does not exist."$NC; echo
  else
  echo -e $BLUE"    You've chosen \"$(ls *.xml | wc -l)\" file(s) to work on."$NC
  echo -e $RED"Executing..."$NC
  for i in *.xml; do gzip -c --best $i > $i.gz;done
  for i in *.xml; do \rm $i;done
  for i in *.xml.gz; do ln -s -T "$i" $(basename "$i" .gz);done
  fi
  ;;
  "JS" | "Js" | "js")
  if [ ! "$(ls *.js 2>/dev/null)" ]
  then
  echo -e $YELLOW"$1 does not exist."$NC; echo
  else
  echo -e $BLUE"    You've chosen \"$(ls *.js | wc -l)\" file(s) to work on."$NC
  echo -e $RED"Executing..."$NC
  for i in *.js; do gzip -c --best $i > $i.gz;done
  for i in *.js; do \rm $i;done
  for i in *.js.gz; do ln -s -T "$i" $(basename "$i" .gz);done
  fi
  ;;
  *)
  echo
  echo "Please choose a valid option."
  echo "\"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
  echo -e $YELLOW"    Usage$NC: "
  echo -e $CYAN"    massedit$NC$BLUE html$NC"
  echo -e $CYAN"    massedit$NC$BLUE text$NC"
  echo -e $CYAN"    massedit$NC$BLUE js$NC"
  echo -e $CYAN"    massedit$NC$BLUE xml$NC"
  echo -e $CYAN"    massedit$NC$BLUE css$NC"
  echo
  ;;
  esac
}
## This one removes the empty lines and unnecessary spaces,
## of the text based type of file,
## you gave it to chew on. ; - )
squeeze()
{
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"
if [ $USER = root ]; then
  echo -e $RED"   Are you Insane!"
  echo -e $CYAN"    Error: In order to use this script, one must NOT be $USER"
  echo -e $YELLOW"    Exiting..."$NC
  exit 0
else
  echo ""
  echo -e $BLUE"    $USER may proceed."
  echo -e $CYAN"    May peace be with you."$NC
fi
clear # Clear the screen.
if [ ! -e "$1" ]
then
echo -e $YELLOW"$1 does not exist."$NC; echo
else
## This removes the trailing spaces in your doc.
sed -i 's/[ \t]*$//' "$1"
## Removing those empty lines for you as well.
sed -i '/^$/d' "$1"
fi
}
## The following function might interest some of you?
## With the added bonus to either sign or verify signatures.
#
## As taken from here: https://calomel.org/openssh.html
## At the bottom of the page you can find the related
## openssl commands which will correspond to the ones
## used in the function below.
crypto()
{
  if [ -z "$1" ]; then
      echo -e $YELLOW"    Please choose a valid option!"$NC  
      echo -e $YELLOW"    Usage"$NC": "$CYAN"\"UPPER\""$NC", "$CYAN"\"lower\""$NC" and "$CYAN"\"Capitalized\""$NC" spelling are supported."
      echo -e $CYAN"    crypto"$NC" {"$CYAN"--ENCRYPT"$NC","$CYAN"--Encrypt"$NC","$CYAN"--encrypt"$NC","$CYAN"-E"$NC","$CYAN"-e"$NC"}: $BLUE Your-file $NC"
      echo -e $CYAN"    crypto"$NC" {"$CYAN"--DECRYPT"$NC","$CYAN"--Decrypt"$NC","$CYAN"--decrypt"$NC","$CYAN"-D"$NC","$CYAN"-d"$NC"}: $BLUE Your-file.aes $NC"
      echo -e $CYAN"    crypto"$NC" {"$CYAN"--SIGN"$NC","$CYAN"--Sign"$NC","$CYAN"--sign"$NC","$CYAN"-S"$NC","$CYAN"-s"$NC"}: $BLUE Your-file $NC"
      echo -e $CYAN"    crypto"$NC" {"$CYAN"--VERIFY"$NC","$CYAN"--Verify"$NC","$CYAN"--verify"$NC","$CYAN"-V"$NC","$CYAN"-v"$NC"}: $BLUE Your-file.asc $NC"
  elif [ -z "$2" ]; then
    echo -e $YELLOW"   Error: Providing a filename is MANDATORY!   "$NC
    echo -e $RED"   Exiting..."$NC
  elif [ -d "$2" ]; then
    echo -e $YELLOW"   Error: File is a directory!"$NC
    echo -e $RED"   Exiting..."$NC
  else
    case "$1" in
      "--ENCRYPT" | "--Encrypt" | "--encrypt" | "-E" | "-e")
      ## to encrypt (-e):
      openssl aes-256-cbc -a -e -salt -in "$2" -out "$2".aes
      ;;
      "--DECRYPT" | "--Decrypt" | "--decrypt" | "-D" | "-d")
      ## to decrypt (-d):
      openssl aes-256-cbc -a -d -salt -in "$2" -out $(basename "$2" .aes)
      ;;
      "--SIGN" | "--Sign" | "--sign" | "-S" | "-s")
      ## to sign (-s):
      echo -e $CYAN"    gpg -a --detach-sign \""$2"\""$NC
      gpg -a --detach-sign "$2"
      ;;
      "--VERIFY" | "--Verify" | "--verify" | "-V" | "-v")
      ## to verify (-v):
      echo -e $CYAN"    gpg --verify \""$2"\" \"$(basename "$2" .asc)\""$NC
      gpg --verify "$2" $(basename "$2" .asc)
      ;;
      *)
      echo
      echo -e $YELLOW"    Nothing done!"$NC
      echo
      ;;
    esac
  fi
}

The tidy config file as mentioned in one of the many functions above. ;-)

// sample config file for HTML tidy
doctype: transitional
indent: auto
indent-spaces: 2
wrap: 76
markup: yes
bare: yes
clean: yes
preserve-entities: yes
output-xml: no
input-xml: no
output-xhtml: yes
show-warnings: yes
numeric-entities: yes
quote-marks: yes
quote-nbsp: yes
quote-ampersand: no
break-before-br: no
uppercase-tags: no
uppercase-attributes: no
char-encoding: utf8
input-encoding: utf8
output-bom: auto
output-encoding: utf8
new-inline-tags: cfif, cfelse, math, mroot,
  mrow, mi, mn, mo, msqrt, mfrac, msubsup, munderover,
  munder, mover, mmultiscripts, msup, msub, mtext,
  mprescripts, mtable, mtr, mtd, mth
new-blocklevel-tags: cfoutput, cfquery
new-empty-tags: cfelse
repeated-attributes: keep-last
error-file: errs.txt
write-back: yes

How?

## Which you can enable just like you'd for a possible .bash_aliases file
## Like so (in your $HOME/.bashrc) in my case around line 91:
## By uncommenting the following, if necessary (i.e.: removing the #'s in front)
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi
## And adding this block right thereafter.
## Don't forget to create the file. ; - )
# Functions: check for a separate function file, and if we find one
# source it.
if [[ -f ~/.bash_functions ]]; then
    . ~/.bash_functions
fi

Iptables how to.

Updated today: Saturday, November 19, 2011
Reason: I’ve added (and updated) my

/etc/iptables.rules

and

/etc/ip6tables.rules

files to this post.

Today I am going to write about firewalls, the linux firewall aka netfilter/iptables to be precise.

So what is a firewall? To my understanding that would be like an imaginary ‘wall of fire’ which tends to keep the bad guys out and the good guys in (can be taken literally!) whatever it is the firewall was meant to protect.

In this sense a firewall may not be of use to you!?

Because:
Obviously, one wants to keep the bad guys out; while at the same time one wants to be able to traverse to and fro the firewall unencumbered. Which basically is what this script intends to give you. ;-) Another intent of this author is for you not to have to fiddle to much with your current router (except when the need arises to enable a service), whether this be the one at home or at your local wifi supplying bar. Or in somewhat more foul language (plain folk speak if you will): I want to be able to plug in my “lappie” in any slut sorry I meant {slot,socket} available :lol: and just go go go…

Strictly speaking: A firewall can’t protect you from a(ny) mis configured serv{ice,ices,er,ers} because to be able to make use of any service, one has to punch a (lot of) hole(s) in his/her firewall, hence there is no benefit gained by applying a firewall with holes. :lol:

Since the reliance of any user on the ‘bulletproof‘ coding of any service is way beyond the scope of this tutorial. I advice you to either NOT run any service or that you look into subjects as ‘apparmor‘ing or (||) SeLinux‘ing your applications and (&&) make use of intrusion systems like snort or ossec-hids.

Another advice that I could give is to NOT simply download away all that is available (this although not self serving would include the usage of my own scripts amongst things) on the net but stick to the repositories made available to you by your distribution when a certain piece of software is needed. Also if the need exists to run a torrent client. ;-) One could consider to run this under another unprivileged account [think kde platform ;-) ] (e.g. ktorrent (this user is biased though :lol: )).

Now that I’ve taken care of these dependencies:

If one searches for intel, then one will find out that there is an abundance of information out there about precisely this subject.

The script I made (which for all purposes should be considered experimental) attempts to be a mix of the above three links. Regardless of the fact that I made a fairly benign script (it only echoes at ye for now) it is advisable/to be recommended that a ‘newbie‘ either turns his attention to the IptablesHowTo of the Ubuntu community or simply installs firestarter (http://www.fs-security.com/).

So do I really need one!
http://psychocats.net/ubuntu/security#firewallantivirus

“Why (should I try to) reinvent the wheel when someone else already has pointed out a similar stance on the matter.”

So, do I need a firewall, anti-virus, anti-spyware tools?

By default, Ubuntu ships with no open ports on public interfaces. In other words, a “port scan” would show all closed ports, nothing open. As a result, putting up a firewall would provide no more security than not putting one up. Remember that open ports provide services that hackers can connect to, and only if they can connect to these services can they be potentially abused and exploited.

A firewall, however, adds the benefit of peace-of-mind from accidentally installing a server program that opens up a port by default. Also, it satisfies curiousity by logging potential “hits.” Linux comes with a very strong, secure, and powerful firewall called iptables, but it is relatively difficult to use from a new user’s standpoint. As a result, there are many graphical tools that give you a simple user interface for configuring iptables, such as Firestarter for GNOME or Guarddog for KDE. There are many more in the repository, too. Remember—these all use iptables in the background, so find your favorite interface—they all offer the same great protection. [These last two paragraphs contributed by jdong from the Ubuntu Forums. Thanks, jdong!]

With all that out of the way let’s start describing this script.

The color codes used in the script below have the following purposes:
$RED= Error!
$BLUE= Tries to explain what is being done
$CYAN= The actual code that would be executed if this script were ‘live’.
$YELLOW= Warning, aka there’s something you need to do first before you can continue
$NC= ‘No Color’ nothing more to it. Think of it as the closing bracket to whatever line it has been implemented.

Now about those color definitions:
(These start around line 54)

## For these colors to work either uncomment the next 5 lines.
#RED="\033[0;31m"
#BLUE="\033[1;34m"
#CYAN="\033[1;36m"
#YELLOW="\033[1;33m"
#NC="\033[0m"              # No Color
#
## OR...
#
## Paste the following lines in your ~/.bashrc file for a more 'global feel'. ; - )
## (At the bottom is recommended.)
## Do uncomment those first before resourcing your ~/.bashrc file. ; - )
## http://tldp.org/LDP/abs/html/sample-bashrc.html
## Define some colors first:
#RED="\033[0;31m"
#export RED
#BLUE="\033[1;34m"
#export BLUE
#CYAN="\033[1;36m"
#export CYAN
#YELLOW="\033[1;33m"
#export YELLOW
#NC="\033[0m"              # No Color
#export NC
# --> Nice. Has the same effect as using "ansi.sys" in DOS.
## Don't forget to resource your bashrc file!

Aside from all that, I believe it really 'cutsyfies' the script. ;-)

*The focus should be on the execution of commands and not the prompt.*

While true, I believe colorizing commands in this fashion actually helps explaining what is being done.

Anyway:
If for any reason you feel "obliged" to use this script (not recommended (yet)) or you feel adventurous (most likely :lol: ). Then I recommend that you use this startup script! The only difference in between the one posted below and the one used here: Configuration on Startup for NetworkManager
is that I ALSO USE ip6tables to block, drop, reject anything that is not of use to me!

For now, I bid you adieu and "may you live long prosper" or "may the force be with you" :lol:

Kindest regards,

Alex


The StartUp Script goes here:

if [ -x /usr/bin/logger ]; then
        LOGGER="/usr/bin/logger -s -p daemon.info -t FirewallHandler"
else
        LOGGER=echo
fi

case "$2" in
        up)
                if [ ! -r /etc/iptables.rules ]; then
                        ${LOGGER} "No iptables rules exist to restore."
                        return
                fi
                if [ ! -r /etc/ip6tables.rules ]; then
                        ${LOGGER} "No iptables rules exist to restore."
                        return
                fi
                if [ ! -x /sbin/iptables-restore ]; then
                        ${LOGGER} "No program exists to restore iptables rules."
                        return
                fi
                ${LOGGER} "Restoring iptables rules"
                /sbin/iptables-restore -c < /etc/iptables.rules
                /sbin/ip6tables-restore -c < /etc/ip6tables.rules                
                ;;
        down)
                if [ ! -x /sbin/iptables-save ]; then
                        ${LOGGER} "No program exists to save iptables rules."
                        return
                fi
                if [ ! -x /sbin/ip6tables-save ]; then
                        ${LOGGER} "No program exists to save iptables rules."
                        return
                fi
                ${LOGGER} "Saving iptables rules."
                /sbin/iptables-save -c > /etc/iptables.rules
                /sbin/ip6tables-save -c > /etc/ip6tables.rules                
                ;;
        *)
                ;;
esac

The HowTo Script goes here:
7 feb. 2011: Slowly but surely we’re getting nearer to the end. ;-)
Also the astute {reader,viewer} will notice a minor mistake in both the script as well in the video. If you have {guessed,seen} it, then you most likely can determine that I am aware of it. ;-)

I should for example include a line like: kill -USR1 “$PROCESS”. To gently kill processes (other than services that run from start up) that create open sockets while using this script.

For transparency’s sake I’m not going to remove my small mistake, besides what was about to be done was only echoed after all and I am here to learn from my own mistakes as well. ;-)

#!/bin/bash
# http://en.support.wordpress.com/code/posting-source-code/
# Modified: Today by E.l.f
#
## http://www.gnu.org/copyleft/gpl.html
#
## Script-name - Conf.Iptables.sh
#
## Scripts executed by root should imo be written with capitals.
## Perhaps preceded with an 'S' to indicate sudo\?
## Which should provide the user a hint about the importance given to said script.
#
## This is a slightly modified version of my current iptables ruleset.
## I also tossed it about a bit for readability, think cascade.
# Sources and other related info.
## No endorsement or approval (from the respective authors) implied
## by linking to these sources.
# https://help.ubuntu.com/community/IptablesHowTo
# http://bodhizazen.net/Tutorials/iptables/#Using_iptables_for_Filtering
# http://www.novell.com/coolsolutions/feature/18139.html
#<----------------------------------------------------------------------------->
## eth0=the interface facing the internet in my case.
## Use at your own risk!
#
# Assumptions:
## A Gnu/linux (compliant) or clone thereof box.
## The client has a simple gateway at home, i.e. a router provided by his/her ISP.
## The interface used for both in and outbound traffic is named eth0
#
## There may be a wireless card on the user\'s computer (do you use one?)?
## In that case either substitute eth0 with the name of the wifi one,
## or make duplicates of the rules referring to eth0 to apply to both interfaces.
#
## NEVER EVER use this script on a remote machine!!!
## Instant lockout IS guaranteed if you do.
## Included a check to counter PRECISELY that.
#
## Script starts here.
# Define some colors first:
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"              # No Color
# --> Nice. Has the same effect as using "ansi.sys" in DOS.
echo -e ${YELLOW}"    What works for me:"${NC}
echo -e ${YELLOW}"    Neither has to apply to you nor does it have to imply"${NC}
echo -e ${YELLOW}"    that it will work for you!?"${NC}
echo -e ${YELLOW}"    Therefore your mileage may vary?"${NC}
echo
echo -e ${YELLOW}"    Since this script is far from being complete!"${NC}
echo -e ${YELLOW}"    And because it is part of my learning experience."${NC}
echo -e ${YELLOW}"    It will only echo (for now) what it is about to execute."${NC}
echo
#if [ $USER != root ]; then
#  echo -e ${RED}"    Only root can do this!"${NC}
#  echo -e ${CYAN}"    Error: In order to use this script, one must NOT be "$USER"!"${NC}
#  echo -e ${CYAN}"    Hint: Use 'sudo -s' and try again."${NC}
#  echo -e ${YELLOW}"    Exiting..."${NC}
#  exit 0
#else
#  echo ""
#  echo -e ${BLUE}"    "$USER" may proceed."${NC}
#  echo -e ${CYAN}"    May peace be with you."${NC}
#fi
clear
echo
echo -e ${BLUE}"    Because I can't determine (yet) if you're logged into a remote machine."${NC}
echo -e ${YELLOW}"    I'll ask you now:  Are you logged in remotely?"${NC}
echo
  echo -n "Enter either yes or no: "
  read ANSWER
    case "$ANSWER" in
    "YES" | "Yes" | "yes")
    echo -e ${RED}"    Not a smart move on your part!"${NC}
    echo -e ${YELLOW}"    Exiting now before you can hurt yourself..."${NC}
    exit 0
    ;;
    "NO" | "No" | "no")
    echo -e ${BLUE}"    Please continue... oh wise, great and powerful one."${NC}
    echo
    ;;
    *)
    echo -e ${RED}"    Wrong answer!!!"
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    exit 0
    ;;
    esac
## This appears to be a promising start.
## Kindly ripped from the torbrowser bundle start up script.
# if any relevant processes are running, inform the user and exit cleanly
## I need to find an alternative to shut down boinc-client?
# boinc: unrecognized service (=user boinc and not service boinc-client)
## Without editing the /etc/init.d/boinc-client script.
## The intent is to have NO SERVICE()S) running while editing the firewall!
## Please edit in your own services as needed.
for process in apache ktorrent polipo privoxy thttpd tor transmission vidalia
do pid=$(pidof $process)
if [ -n "$pid" ]
then
echo -e ${YELLOW}"\n$process is already running as PID $pid\n\n"${NC}
echo -e ${BLUE}"    To continue this script it is advisable to shut down $process."${NC}
echo -e ${YELLOW}"    Do you want me to shut those down for you?"${NC}
echo
  echo -n "Enter either yes or no: "
  read ANSWER
    case "$ANSWER" in
    "YES" | "Yes" | "yes")
    echo -e ${CYAN}"service \"$process\" stop"${NC}
    ;;
    "NO" | "No" | "no")
    echo -e ${BLUE}"    To continue this script it is advisable to shut down $process."${NC}
    exit 0
    ;;
    *)
    echo -e ${RED}"    Wrong answer!!!"
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    exit 0
    ;;
    esac
fi
done
echo -e ${YELLOW}"    Saving your current configuration (just in case)!"${NC} #If any!?
echo -e ${CYAN}"iptables-save > /etc/iptables.rules.jic"${NC}
echo -e ${CYAN}"iptables-save -c > /etc/iptables.save.jic"${NC}
echo
  echo -e ${YELLOW}"    This WILL flush your current iptables ruleset."${NC}
  echo -e ${YELLOW}"    Do you wish to continue?"${NC}
  echo -e ${BLUE}"    If unsure then either type \"no\" or simply hit \"enter\" to abort."${NC}
  echo -n "Enter either yes or no: "
  read Answer
    case "$Answer" in
    "YES" | "Yes" | "yes")
    echo -e ${RED}"   Executing..."${NC}
    echo -e ${YELLOW}"    Reset firewall..."${NC}
    echo -e ${CYAN}"iptables -F"${NC}
    echo -e ${CYAN}"iptables -X"${NC}
    echo -e ${CYAN}"iptables -t nat -F"${NC}
    echo -e ${CYAN}"iptables -t nat -X"${NC}
    echo -e ${CYAN}"iptables -t mangle -F"${NC}
    echo -e ${CYAN}"iptables -t mangle -X"${NC}
    echo -e ${YELLOW}"    All rules flushed!"${NC}
    ;;
    "NO" | "No" | "no")
     echo -e ${CYAN}"    Maybe later..."${NC}
     exit 0
    ;;
    *)
     echo -e ${RED}"    Wrong answer!!!"
     echo -e ${BLUE}"    Please rerun the script again?"
     echo -e ${BLUE}"    Then: Either enter yes or no."
     echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
     echo -e ${CYAN}"    Usage: Yes|No"${NC}
     echo
     exit 0
    ;;
    esac
  echo -e ${BLUE}"    I don't see any reason whatsoever, "${NC}
  echo -e ${BLUE}"    to allow any inbound traffic unless I choose to run a server. "${NC}
  echo -e ${BLUE}"    A torrent client IS of type server! "${NC}
  echo
  echo -e ${YELLOW}"    Do you wish to continue?"${NC}
  echo -e ${BLUE}"    If unsure then either type \"no\" for the default (ACCEPT) or simply hit \"enter\" to abort."${NC}
  echo -n "Enter either yes or no: "
  read Answer
    case "$Answer" in
    "YES" | "Yes" | "yes")
    echo -e ${CYAN}"iptables -P INPUT DROP"${NC}
    echo -e ${CYAN}"iptables -P FORWARD DROP"${NC}
    echo -e ${CYAN}"iptables -P OUTPUT DROP"${NC}
    echo -e ${YELLOW}"    Policy (DROP) is set and enabled!"${NC}
    ;;
    "NO" | "No" | "no")
    echo -e ${YELLOW}"   Maybe later..."${NC}
    echo -e ${CYAN}"iptables -P INPUT ACCEPT"${NC}
    echo -e ${CYAN}"iptables -P FORWARD ACCEPT"${NC}
    echo -e ${CYAN}"iptables -P OUTPUT ACCEPT"${NC}
    echo -e ${YELLOW}"    Policy (ACCEPT) \"default\" is set and enabled!"${NC}
    ;;
    *)
    echo -e ${RED}"    Wrong answer!!!"
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    exit 1
    ;;
    esac
echo -e ${BLUE}"    Setting some sane defaults (OUTPUT) here."${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o lo -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o eth0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT"${NC}
echo -e ${BLUE}"    You do want to be able to update/upgrade and install stuff."${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o eth0 -m owner --uid-owner 0 -j ACCEPT"${NC} # root
## Granting a few other users access here.
## Which in my case refers to the following.
# cat /etc/group | grep <name of group>
# iptables -A OUTPUT -o eth0 -m owner --uid-owner debian-tor -j ACCEPT # debian-tor
# iptables -A OUTPUT -o eth0 -m owner --uid-owner boinc-client -j ACCEPT # boinc-client
echo -e ${BLUE}"    You also want to be able to surf the web, email friends and all that other good stuff."${NC}
echo -e ${CYAN}"iptables -A OUTPUT -o eth0 -m owner --uid-owner 1000 -j ACCEPT"${NC} # you
# iptables -A OUTPUT -o eth0 -m owner --uid-owner 1001 -j ACCEPT # another you
echo -e ${BLUE}"    We don't need to wait for connection time outs!"${NC}
echo -e ${CYAN}"iptables -A OUTPUT -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"iptables -A OUTPUT -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${YELLOW}"    Outbound traffic enabled."${NC}
echo
echo -e ${BLUE}"    Next we are going to create some user defined chains, we will need them later."${NC}
echo -e ${CYAN}"iptables -N blacklist"${NC}
echo -e ${CYAN}"iptables -N icmp"${NC}
echo -e ${CYAN}"iptables -N tobesortedout"${NC}
echo -e ${CYAN}"iptables -N logndrop"${NC}
## Bozo check.
echo -e ${CYAN}"iptables -A INPUT -j blacklist"${NC}
  echo -e ${BLUE}"    The following ipadresses, I have collected over time, are known to scan for "${NC}
  echo -e ${BLUE}"    vulnerabilities in webapplications.  Not that I run any, duh..."${NC}
  echo -e ${BLUE}"    e.g."${NC}
  echo -e ${YELLOW}"    iptables -A blacklist -s <source-ip>(/32) -j REJECT --reject-with icmp-host-prohibited"${NC}
  echo -e ${YELLOW}"    iptables -A blacklist -s <source-net>(/24) -j REJECT --reject-with icmp-net-prohibited"${NC}
  echo -e ${BLUE}"    Placing an octothorpe --> # in front of the following lines,"${NC}
  echo -e ${BLUE}"    obviously will disable the referred to rule."${NC}
  echo -e ${BLUE}"    Deleting them is so much easier!  : - )"${NC}
  echo -e ${BLUE}"    When?"${NC}
  echo -e ${BLUE}"    You don't run or want to run (ever) some service."${NC}
  echo
  echo -e ${YELLOW}"    Do you wish to keep them (NOT mandatory)?"${NC}
  echo -e ${BLUE}"    If unsure then either type \"no\" or simply hit \"enter\" to abort."${NC}
  echo -n "Enter either yes or no: "
  read aNSWER
    case "$aNSWER" in
    "YES" | "Yes" | "yes")
    echo -e ${CYAN}"iptables -A blacklist -s 222.76.86.104/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 218.249.107.12/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 218.38.12.202/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 218.14.146.200/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 217.133.138.220/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 216.245.217.242/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 202.194.15.192/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 202.108.181.80/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 122.95.3.74/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 92.243.84.187/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 86.125.221.212/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 85.17.187.145/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.45.126.182/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.153.229.140/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 79.99.42.182/32 -j REJECT --reject-with icmp-host-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 212.26.193.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 208.80.194.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 208.80.193.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.177.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.176.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.146.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 84.74.144.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.7.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.6.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.5.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.4.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.3.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.2.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.1.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 80.218.0.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -s 71.130.111.0/24 -j REJECT --reject-with icmp-net-prohibited"${NC}
    echo -e ${CYAN}"iptables -A blacklist -j icmp"${NC}
    echo -e ${YELLOW}"    Known repeaters are blocked by default!"${NC}
    ;;
    "NO" | "No" | "no")
    echo -e ${BLUE}"    Don't delete this one!"${NC}
    echo -e ${CYAN}"iptables -A blacklist -j icmp"${NC}
    ;;
    *)
    echo -e ${BLUE}"    Please rerun the script again?"
    echo -e ${BLUE}"    Then: Either enter yes or no."
    echo -e ${BLUE}"    \"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
    echo -e ${CYAN}"    Usage: Yes|No"${NC}
    echo
    echo -e ${RED}"   Executing...(again)"${NC}
    echo -e ${YELLOW}"    Reset firewall..."${NC}
    echo -e ${CYAN}"iptables -F"${NC}
    echo -e ${CYAN}"iptables -X"${NC}
    echo -e ${CYAN}"iptables -t nat -F"${NC}
    echo -e ${CYAN}"iptables -t nat -X"${NC}
    echo -e ${CYAN}"iptables -t mangle -F"${NC}
    echo -e ${CYAN}"iptables -t mangle -X"${NC}
    echo -e ${YELLOW}"    All rules flushed!"${NC}
    echo -e ${YELLOW}"    So you can start fresh again."${NC}
    echo
    exit 0
    ;;
    esac
echo
echo -e ${BLUE}"    The ping utility is a must, whether you believe me or not."${NC}
echo -e ${BLUE}"    Sings *Black hole sun won't you come*"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 0 -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 3 -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 11 -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -p icmp -m icmp --icmp-type 8 -m limit --limit 1/sec -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A icmp -j tobesortedout"${NC}
echo -e ${YELLOW}"    Ping permissions set."${NC}
echo
echo -e ${BLUE}"    Setting some sane defaults (INPUT) here."${NC}
echo -e ${CYAN}"iptables -A tobesortedout -i lo -j ACCEPT"${NC}
echo -e ${CYAN}"iptables -A tobesortedout -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT"${NC}
echo -e ${BLUE}"    From here on out, it is up to you to allow inbound traffic or not."${NC}
echo -e ${BLUE}"    Don't forget to setup your router to set the port of your choice to open!"${NC}
echo
#echo -e ${BLUE}"    Despite the fact that thttpd (Tiny hyper text transfer protocol daemon) is well known for"${NC}
#echo -e ${BLUE}"    being able to serve up a surplus of 1000+ files "${NC}
#echo -e ${BLUE}"    and thus becomes better under pressure.  ; - )"${NC}
#echo -e ${BLUE}"    I've decided to \"rate limit\" the amount of simultaneous connections to this server!"${NC}
## webserver
#echo -e ${CYAN}"iptables -A tobesortedout -i eth0 -p tcp -m state --state NEW -m limit --limit 20/sec --limit-burst 40 -m tcp --dport 80 -j ACCEPT"${NC}
#echo -e ${BLUE}"    Please note that from my perspective: anything lower than 20 per second causes a noticeable lag while loading my own pages.  ; - )"${NC}
echo -e ${CYAN}"iptables -A tobesortedout -j logndrop"${NC}
echo -e ${YELLOW}"I've configured the minimum amount of incomming traffic for you."${NC}
echo
echo -e ${BLUE}"    Surely we want to know, who we've denied while trying to access this server?"${NC}
echo -e ${CYAN}"iptables -A logndrop -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied TCP: " --log-level 7"${NC}
echo -e ${CYAN}"iptables -A logndrop -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied UDP: " --log-level 7"${NC}
echo -e ${CYAN}"iptables -A logndrop -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ICMP: " --log-level 7"${NC}
echo -e ${BLUE}"    Be a good netizen, simply  because we don't like to wait for connections, "${NC}
echo -e ${BLUE}"    to time out on ourselves."${NC}
echo -e ${CYAN}"iptables -A logndrop -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"iptables -A logndrop -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${YELLOW}"    Logging enabled"${NC}
echo
echo -e ${YELLOW}"    I've also turned back on any services you had running before using this script."${NC}
## Work in progress!
# sudo service $DAEMON start
## e.g.
echo -e ${CYAN}"service boinc-client start"${NC}
echo -e ${CYAN}"service polipo start"${NC}
echo -e ${CYAN}"service tor start"${NC}
echo -e ${CYAN}"service thttpd start"${NC}
echo
echo -e ${YELLOW}"    My job is done."${NC}
echo -e ${YELLOW}"    Have a nice day!"${NC}
echo
echo -e ${YELLOW}"    Don't forget to save your new rules!"${NC}
echo -e ${CYAN}"iptables-save > /etc/iptables.rules"${NC}
echo
echo -e ${BLUE}"    #<----------------------------------------------------------------------------->"${NC}
echo -e ${BLUE}"    ## How about ipv6!?  Well since I am not using it anyway."${NC}
echo -e ${BLUE}"    ## (I doubt my router even understands it?)"${NC}
echo -e ${BLUE}"    ## This part refers to the contents of (a future) /etc/ip6tables.rules, "${NC}
echo -e ${BLUE}"    ## if one follows the ubuntu community tutorial that is."${NC}
echo -e ${BLUE}"    #<----------------------------------------------------------------------------->"${NC}
echo -e ${CYAN}"#ip6tables -P INPUT DROP"${NC}
echo -e ${CYAN}"#ip6tables -P FORWARD DROP"${NC}
echo -e ${CYAN}"#ip6tables -P OUTPUT DROP"${NC}
echo -e ${CYAN}"#ip6tables -N logndropip6"${NC}
echo -e ${CYAN}"#ip6tables -A INPUT -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"#ip6tables -A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${CYAN}"#ip6tables -A OUTPUT -j logndropip6"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 TCP: " --log-level 7"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 UDP: " --log-level 7"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 ICMP: " --log-level 7"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p tcp -j REJECT --reject-with tcp-reset"${NC}
echo -e ${CYAN}"#ip6tables -A logndropip6 -p udp -j REJECT --reject-with icmp-port-unreachable"${NC}
echo -e ${BLUE}"    #<----------------------------------------------------------------------------->"${NC}
echo -e ${CYAN}"#ip6tables-save > /etc/ip6tables.rules"${NC}
exit 0
# Generated by ip6tables-save v1.4.1.1 on Tue Sep 21 19:52:49 2010
#*filter
#:INPUT DROP [0:0]
#:FORWARD DROP [0:0]
#:OUTPUT DROP [0:0]
#:logndropip6 - [0:0]
#[0:0] -A INPUT -p tcp -j REJECT --reject-with tcp-reset
#[0:0] -A OUTPUT -j logndropip6
#[0:0] -A logndropip6 -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 TCP: " --log-level 7
#[0:0] -A logndropip6 -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 UDP: " --log-level 7
#[0:0] -A logndropip6 -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 ICMP: " --log-level 7
#[0:0] -A logndropip6 -p tcp -j REJECT --reject-with tcp-reset
#COMMIT
# Completed on Tue Sep 21 19:52:49 2010

A fully working example partially based on the script above can be found here:
Please note that I _ONLY_ use opendns’ nameservers to resolve hostnames now!!! If you do _NOT_ then make sure to change the following rules accordingly. ;-)
Filename:

/etc/iptables.rules
# Generated by iptables-save v1.4.4 on Sat Nov 19 19:39:46 2011
*nat
## Remove the spaces in between the ":" and "P"!!!
## Or maybe I should simply turn off those wordpress smileys?
: PREROUTING ACCEPT [0:0]
: POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
COMMIT
# Completed on Sat Nov 19 19:39:46 2011
# Generated by iptables-save v1.4.4 on Sat Nov 19 19:39:46 2011
*mangle
## Remove the spaces in between the ":" and "P"!!!
: PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
: POSTROUTING ACCEPT [0:0]
COMMIT
# Completed on Sat Nov 19 19:39:46 2011
# Generated by iptables-save v1.4.4 on Sat Nov 19 19:39:46 2011
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:blacklist - [0:0]
:icmp - [0:0]
:logndrop - [0:0]
:tobesortedout - [0:0]
-A INPUT -j blacklist 
-A OUTPUT -o lo -j ACCEPT 
-A OUTPUT -o eth0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 
-A OUTPUT -o eth0 -p tcp -m tcp --dport 80 -m owner --uid-owner 0 -j ACCEPT 
## ^^ apt-get {update,upgrade,install,remove,purge} # <-- deb http://
-A OUTPUT -o eth0 -p tcp -m tcp --dport 443 -m owner --uid-owner 0 -j ACCEPT 
## ^^ apt-get {update,upgrade,install,remove,purge} # <-- deb https://
-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner root -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only! If applicable? Then insert yours instead.
## E.g.: https://code.google.com/speed/public-dns/
-A OUTPUT -o eth0 -p tcp -m tcp -m owner --uid-owner 1000 -j ACCEPT
## ^^ Admin with sudo rights.
-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner 1000 -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only!
#-A OUTPUT -o eth0 -p tcp -m tcp -m owner --uid-owner 1001 -j ACCEPT 
## ^^ A simple daily user.
#-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner 1001 -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only!
#-A OUTPUT -o eth0 -p tcp -m tcp -m owner --uid-owner boinc -j ACCEPT 
#-A OUTPUT -o eth0 -p udp -m udp --dport 53 -m owner --uid-owner boinc -m iprange --dst-range 208.67.220.220-208.67.222.222 -j ACCEPT 
## ^^ Use opendns resolver only!
-A OUTPUT -p tcp -j REJECT --reject-with tcp-reset 
-A OUTPUT -p udp -j REJECT --reject-with icmp-port-unreachable 
# -A blacklist -s X.X.X.X/32 -j REJECT --reject-with icmp-host-prohibited 
# -A blacklist -s X.X.X.0/24 -j REJECT --reject-with icmp-net-prohibited 
-A blacklist -j icmp 
-A icmp -p icmp -m icmp --icmp-type 0 -j ACCEPT 
-A icmp -p icmp -m icmp --icmp-type 3 -j ACCEPT 
-A icmp -p icmp -m icmp --icmp-type 11 -j ACCEPT 
-A icmp -p icmp -m icmp --icmp-type 8 -m limit --limit 1/sec -j ACCEPT 
-A icmp -j tobesortedout 
-A logndrop -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied TCP: " --log-level 7 
-A logndrop -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied UDP: " --log-level 7 
-A logndrop -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ICMP: " --log-level 7 
-A logndrop -p tcp -j REJECT --reject-with tcp-reset 
-A logndrop -p udp -j REJECT --reject-with icmp-port-unreachable 
-A tobesortedout -i lo -j ACCEPT 
-A tobesortedout -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT 
#-A tobesortedout -i eth0 -p tcp -m tcp --dport (UpToYou) --tcp-flags FIN,SYN,RST,ACK SYN -m connlimit --connlimit-above 16 --connlimit-mask 24 -j REJECT --reject-with tcp-reset 
#-A tobesortedout -i eth0 -p tcp -m state --state NEW -m limit --limit 20/sec --limit-burst 20 -m tcp --dport (UpToYou) -j ACCEPT 
-A tobesortedout -j logndrop 
COMMIT
# Completed on Sat Nov 19 19:39:46 2011

How about ipv6? Of course, here you go!
Filename:

/etc/ip6tables.rules
# Generated by ip6tables-save v1.4.4 on Fri Oct  7 08:44:05 2011
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]
:logndropip6 - [0:0]
[0:0] -A INPUT -p tcp -j REJECT --reject-with tcp-reset 
[0:0] -A OUTPUT -j logndropip6 
[0:0] -A logndropip6 -p tcp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 TCP: " --log-level 7 
[0:0] -A logndropip6 -p udp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 UDP: " --log-level 7 
[0:0] -A logndropip6 -p icmp -m limit --limit 5/min -j LOG --log-prefix "Denied ipv6 ICMP: " --log-level 7 
[0:0] -A logndropip6 -p tcp -j REJECT --reject-with tcp-reset 
COMMIT
# Completed on Fri Oct  7 08:44:05 2011

Please note, there is no such thing as:

sudo service iptables

(iptables or better yet the netfilter module is an “add on” for the linux kernel and has nothing to do whatsoever with the startup of system services.)

“What the eyes see and the ears hear the mind believes…”

^^No doubt about that. Therefore a small video (sorry, no audio folks) of this script in action will be more explanatory!?

Or see the gallery below instead?


Is there any way to be 100% sure my computer will never be cracked into?

If you follow the instructions at the top of this page, you probably will not have your computer cracked. When you’re connected to the Internet, though, you are always vulnerable to security breaches of some kind. The only thing you can do is try to reduce your vulnerability. And I’ve read from a few security experts on the Ubuntu Forums that if someone is really determined to crack into your computer and capable, she pretty much will eventually it’s just a matter of time. The more obstacles you can put in the way of that happening, the more time it will take. Of course, disallowing remote logins is a big help.

What’s the most important part of OS security?
The user. It’s always the user. I’d rather have a smart user running as administrator on a Windows computer with no firewall, no anti-virus, and no antispyware than a dumb user running as limited user on a Ubuntu computer with a firewall, anti-virus, and a rootkit detector. Dumb users click on anything, somehow manage to install untrustworthy software even without administrative privileges, and use easy-to-guess passwords.

Grab that screen!

Updated today: Sunday, September 4, 2011
Reason: I’ve altered a few tidbits here and there in the script, with the result of providing a better picture/end result but at the cost of a slightly increased filesize. For example: an hour of footage, this depends on the amount of fast moving objects, is equivalent to say: 1GB, not bad when one considers a ‘ripped’ DVD with an approx bitrate of 1400kb/s to be of size: ~ 1.5GB. Fwiw I record my desktop in “HD ready” (1280×720) quality now. ;-)

Anyway!

There are times one wants to do a bit more than simply make a screenshot of one’s desktop. This is either to just prove a point or simply for the fun of it. Which can be done like so on afaik both windows and G(nu)/linux, Just press: (alt)+PrtSc and tada a picture of your desktop resides on your clipboard. Now in windows with the lack of a decent photo-editor (I’m not counting ‘paint’ here. :lol: ) or while you perhaps use a stripped down version of windows at work? One then simply opens up a word doc or if ‘paint’ is present open that instead. Hit ‘paste (ctrl+v), use the save as to give your ‘screenshot’ a name, that’s all there’s to it. ;-) Use it with ‘alt’ for the current window and on its own for the whole desktop.

But since I am not on windows. I instead work with a rather flexible system that comes with a lot of interesting {features,goodies} in its default state; such as ‘gnome-screenshot‘. Therefore, I can do the following.

For the current window:

gnome-screenshot -b -w -d 2 -e shadow

For a selected region:

gnome-screenshot --area

And probably a whole lot more: man gnome-screenshot

Post production of any shot made this way and if needed!? I do with the ‘Gimp

No offense intended towards the following program!!! gtk-recordMyDesktop because in a lot of ways it is far more advanced than what I am about to show ye! Especially when it concerns choosing a region to record. My dislike has more to do with the theora (video) codec than it has to do with the program!

Its alternative and hence the reason for this quick post is simply to grab one’s screen: Howto.

  • Advantages!? A much smaller file size than when using aforementioned program. Quick to set up as an ‘add to panel’ {app,script}. More choices in regards to the used codecs and the container one wants to wrap {his,her} clip in.
  • Disadvantage(s): No sound but that can easily be dubbed in after. Also the “mandatory post editing” out of any unwanted shots such as filling in sudo prompts or at the end where I’ve to close the calling terminal. But can fairly easy be ‘fixed’ by running ‘quote.sh‘ right after! ;-)

OK, so here is the script:
Scriptname: xgrabber.sh

#!/bin/bash
# Modified: Today by E.L.F.
#
## Licensed as:
## http://www.opensource.org/licenses/mit-license.php
#
## Script-name - xgrabber.sh
#
set -e
#. "$HOME"/.bash_functions
## http://ubuntuforums.org/tags.php?tag=recordmydesktop
## http://ubuntuforums.org/showthread.php?t=1392026 - How to screencast properly.
## https://wiki.ubuntu.com/PulseAudio
if [ "$USER" = root ];then echo -e "\tError: \""$USER"\" isn't allowed to use this script!";exit 0
else echo -e "\t${USER} may proceed.\n\tMay peace be with you.\n";fi
Color_Test=$(grep -i '\\033\[' "$HOME"/.bashrc)
if [ -n "$Color_Test" ];then echo -e ${Magenta}"\tOk, colors are defined."${Nc}
else
Black="\033[0;30m"
Red="\033[0;31m"
Green="\033[0;32m"
Yellow="\033[1;33m"
Blue="\033[1;34m"
Magenta="\033[1;35m"
Cyan="\033[1;36m"
White="\033[1;37m"
Nc="\033[0m" # No Color
echo -e ${White}"\tThey weren't, but now they are."${Nc}
fi
clear
## Monitor operates at 60hz.
echo -n "Enter name for output file: "
read Output
## The following line makes certain you can type a 'normal' sentence as filename.
## All this without 'violating' UNIX' restriction on spaces.
## I.e. 'This is my recording' becomes 'This.is.my.recording'
Output=$(echo "$Output" |sed -e 's_ _._g')
Output+=".mkv"
## Change to a foldername of your convenience.
WD=/my/folder/tmp
[ ! -d "$WD" ] && mkdir "$WD"
## Now you can press either 'minimize' or 'alt+f9' in my case
## To get the terminal out of your way.
## You have 2 seconds to do so.
sleep 2
## Adjust '-s 1366x716' to fit your purposes, same goes for this ':0.0+0,25'
ffmpeg -y -f alsa -ac 2 -i pulse -f x11grab -r 30 -s 1366x768 -i :0.0 \
-acodec pcm_s16le -alang eng \
-vcodec libx264 -vpre ultrafast -crf 18 -threads 0 -vlang eng \
-metadata title=$(basename "$Output" .mkv) \
-metadata artist="$USER" \
-metadata date="$(date +"%A, %B %-d, %Y")" \
-metadata publisher="$(echo "What is in a name anyway.")" \ # Change me.
-metadata copyright="$(echo "Attribution 3.0 Unported (CC BY 3.0)")" \ # Change me.
## '-s hd720' change this to suit your purposes.
-s hd720 "$WD"/"$OUTPUT"
exit 0

An example screen-recording (used the previous script that I had posted up here before.) can be seen here [Yes an 720p (HD ready) version is also available. :-) ]:

I have been fine-tuning my screen-recording capabilities, so be ready to get bored, quickly. ;-)
But at least now I know how to grab only the portion of the screen I want and provide you with a saner resolution. ;-)

An example with mpeg4 encoding. (21.1MB)

^^
Seems OK with me and is the one I used with this script.

An example with x264 encoding. (51.0MB)

^^
Smoother picture, but somewhat troublesome with faster moving pictures and larger than life filesize (approx 3GB for an whole hour!).

Enjoy and profit!?

PS: Time used aside from whatever it is you’re trying to record for pre and post production? No more then a few minutes of your time on a fairly modern computer. ;-)

Cat 1.mpg 2.mpg 3.mpg et al… > New.mpg

Updated today: Saturday, September 10, 2011
(Dear reader, you might want to take a look at the following post: http://wp.me/pNJrg-dM Why? Well I’ve got plans to add this one and many others to my “one script to rule them all” effort soon.)

Either:

cat 1.mpg 2.mpg 3.mpg et al... > New.mpg

Or:
If one were so inclined to do:

cat 1.vob 2.vob 3.vob et al... > New.vob

Anyway this post belongs to its master:
case-select-video-conversions/
Related post:
odd-sweet-and-still-elegant

By far the easiest way to join multiple *.mp(e)g files together is to merge them with a simple utility called cat. There is only one problem though. While playback of the new file will work (most of the times :lol: ) one will notice that the time index is off (Relating to the first file in the catenated series.) To overcome this problem: One uses in the next example an ever handy utility called: avidemux.

#!/bin/bash
# Modified: Today by E.l.f
#
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 2 of the License, or (at your option) any later
## version.
#
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
#
## You should have received a copy of the GNU General Public License along with
## this program; if not, write to the Free Software Foundation, Inc., 51
## Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
## http://www.gnu.org/copyleft/gpl.html
#
## Script-name - cat-mpg.sh
#
## Source (inspired on): http://ffmpeg.org/ffmpeg-doc.html
## And: http://ubuntuforums.org/showthread.php?t=1037517
## If colors are not defined in .bashrc, then uncomment the next three lines.
#YELLOW="\033[1;33m"
#RED="\033[0;31m"
#ENDCOLOR="\033[0m"
## Root check / Sanity check.  You decide.  >-)
## Just in case someone calls this script with sudo -s,
## or has cd'ed into his/her path.
if [ $USER = root ]; then
  echo -e $RED"Are you Insane!"
  echo -e $RED"Error: In order to use this script, one must NOT be $USER"
  echo -e $YELLOW"Exiting..."$ENDCOLOR
  exit 0
else
  echo ""
  echo "$USER may proceed."  
  echo "May peace be with you."  
fi
echo -n "Enter filename: "
read OUTPUT
OUTPUT=$OUTPUT
OUTPUT+=".mpg" # Append new extension
VAR="mpg-files.txt"
ls *.mp*g | sort > $VAR # Collect the files in the current directory
cat $VAR | while read line; do  # Loop read the filenames from the file
INPUT=$(echo ${line}) # Grab the nxt new filename
cat "$INPUT" >> "$OUTPUT"  # Append works.
done
\rm $VAR # Remove the text file with the file names
# \rm *.mp*g # Maybe later!?
exit 0

An updated version of the above mentioned script is available below:
Now it also handles ‘catenation’ of other file types. <– Changed a few bits here and there, enough to merit an “update”.

#!/bin/bash
# Modified: Today by E.l.f.
#
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 2 of the License, or (at your option) any later
## version.
#
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
#
## You should have received a copy of the GNU General Public License along with
## this program; if not, write to the Free Software Foundation, Inc., 51
## Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
## http://www.gnu.org/copyleft/gpl.html
#
## Script-name - cat.files.sh
#
## Source (inspired on): http://ffmpeg.org/ffmpeg-doc.html
## And: http://ubuntuforums.org/showthread.php?t=1037517
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"
if [ $USER = root ]; then
  echo -e $RED"   Are you Insane!"
  echo -e $CYAN"   Error: In order to use this script, one must NOT be $USER"
  echo -e $YELLOW"    Exiting..."$NC
  exit 0
else
  echo ""
  echo -e $BLUE"    $USER may proceed."
  echo -e $CYAN"    May peace be with you."$NC
fi
clear
echo "-------------------Catenate Options List-------------------"
echo
echo "    Please choose one of the following options:              "
echo "                              Or                             "
echo "    Hit Ctrl+c (^c) to stop now."
echo "    \"UPPER\", \"lower\" and \"Capitalized\" spelling "
echo "    are valid forms of input."
echo
echo "    Catenate [avi] files."
echo "    Catenate [mpg] files."
echo "    Catenate [wmv] files."
echo
echo "-------------------------------------------------------------"
echo ""
MINPARAMS=1
if [ $# -gt "$MINPARAMS" ]; then
  echo -e $YELLOW"This script only operates on"$NC" $BLUE"$MINPARAMS""$NC" "$YELLOW"file at a time!"$NC
  echo -e $BLUE"(Do)es your filename(s): "$YELLOW""$*""$NC". "$BLUE"Contain space(s)?"$NC
  echo -e $BLUE"If so, then you might want to rename {that,those} file(s)."$NC
  echo -e $BLUE"By replacing those spaces with {.,-,_}s. ; - )"$NC
  exit 0
fi
if [ "$1" = avi ];then Choice=avi;Choice=$Choice;fi
if [ "$1" = mpg ];then Choice=mpg;Choice=$Choice;fi
if [ "$1" = wmv ];then Choice=wmv;Choice=$Choice;fi
#read Choice
case "$Choice" in
    "Avi" | "AVI" | "avi")
    echo -n "Enter filename: "
    read OUTPUT
    OUTPUT=$OUTPUT
    OUTPUT+=".avi"
    ## Here have one to rule them all!
    # LS=$(ls *.{avi,mp{e,eg,g},wmv} 2>/dev/null)
    LS=$(ls *.avi 2>/dev/null)
    echo -e $BLUE"The elegance in this case referring only to this one short but sweet line..."$NC
    ## Why does the echo work as expected\?  *Continues on line 54*
    echo -e $CYAN"    mencoder -forceidx -oac copy -ovc copy "$LS" -o "$OUTPUT""$NC
    mencoder -forceidx -oac copy -ovc copy $(ls *.avi | sort -n) -o "$OUTPUT"
    ## Let's move the new file out of the way.
    mv "$OUTPUT" ../"$OUTPUT"
    ## Then we remove the files we've worked on.
    \rm *.avi
    ## Make it seem nothing happened. ; - )
    mv ../"$OUTPUT" .
    ls -lh
    cd ..
    exit 0
  ;;
    "Mpg" | "MPG" | "mpg")
    echo -n "Enter filename: "
    read OUTPUT
    OUTPUT=$OUTPUT
    OUTPUT+=".mpg" # Append new extension
    VAR="mpg-files.txt"
    ls *.mp{e,eg,g} 2>/dev/null | sort > $VAR # Collect the files in the current directory
    cat $VAR | while read line; do  # Loop read the filenames from the file
    INPUT=$(echo ${line}) # Grab the nxt new filename
    cat "$INPUT" >> "$OUTPUT"
    done
    \rm $VAR # Remove the text file with the file names
    ## Let's move the new file out of the way.
    mv "$OUTPUT" ../"$OUTPUT"
    ## Then we remove the files we've worked on.
    \rm *.mp{e,eg,g} 2>/dev/null
    ## Make it seem nothing happened. ; - )
    mv ../"$OUTPUT" .
#    sleep 2
#    ## Lets run repair right after shall we.
#    ls *.mp{e,eg,g,4} 2>/dev/null | sort > $VAR # Collect the files in the current directory
#    cat $VAR | while read line; do  # Loop read the filenames from the file
#    INPUT=$(echo ${line}) # Grab the nxt new filename
#    OUTPUT=${INPUT%.mp*} # Remove shortest match of characters between the '. ' and the '*' at end of string
#    OUTPUT+=".avi" # Append new extension
#    avidemux --nogui --rebuild-index --autoindex --force-alt-h264 --load "$INPUT" --save "$OUTPUT" --output-format AVI --quit
#    done
#    if [ -f "$VAR" ] ; then \rm $VAR;fi # Remove the text file with the file names
#    \rm *.mp{e,eg,g,4} 2>/dev/null
#    \rm *.idx 2>/dev/null # We don't need those indexes anymore.
    ls -lh
    cd ..
    exit 0
  ;;
    "Wmv" | "WMV" | "wmv")
    echo -n "Enter filename: "
    read OUTPUT
    OUTPUT=$OUTPUT
    OUTPUT+=".wmv"
    LS=$(ls *.wmv 2>/dev/null)
    echo -e $BLUE"The elegance in this case referring only to this one short but sweet line..."$NC
    ## Why does the echo work as expected\?  *Continues on line 54*
    echo -e $CYAN"    mencoder -forceidx -oac copy -ovc copy "$LS" -o "$OUTPUT""$NC
    mencoder -forceidx -oac copy -ovc copy $(ls *.wmv | sort -n) -o "$OUTPUT"
    ## Let's move the new file out of the way.
    mv "$OUTPUT" ../"$OUTPUT"
    ## Then we remove the files we've worked on.
    \rm *.wmv
    ## Make it seem nothing happened. ; - )
    mv ../"$OUTPUT" .
    ls -lh
    cd ..
    exit 0
  ;;
    *)
     # Default option.
     # Empty input (hitting RETURN) fits here, too.
     echo
     echo "Please choose a valid option."
     echo "\"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
     echo "Usage: wmv|flv|vob|avi|mpg"
     echo
  ;;
esac
exit 0

Mass editing text files too

The real reason why I bumped this post is for the following:

“Tor is written for and supported by people like you.”
“Tor jest pisany dla i wspierany przez ludzi takich, jak Ty.”
“Tor {is,wordt} geschreven voor en ondersteund door mensen zoals jou.”

Moet ik ‘m natuurlijk wel ‘up to date’ houden en niet na pas 2 maanden bijwerken. ;-)

http://tor-relay.thruhere.net/tor/

http://tor-relay.thruhere.net/tor/dist/

This post picks up where I left off in my last post.

Let’s start with this one:
Insert (arbitrary text) into the middle of some text file.

#!/bin/bash
## Modified: Today by E.l.f.
#
## Script-name - insert_html.sh
# -> Commented out command.
## -> My comments/explanation(s).
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"
if [ $USER = root ]; then
  echo -e $RED"   Are you Insane!"
  echo -e $CYAN"    Error: In order to use this script, one must NOT be $USER"
  echo -e $YELLOW"    Exiting..."$NC
  exit 0
else
  echo ""
  echo -e $BLUE"    $USER may proceed."$NC
  echo -e $CYAN"    May peace be with you."$NC
fi
clear # Clear the screen.
## Could be replaced with a for arg in something; do ...
echo -n "Enter filename: "
read INPUT
INPUT=$INPUT
## There's no need to type the extension after the filename.  ; - )
## Just let the script take care of that.
INPUT+=".html"
## Use your "grep.txt"\!
# e.g. grep -in \<div\ class=\"main-column\"\> *.html >> grep.txt
## That last command will output the exact line number where you wish to insert
## something else.
if [ ! -f "$INPUT" ]; then
  echo ""
  echo -e $RED"Error: File doesn't exist!"$NC
  echo -e $YELLOW"Exiting..."$NC
  echo ""
  exit 0
fi
## Yep, smilies still don't work well within 1 delimiters on wordpress.
## But be(a)ware of the single quote!!!  : - D : - D
## See:
# echo 'Why can'\''t I write '"'"'s between single quotes'
## As an example in why this is almost impossible.
## This particular widget uses ' quotes, hence my warning to you. ; - )
## Must be an exact match [^] (this includes spaces et all.)
## i for edit inplace and a for append.
# sed -i '/^searchForSomeString/a \
# Append sometext to it' YourFile.someExt
#
## Your mileage may vary and so does your text perhaps/possibly. ; - )
## And yes spaces (10 in this case) not tabs (\t), my tabs convert into two spaces while editing.
## Author's preference nothing more.
## FOUND!  : - D
sed -i '/^        <th colspan="3" align="center">Advanced Bash-Scripting Guide:<\/th>/a \
      <\/tr>\
      <tr>\
        <td>&nbsp;</td>\
        <td width="80%" align="center" valign="bottom">\
          <div id="google_translate_element"></div>\
          <script type="text/javascript">\
          //<![CDATA[\
          function googleTranslateElementInit() {\
          new google.translate.TranslateElement({\
            pageLanguage: "en",\
            includedLanguages: "af,sq,ar,hy,az,eu,be,bg,ca,zh-CN,zh-TW,hr,cs,da,nl,en,et,tl,fi,fr,gl,ka,de,el,ht,iw,hi,hu,is,id,ga,it,ja,ko,lv,lt,mk,ms,mt,no,fa,pl,pt,ro,ru,sr,sk,sl,es,sw,sv,th,tr,uk,ur,vi,cy,yi",\
            layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL\
          }, "google_translate_element");\
          }\
          //]]>\
          </script>\
          <script src=\
          "http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"\
          type="text/javascript">\
          </script>\
        </td>\
        <td>&nbsp;</td> ' "$INPUT"
exit 0

As the script used to be goes here (well at least a part of it):

# echo -n "Enter line-number here (e.g. 36, 41, 42): "
# read LINE
# LINE=$LINE
## Again choose carefully\!
# echo -n "Read the same file from line (usually this would be +1): "
# CNT=$(echo $(($LINE+1)))
## Just in case\!
# cp "$INPUT" "$INPUT".jic
# head --lines=$LINE "$INPUT" > head.html
# tail -n +$CNT "$INPUT" > tail.html
## The google.txt file is assumed to be in the WD,
## it could be any textfile you wish to insert though.
## Which in my case would be a simple translator's gadget.
## Adjust your spaces and tabulations (if applicable!?)
# cat google.txt >> head.html
# cat tail.html >> head.html
# \mv head.html "$INPUT"
# \rm tail.html

As you can see I’ve come a long way from just cutting up some piece of paper inserting some lines in and then gluing them back together (so to speak)! :lol: To me figuring out how one can indeed use sed to insert multiple lines, one must be weary of single ’s though. :lol: The top mentioned script features the google translate widget I meant to insert into a bunch of html files. An example can be viewed here. But this could be used for any purpose whatsoever, hence this publication. I must admit though that there (always) may be a quicker and dirtier way to do this? It still beats having to open an ‘n‘ amount of files and editing all this in manually :-o .

So now that is done with. On to mirroring tor.
Done!

How?
(Of if you prefer then go here.)
First we do:

rsync -av --delete rsync://rsync.torproject.org/tor tor-mirror/  ## I chose 'current' in this instance.

Then (Smallish update for today the 22nd of April.):

#cd into wd (working directory.
#Download the mirror.
rsync -av --delete rsync://rsync.torproject.org/tor tor-current/
cd tor-current
find -iname 'index.html' | wc -l ## None.
## thttpd sends these as 'plain/text'
find -iname 'index.html.en' | wc -l ## Just a few.
find -iname 'index.html.en' -exec ls -lh "{}" \; ## Where are they.
find -iname 'makefile' -exec ls -lh "{}" \; ## More of a necessity for the developer(s)
find -iname 'makefile' -exec \rm "{}" \; ## No need for those on a mirror.
find -iname 'makefile' -exec ls -lh "{}" \; ## Check.
find -iname 'en' -exec ls -lh "{}" \; ## These folders contain *.wml files.
find -iname 'en' -exec \rm -r "{}" \; ## -r because these are folders.
## Also removed any reference to the 'languageswitch' cgi script
## As well as any other shell script encountered.
history >> tor.s.history.txt ## Just to keep track of my own changes.  ; - )
## No need for GID but sticky? Yes.
find . -type d -exec chmod -s {} \; # Remove the setuid!
find . -type d -exec chmod 1755 {} \; # Folders are set to sticky.
## dist is gonna go on its own slice due to lack of space in /var/www.
# alias Bind='sudo mount -o bind' # /sourcefolderurl /destinationfolderurl
# ztar dist.tgz dist/ # alias ztar='tar cvzf ' # Name.tgz folder/
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
## In tor's wd.
## Please note that I consider it a safer approach to work in one directory at a time!
## This instead of:
# find -iname '*someName*' -exec someThing "{}" \;
cd about
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">@<a target="_blank" href="https://blog.torproject.org/blog/">@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">@<a target="_blank" href="http://printfection.com/torprojectstore">@' *.html
cd ../docs
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd ../donate
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd ../download
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd ../eff
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd ../getinvolved/
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd ../press
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd ../projects/
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd ../torbutton/
for i in *.html.en;do mv "$i" $(basename "$i" .html.en).html;done
sed -i 's@.html.en@.html@' *.html
sed -i 's@<h1 id="logo"><a href="../index.html">Tor</a></h1>@<h1 id="logo"><a target="_blank" href="https://www.torproject.org/">Tor</a></h1>@' *.html
sed -i 's@<li><a href="../index.html">Home</a></li>@<li><a href="../">Home</a></li>@' *.html
sed -i 's@<a href="https://blog.torproject.org/blog/">Blog</a>@<a target="_blank" href="https://blog.torproject.org/blog/">Blog</a>@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">Store</a>@<a target="_blank" href="http://printfection.com/torprojectstore">Store</a>@' *.html
cd..
#For all other foreign pages (repeated per directory):
#{ar,da,de,es,fa,fr,it,pl,ru}
for i in *.html.ar;do mv "$i" $(basename "$i" .html.ar).ar.html;done
for i in *.html.da;do mv "$i" $(basename "$i" .html.da).da.html;done
for i in *.html.de;do mv "$i" $(basename "$i" .html.de).de.html;done
for i in *.html.es;do mv "$i" $(basename "$i" .html.es).es.html;done
for i in *.html.fa;do mv "$i" $(basename "$i" .html.fa).fa.html;done
for i in *.html.fr;do mv "$i" $(basename "$i" .html.fr).fr.html;done
for i in *.html.it;do mv "$i" $(basename "$i" .html.it).it.html;done
for i in *.html.pl;do mv "$i" $(basename "$i" .html.pl).pl.html;done
for i in *.html.ru;do mv "$i" $(basename "$i" .html.ru).ru.html;done
# 2> /dev/null suppresses error messages about files being non existent and such clutter.
sed -i 's@.html.ar@.ar.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.da@.da.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.de@.de.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.es@.es.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.fa@.fa.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.fr@.fr.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.it@.it.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.pl@.pl.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.ru@.ru.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@.html.en@.html@' *.{ar,da,de,es,fa,fr,it,pl,ru}.html 2> /dev/null
sed -i 's@<a href="https://blog.torproject.org/blog/">@<a target="_blank" href="https://blog.torproject.org/blog/">@' *.html
sed -i 's@<a href="http://printfection.com/torprojectstore">@<a target="_blank" href="http://printfection.com/torprojectstore">@' *.html
# Oops, I forgot to update the English only pages! *hint do the English pages first!*
sed -i 's@.html.ar@.ar.html@' *.html 2> /dev/null
sed -i 's@.html.da@.da.html@' *.html 2> /dev/null
sed -i 's@.html.de@.de.html@' *.html 2> /dev/null
sed -i 's@.html.es@.es.html@' *.html 2> /dev/null
sed -i 's@.html.fa@.fa.html@' *.html 2> /dev/null
sed -i 's@.html.fr@.fr.html@' *.html 2> /dev/null
sed -i 's@.html.it@.it.html@' *.html 2> /dev/null
sed -i 's@.html.pl@.pl.html@' *.html 2> /dev/null
sed -i 's@.html.ru@.ru.html@' *.html 2> /dev/null

All in all I didn't adjust this mirror in the intended 15 minutes as can be read in the link below.
This is due mainly because this version features a lot of translations of which it is noteworthy to see a lot of them to be in Polish.
ofchmod # alias for chmod 644 all files.
find -iname '*.html' -exec sed -i 's@<title>Tor@<title>Please note that you'\''re viewing a local mirror - Tor@' "{}" \;

tidyup.sh  ## See my previous post about mass editing text.

http://bohemian0wildebeest.wordpress.com/2011/01/22/mass-editing-text-files-too/

The code looks daunting, doesn’t it? It really isn’t! ;-) If I subtract the amount of time necessary to figure things out (which IS the larger part and we don’t like to repeat ourselves!), this basically could be done in less than 10 minutes (minus the download time for rsync of course.) Basically I tracked my own progress while editing, which IS the smarter thing to do. Because next time I don’t have to do the figure it out again part, which I didn’t do last time. ;-)

Until next time,

Alex

Odd, sweet and still elegant.

In case you were wondering? This post is part of a series of which its master can be found here.

As I was wondering how ‘catenating’ avi files would/should work, I stumbled upon this short but elegant solution. *SWEET*

avimerge -o Name-of-your-choosing.avi -i $(ls)

In case the directory you work in contains several file types.

avimerge -o Name-of-your-choosing.avi -i $(ls *.avi)

When the ordering of said files is odd at best!?

avimerge -o Name-of-your-choosing.avi -i $(ls *.avi | sort -n)

Only problem with this setup is, that if you want to ‘automate’ this process, avimerge keeps spewing errors at me?? However mencoder will work when used and needed as a ‘batch converter’ of sorts. ;-)

mencoder -forceidx -oac copy -ovc copy $(ls) -o "$OUPUT"

In case the directory you work in contains several file types.

mencoder -forceidx -oac copy -ovc copy $(ls *.avi) -o "$OUPUT"

When the ordering of said files is odd at best!?

mencoder -forceidx -oac copy -ovc copy $(ls *.avi | sort -n) -o "$OUTPUT"

So here is an enhanced script which from now on also process(es) *.wmv and mp{e,eg,g,4} file(s) for you.
Edited on: 10092011@11:15GMT)

## Invoke as: ./cat.files.sh $ARG
## Where $ARG is one of the following three.
# avi, mpg or wmv
## Thus (in my case):
# cat.files.sh avi
## Will catenate all the avi files it finds in the current working directory.
## However:
# cat.files.sh avi wmv
## Will fail, because the script only accepts one argument passed to it.
## That's on purpose!
## But feel free to edit at will.

Scriptname: cat.files.sh :

#!/bin/bash
# Modified: Today by E.l.f.
#
## This program is free software; you can redistribute it and/or modify it under
## the terms of the GNU General Public License as published by the Free Software
## Foundation; either version 2 of the License, or (at your option) any later
## version.
#
## This program is distributed in the hope that it will be useful, but WITHOUT
## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
## FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
## details.
#
## You should have received a copy of the GNU General Public License along with
## this program; if not, write to the Free Software Foundation, Inc., 51
## Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
## http://www.gnu.org/copyleft/gpl.html
#
## Script-name - cat.files.sh
#
## Source (inspired on): http://ffmpeg.org/ffmpeg-doc.html
## And: http://ubuntuforums.org/showthread.php?t=1037517
RED="\033[0;31m"
BLUE="\033[1;34m"
CYAN="\033[1;36m"
YELLOW="\033[1;33m"
NC="\033[0m"
if [ $USER = root ]; then
  echo -e $RED"   Are you Insane!"
  echo -e $CYAN"   Error: In order to use this script, one must NOT be $USER"
  echo -e $YELLOW"    Exiting..."$NC
  exit 0
else
  echo ""
  echo -e $BLUE"    $USER may proceed."
  echo -e $CYAN"    May peace be with you."$NC
fi
clear
echo "-------------------Catenate Options List-------------------"
echo
echo "    Please choose one of the following options:              "
echo "                              Or                             "
echo "    Hit Ctrl+c (^c) to stop now."
echo "    \"UPPER\", \"lower\" and \"Capitalized\" spelling "
echo "    are valid forms of input."
echo
echo "    Catenate [avi] files."
echo "    Catenate [mpg] files."
echo "    Catenate [wmv] files."
echo
echo "-------------------------------------------------------------"
echo ""
MINPARAMS=1
if [ $# -gt "$MINPARAMS" ]; then
  echo -e $YELLOW"This script only operates on"$NC" $BLUE"$MINPARAMS""$NC" "$YELLOW"argument at a time!"$NC
  exit 0
fi
if [ "$1" = avi ];then Choice=avi;Choice=$Choice;fi
if [ "$1" = mpg ];then Choice=mpg;Choice=$Choice;fi
if [ "$1" = wmv ];then Choice=wmv;Choice=$Choice;fi
#read Choice
case "$Choice" in
    "Avi" | "AVI" | "avi")
    echo -n "Enter filename: "
    read OUTPUT
    OUTPUT=$OUTPUT
    OUTPUT+=".avi"
    ## Here have one to rule them all!
    # LS=$(ls *.{avi,mp{e,eg,g},wmv} 2>/dev/null)
    LS=$(ls *.avi 2>/dev/null)
    echo -e $BLUE"The elegance in this case referring only to this one short but sweet line..."$NC
    ## Why does the echo work as expected\?  *Continues on line 54*
    echo -e $CYAN"    mencoder -forceidx -oac copy -ovc copy "$LS" -o "$OUTPUT""$NC
    mencoder -forceidx -oac copy -ovc copy $(ls *.avi | sort -n) -o "$OUTPUT"
    ## Let's move the new file out of the way.
    mv "$OUTPUT" ../"$OUTPUT"
    ## Then we remove the files we've worked on.
    \rm *.avi
    ## Make it seem nothing happened. ; - )
    mv ../"$OUTPUT" .
    ls -lh
    cd ..
    exit 0
  ;;
    "Mpg" | "MPG" | "mpg")
    echo -n "Enter filename: "
    read OUTPUT
    OUTPUT=$OUTPUT
    OUTPUT+=".mpg" # Append new extension
    VAR="mpg-files.txt"
    ls *.mp{e,eg,g} 2>/dev/null | sort > $VAR # Collect the files in the current directory
    cat $VAR | while read line; do  # Loop read the filenames from the file
    INPUT=$(echo ${line}) # Grab the nxt new filename
    cat "$INPUT" >> "$OUTPUT"
    done
    \rm $VAR # Remove the text file with the file names
    ## Let's move the new file out of the way.
    mv "$OUTPUT" ../"$OUTPUT"
    ## Then we remove the files we've worked on.
    \rm *.mp{e,eg,g} 2>/dev/null
    ## Make it seem nothing happened. ; - )
    mv ../"$OUTPUT" .
#    sleep 2
#    ## Lets run repair right after shall we.
#    ls *.mp{e,eg,g,4} 2>/dev/null | sort > $VAR # Collect the files in the current directory
#    cat $VAR | while read line; do  # Loop read the filenames from the file
#    INPUT=$(echo ${line}) # Grab the nxt new filename
#    OUTPUT=${INPUT%.mp*} # Remove shortest match of characters between the '. ' and the '*' at end of string
#    OUTPUT+=".avi" # Append new extension
#    avidemux --nogui --rebuild-index --autoindex --force-alt-h264 --load "$INPUT" --save "$OUTPUT" --output-format AVI --quit
#    done
#    if [ -f "$VAR" ] ; then \rm $VAR;fi # Remove the text file with the file names
#    \rm *.mp{e,eg,g,4} 2>/dev/null
#    \rm *.idx 2>/dev/null # We don't need those indexes anymore.
    ls -lh
    cd ..
    exit 0
  ;;
    "Wmv" | "WMV" | "wmv")
    echo -n "Enter filename: "
    read OUTPUT
    OUTPUT=$OUTPUT
    OUTPUT+=".wmv"
    LS=$(ls *.wmv 2>/dev/null)
    echo -e $BLUE"The elegance in this case referring only to this one short but sweet line..."$NC
    ## Why does the echo work as expected\?  *Continues on line 54*
    echo -e $CYAN"    mencoder -forceidx -oac copy -ovc copy "$LS" -o "$OUTPUT""$NC
    mencoder -forceidx -oac copy -ovc copy $(ls *.wmv | sort -n) -o "$OUTPUT"
    ## Let's move the new file out of the way.
    mv "$OUTPUT" ../"$OUTPUT"
    ## Then we remove the files we've worked on.
    \rm *.wmv
    ## Make it seem nothing happened. ; - )
    mv ../"$OUTPUT" .
    ls -lh
    cd ..
    exit 0
  ;;
    *)
     # Default option.
     # Empty input (hitting RETURN) fits here, too.
     echo
     echo "Please choose a valid option."
     echo "\"UPPER\", \"lower\" and \"Capitalized\" spelling are supported"
     echo "Usage: wmv|flv|vob|avi|mpg"
     echo
  ;;
esac
exit 0

Enjoy! You scriptkiddies, you… :-D