Showing posts with label Shell script. Show all posts
Showing posts with label Shell script. Show all posts

07 January, 2015

How to create a file extension association with the program in Windows

Assume that you have a program named "table-explorer.exe".
And you want to open all ".csv" and ".sas7bdat" files using  this program by default in Windows.

First you need to create a file extension association with the program via these commands:


reg add HKCU\SOFTWARE\Classes\.csv /d "table-explorer" /f
reg add HKCU\SOFTWARE\Classes\.sas7bdat /d "table-explorer" /f


And then register the application:


reg add HKCU\SOFTWARE\Classes\table-explorer\shell\open\command /d "\"C:\Path\to\table-explorer.exe\"" /f

06 January, 2013

Merge log files from multiple servers

If you have some similar servers (e.g. balanced EC2-instances) and need to analyze log files from them - it is possible to automatize downloading and merging all these files via shell script like this:

#!/bin/bash

LOG_DIR=log-`date +%Y.%m.%d_%H.%M.%S`

mkdir -p $LOG_DIR

scp -C ec2-user@node1.server.com:/log/file.log $LOG_DIR/file1.log
scp -C ec2-user@node2.server.com:/log/file.log $LOG_DIR/file2.log
scp -C ec2-user@node3.server.com:/log/file.log $LOG_DIR/file3.log

cat $LOG_DIR/*.log | sort >$LOG_DIR/files.log


Also it is a good idea to use ssh-agent to keep private keys.

02 April, 2012

Resize and rotate video

From large iPhone's 1080x1920 to compact 640x360 size:

ffmpeg.exe -i SOURCE.MOV -vf "transpose=1,scale=360:640" TARGET.MOV

14 August, 2009

Make local FreeBSD mirror via rsync

rsync -va --delete --progress ftp.nl.FreeBSD.org::FreeBSD/ports/i386/packages-7.2-release/ FreeBSD-7.2-i386

24 October, 2008

Eclipse icons

How to extract icons from Eclipse


I've created it in few steps:

  1. Downloaded and unzipped eclipse

  2. Extracted all images from eclipse directories, subdirectories, zips and jars*

  3. Filtered only unique files*

  4. Sorted images by dimension (16x16, 24x24, 32x32, etc.)*

  5. Removed large images (that not look like icon)

  6. Created html pages (via PHP script)

* Via my shell scripts.

This is one script from this project:
#!/bin/bash

#Find and copy only unique files (with same size and checksums) from $SOURCE directory to $OUTPUT.

SOURCE=output
OUTPUT=images

rm -rf $OUTPUT
mkdir -p $OUTPUT

uniqProcess() {

echo >xqx_unique.idx
while read; do
echo -ne \\r$REPLY
echo $REPLY $(stat -c%s $REPLY)+$(md5sum $REPLY|cut -f 1 -d ' ')+$(cksum $REPLY|cut -f 1 -d ' ')>>xqx_unique.idx
done
sort -k 2 xqx_unique.idx|uniq -f 1|cut -f 1 -d ' '|xargs -I '{}' cp '{}' $OUTPUT
}

find $SOURCE -type f |uniqProcess

18 September, 2008

PHP - exec output

This is the simple way how to capture exec output:
<?php

function execOutput($command) {
$output = array($command);
exec($command.' 2>&1', $output);
return implode("\n", $output);
}

echo execOutput('help');
?>

01 September, 2008

Access logging under Tomcat

Do you want to get "access.log" file under Apache Tomcat Server as well as under Apache HTTP Server? Like this:
192.168.1.1 - - [25/Aug/2008:15:08:11 +0400] "GET / HTTP/1.1" 200 82777
192.168.1.1 - - [25/Aug/2008:15:08:11 +0400] "GET /js/event-debug.js HTTP/1.1" 200 88582
192.168.1.1 - - [25/Aug/2008:15:08:11 +0400] "GET /js/history-debug.js HTTP/1.1" 200 28540
192.168.1.1 - - [25/Aug/2008:15:08:11 +0400] "GET /js/prototype.js HTTP/1.1" 200 126120
192.168.1.1 - - [25/Aug/2008:15:08:11 +0400] "GET /js/json2.js HTTP/1.1" 200 9490
192.168.1.1 - - [25/Aug/2008:15:08:12 +0400] "GET /css/app.css HTTP/1.1" 200 1937

Just insert one line into the "Engine" section of the "server.xml" file:
<Engine name="Catalina" defaultHost="localhost">
...
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="access." suffix=".log" pattern="common"/>
...
</Engine>


Also it is possible to collect and filter the set of raised files via this script:


access.sh
#!/bin/bash

cat access.log | cut -f2 -d"\"" access.log | cut -f2 -d" " | egrep -v -f ignore.txt | sort



ignore.txt
^/$
^/JSON-RPC$
^/JSON-RPC-GET\?
//Any other patterns

HowTo run IntelliJ IDEA from the RAM-Drive under Linux

Sometimes people need to run IntelliJ IDEA at "readonly" systems.
"Readonly" I mean - without unpacking IDEA into the local file system.

These scripts will help extract and start IDEA from the RAM-Drive and remove it after using:


idea-setup.sh
#!/bin/bash

IDEA_TAR_GZ=~/downloads/idea-7.0.3.tar.gz
IDEA_HOME=~/idea/idea
export JDK_HOME=/usr/lib/jvm/java-6-sun
export REQUIRED_JVM_ARGS="-Didea.system.path=$IDEA_HOME/system -Didea.config.path=$IDEA_HOME/config"

mkdir $IDEA_HOME

sudo mount -t ramfs none $IDEA_HOME
tar -xz --strip 1 --file $IDEA_TAR_GZ -C $IDEA_HOME

$IDEA_HOME/bin/idea.sh

./idea-clean.sh



idea-clean.sh
#!/bin/bash

IDEA_HOME=~/idea/idea

sudo umount $IDEA_HOME
rm -rf $IDEA_HOME

Of course you should buy IntelliJ IDEA license, get open source license or... use evaluation version.

22 August, 2008

HowTo find inconsistency between image format and file extension

Sometimes image files have inconsistency between format and extension.
For example: .jpeg file saved as .png file.

I wrote simple script in order to find such files:
#!/bin/bash

process() {
while read; do
diff=`identify -format "%m %e" "$REPLY" | tr [A-Z] [a-z] | egrep -v "^(png png|gif gif|jpg jpg|jpeg jpg|jpeg jpeg)"`
test -n "$diff" && echo $diff $REPLY
done
}

find -type f -iregex ".*\.\(png\|gif\|jpg\|jpeg\)$" | process

It outputs information about real file format, file extension and filename in case of
difference between format and extension.
Like this:

jpeg png images/rating_0.png
png gif images/left.gif
gif png images/border_tr.png

15 June, 2008

HowTo batch remove temporaty files from directory and subdirectories

Just create .bat file with this content:

@set path=
@for /R %%i in (*.tmp *.bak) do @del %%i


and update (*.tmp *.bak) section with your set of files or masks.

27 April, 2008

HowTo simulate Googlebot

Googlebot is Google's web crawling robot, which finds and retrieves pages on the web and hands them off to the Google indexer.
Googlebot visits sites with special value in his HTTP request header.

It uses special user-agent string:
"Mozilla/5.0 (compatible; Googlebot/2.1; http://www.google.com/bot.html)"

It is possible to simulate Googlebot from the shell script via wget program.

Like this:

#!/bin/bash

TEST_URL="http://digg.com/"

FIREFOX_USERAGENT_STRING="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"
GOOGLEBOT_USERAGENT_STRING="Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"

#get page for firefox browser
wget -c --user-agent="$FIREFOX_USERAGENT_STRING" --output-document=firefox.html "$TEST_URL"

#get page for google bot
wget -c --user-agent="$GOOGLEBOT_USERAGENT_STRING" --output-document=googlebot.html "$TEST_URL"


This script may be useful for testing of site's search engine optimization.

...May the Force be with you...

22 January, 2008

StarCraft (Brood War) under Linux (Wine)

I use this script to play network StarCraft under wine:

#!/bin/bash

#At first, run "wine setup.exe"

BROODWAR_HOME=/usr/games/broodwar

ipx_interface add -p eth0 802.2 0x39ab0222
cd $BROODWAR_HOME
xinit /usr/bin/wine starcraft.exe


I think it is the best game.

Flash-light from console

With this script I use my monitor as flash-light in the darkness.

#!/bin/bash

#Switch monitor (CRT or LCD) to flash-light mode.

echo -e "\\033[47;30m"
clear
read
echo -e "\\033[0m"
clear

22 November, 2007

HowTo batch replace string in the set of files

This script replaces all occurrences of 'oldString' with 'newString' in all files in the current directory and all subdirectories.



xqx_replace.sh

#!/bin/bash

if test -z "$1" -o -z "$2"; then
echo Replace all occurrences of 'oldString' with 'newString' in all files in the current directory and all subdirectories.
echo Usage: $0 oldSting newString
exit
fi

OLDSTRING=$1
NEWSTRING=$2

replace() {
echo "$1"
mv "$1" "$1".bak
sed s/$OLDSTRING/$NEWSTRING/g "$1".bak >"$1"
}

check() {
while read; do
if test -n "`grep -l $OLDSTRING \"$REPLY\"`"; then
replace "$REPLY"
fi
done
}

find . -type f |check

31 October, 2007

HowTo create LDAP users

LDAP (Lightweight Directory Access Protocol) - not lightweight for my brain.

After some research I found steps how to store users in the LDAP (OpenLDAP server) under Windows.


  1. Change configuration file

    slapd.conf

    ucdata-path ./ucdata
    include ./schema/core.schema
    include ./schema/cosine.schema
    include ./schema/inetorgperson.schema
    include ./schema/misc.schema
    include ./schema/nis.schema
    include ./schema/openldap.schema


    pidfile ./run/slapd.pid
    argsfile ./run/slapd.args

    access to *
    by self write
    by users read
    by anonymous read

    #######################################################################
    # BDB database definitions
    #######################################################################

    database bdb
    suffix "o=sample company"
    rootdn "cn=Manager,o=sample company"
    rootpw secret
    directory ./data
    index objectClass eq

  2. Restart LDAP service

    restart.bat

    net stop OpenLDAP-slapd
    net start OpenLDAP-slapd

  3. Create base record

    base.ldif

    dn: o=sample company
    objectclass: organization
    objectclass: top
    o: sample company

  4. Insert base record into LDAP

    base.bat

    @echo off
    set LDAP_HOME=E:\devenv\tools\OpenLDAP
    set BASE="o=sample company"
    set D=cn=Manager,%BASE%
    set AUTH=-x -w secret -D %D%

    %LDAP_HOME%\ldapadd.exe %AUTH% -a -f base.ldif

  5. Create file with users' definitions

    user.ldif

    dn: cn=Katrien,o=sample company
    objectClass: top
    objectClass: person
    objectClass: inetorgperson
    cn: Katrien
    sn: none
    userPassword: none
    mail: katrien@samplecompany.com

    dn: cn=Gordon,o=sample company
    objectClass: top
    objectClass: person
    objectClass: inetorgperson
    cn: Gordon
    sn: none
    userPassword: none
    mail: Gordon@samplecompany.com

  6. Insert users into LDAP

    user.bat

    @echo off
    set LDAP_HOME=E:\devenv\tools\OpenLDAP
    set BASE="o=sample company"
    set D=cn=Manager,%BASE%
    set AUTH=-x -w secret -D %D%

    %LDAP_HOME%\ldapadd.exe %AUTH% -a -f user.ldif

  7. Check LDAP records

    search.bat

    @echo off
    set LDAP_HOME=E:\devenv\tools\OpenLDAP
    set BASE="o=sample company"
    set D=cn=Manager,%BASE%
    set AUTH=-x -w secret -D %D%

    %LDAP_HOME%\ldapsearch.exe -LLL %AUTH% -b %BASE% "objectClass=person"

30 October, 2007

MySQL shell scripting

MySQL is the best. The best database server. I love it.
I like and appreciate its simplicity, efficiency, small size, good help, cool shell utilities. And its price :-)

I've worked with MySQL many years. And I can't understand some another database systems like Oracle, that big, heavy and high-priced. I can't stand theirs complexity.



You can use this server as you want. You can embed it into your application.
MySQL also pretty good in the console.

You can execute sql script from file e.g.:

data.sql

insert into Sample (name, address) values ('sample name', 'sample address');



with the simple command:

exec.cmd

@echo off
SET DATABASE_HOST=localhost
SET DATABASE_NAME=db
SET DATABASE_USER=root
SET DATABASE_PASSWORD=********

mysql -h %DATABASE_HOST% -u %DATABASE_USER% -p%DATABASE_PASSWORD% -e "source data.sql" %DATABASE_NAME%


and dump data from database with this command:

dump.cmd

@echo off
SET DATABASE_HOST=localhost
SET DATABASE_NAME=db
SET DATABASE_USER=root
SET DATABASE_PASSWORD=********

md tables
mysqldump --compact --no-create-info --tab=tables -h %DATABASE_HOST% -u %DATABASE_USER% -p%DATABASE_PASSWORD% %DATABASE_NAME%


For these purposes you should have only 2 files from mysql: mysql.exe and mysqldump.exe

11 September, 2007

HTML Encoder

I've released new online service: HTML Encoder
It replaces ampersands, tabs, less/greater braces and prepares source code for posting into blog.

If you prefer shell scripts, you may use this:

sed -e 's/\x26/\&amp;/g;s/\x3c/\&lt;/g;s/\x3e/\&gt;/g' sourcefile.txt | expand -t 4 >sourcefile.blog


See this project on GitHub

20 August, 2007

HowTo disable speaker in the Linux terminal

Speaker in the linux console is very tiresome.
I know way how to disable system speaker.
  1. Insert line:

    set bell-style none

    to the file .input.rc

  2. Execute command:

    setterm -blength 0
    or
    setterm -bfreq 0
    or
    echo -ne '\033[11;0]'


Enjoy :-).

14 August, 2007

HowTo check files integrity via shell script

In order to control integrity of files on my fileserver I've created special script.
It walks around filesystem (in the given directory) and calculates checksums for files or checks their.
If the file has been changed after last check the warning message will be displayed.



Script:


xqx_uintegra.sh

#!/bin/bash

#Checks files integrity via md5sum utility.
#
#For removal of all *.md5 files, execute: find -name "*.md5" -exec rm {} \;
#Usage:
# xqx_uintegra.sh "/path/to/directory"


DATE=`date +%Y.%m.%d_%H.%M.%S.%N`
LOG=~/`basename $0`-$DATE.log
touch $LOG

if test ! -w "$LOG"; then
LOG=/dev/stdout
fi

SHIFT=$[`tput cols`-10]
MOVE="\\033["$SHIFT"G"
DEFAULT="\\033[0;39m"
RED="\\033[1;31m"
GREEN="\\033[1;32m"
YELLOW="\\033[1;33m"
BLUE="\\033[1;34m"

logError_end() {
echo -e "$MOVE$RED$1$DEFAULT"
echo -e \\t$1 >>$LOG
}

logOk_end() {
echo -e "$MOVE$GREEN$1$DEFAULT"
echo -e \\t$1 >>$LOG
}

logWarning_end() {
echo -e "$MOVE$YELLOW$1$DEFAULT"
echo -e \\t$1 >>$LOG
}

checkSum() {
#$1=file
echo -en CheckSum:\\t$1
echo -en CheckSum:\\t$1 >>$LOG
file=`basename $1`
dir=`dirname $1`
(cd $dir && md5sum -c -- $file >/dev/null 2>&1 && logOk_end OK || logError_end ERROR)
}

calcSum() {
#$1=file
echo -en CalcSum:\\t$1
echo -en CalcSum:\\t$1 >>$LOG
file=`basename $1`
dir=`dirname $1`
(cd $dir && md5sum -b -- $file >$file.md5 2>/dev/null && logWarning_end CALCULATED || logError_end ERROR)
}


fin_process() {
while read; do
#echo $REPLY
if test -n "`echo $REPLY | grep '\.md5$'`"; then
checkSum $REPLY
else
if test ! -f "$REPLY.md5"; then
calcSum $REPLY
fi
fi
done
}


find $1 -type f | fin_process;
echo
echo -e "\\033[1;31m"
cat $LOG |grep ERROR
echo -e "\\033[0;39m"


This script works in Linux systems and under Cygwin environment.

Examples of usages:
In the Windows+Cygwin:
bash xqx_uintegra.sh E:/Temp/sun

In the Linux:
xqx_uintegra.sh /home/fileserver

13 August, 2007

HowTo understand Vi ( Vim ) editor

"Vim (Vi Improved) is very powerful editor..."
It is true, I know, I like it. Vi is the best editor for the Linux/Unix console.

Have you tried to understand Vi?

Most people don't understand Vi, because they don't like console and command line, it is needlessly for theirs.
Vi is good for servers, embedded and non-GUI systems;
for admins, linux developers and gurus,
but not for normal people, at first look.

You may execute vimtutor in your command line in order to understand Vi.
Vimtutor is great tutorial.

Also Vi supports highlighting for many types of files.


I've created consolidated list of Vi commands and hot keys:

Navigation
h move cursor left
j move cursor down
k move cursor up
l move cursor right
i, INSERT edit mode
R replace mode
ESC normal mode
CTRL-g show filename, current location in the file and status
SHIFT-g goto the end of file
number+SHIFT-g goto to the line number
% goto the matching pair for brackets [, ], {, }, (, )
:syntax on switch text highlight on
:help command help for the command

Search
/ search text
n search text again
? search in the backward direction
SHIFT-N search text again in opposite direction
:set ic search ignore cases

Edit
x delete character under cursor
de delete to the end of word
dw delete to the end of word+space
d$ delete to the end of line
d^ delete to the begin of line
dd delete a whole line

ce,w,$,^ do the same as delete command, but also switch to edit mode

u undo the last command
U restore line to it's original state
CTRL-R redo the last command

p put the last deletion after the cursor
o,O open new empty line below/above the cursor and switch to the edit mode
a append text after the cursor
A append text to the end of a line


Replace
r+character replace character under cursor
:s/old/new replace old text with new text (once)
:s/old/new/g replace all old text with new text in the line
:s/old/new/gc replace all old text with new text in the line, but ask to confirmation
:%s/old/new/g replace all old text with new text in the file
:#,#s/old/new/g replace all old text with new text between lines in the range #,#

Common
number+command repeat command number of times (e.g.: 2dd deletes two lines, 5j moves five lines down)


File
:q! exit without changes
:w save file
:wq save and exit
:w filename save file as filename
:#,# w filename save part of file between lines in the range #,#
:r filename insert the contents of the file
:!command execute external command

This article is created in Vi!

There are some programs which syntax is partially compatible with Vi: ed, sed (stream editor) and others.
E.g.:
command cat file.txt |sed -e '1,10s/a/A/g' replaces all 'a' with 'A' from 1 to 10 line.