Use your shell as calculator

Submitted by Swobodin on Mon, 2006-08-21 11:51. ::
You may sometimes need to calculate a more or less complex mathematic formula and include it within a script.
There are many tools in the shell that allow you to proceed without having difficulties to calculate numbers.
You can use bc in interactive or non-interactive mode.
and you will have the command prompt.
Construction must be like the following:
For example:
Type
and you have a command prompt
For non-interactive mode, you can use pipe method
There are many tools in the shell that allow you to proceed without having difficulties to calculate numbers.
bc
bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming language.You can use bc in interactive or non-interactive mode.
Interactive
Typebc
and you will have the command prompt.
5+9
14
sqrt(25)
5
myvar=8
myvar
8
myvar++
8
myvar
9
quit
Non-interactive
You can include your bc result in shellMYVAR=$(echo "9+6" | bc)
echo $MYVAR
15
Bash
Bash allows you to make some simple operations using special expression.Construction must be like the following:
$[ a+b ]
For example:
MYVAR=$(printf %.2f $[ 8/5 ])
echo $MYVAR
Python
Python in interactive is a powerful scientific calculator!Type
python
and you have a command prompt
>>> import math
>>> 1+1
2
>>> math.cos(1)
0.54030230586813977
>>> math.pi
3.1415926535897931
>>> math.sqrt(625)
25.0
For non-interactive mode, you can use pipe method
echo "import math; print math.tan(1)" | python
1.55740772465
Setting Apache fake files/directories using mod_rewrite

Submitted by Swobodin on Mon, 2006-08-07 09:50. ::
Ever wondered how does Wikipedia use "static" pages (for example: http://en.wikipedia.org/wiki/Linux) whereas it's almost impossible to stock all the files in wiki directory?
The wikimedia platform uses mod_rewrite Apache module which allow to rewrite requested URLs on the fly.
Based on a regular expressions parser, mod_rewrite has complex yet flexible features, which allow you to manipulate the URL. You should have a basic knowledge of regular expressions.
First, configure your httpd.conf to both loading the module and allowing using .htaccess file.
Restart your Apache server
Suppose the directory is you are working on is /home/swobodin/www/Lab/rewrite
Let's start with a simple redirection
Create a HTML file called new.html and edit your .htaccess
RewriteCond sets a condition, %{REQUEST_FILENAME} is an Apache variable meaning (not too difficult to figure out) the requested file.
Any requested file that ends with html and is not a file (-f) neither a directory (-d) will be redirected to the file new.html. The L flag is like Perl's "last" or C "break", means no other rules can be added if a condition is set before.
If we had to translate the lines above to PHP, it would be like the following;
Now, point your browser to http://127.0.0.1/~swobodin/www/Lab/rewrite/anyfile.html
The URL doesn't change, but the content is new.html !
Let's make the operation more useful. Suppose we have req.php that accepts both id and item GET variables.
It should be like the following:
From:
http://127.0.0.1/~swobodin/www/Lab/rewrite/req.php?id=50&item=80
to
http://127.0.0.1/~swobodin/www/Lab/rewrite/50/80/
Edit .htaccess and set the following commands:
We want to have the following URL
http://127.0.0.1/~swobodin/www/Lab/rewrite/entry/145
so that it displays: "Entry number 145"
Create a PHP file called "entry" without suffix.
This was only an overview about the module. For further information, you may consult http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
The wikimedia platform uses mod_rewrite Apache module which allow to rewrite requested URLs on the fly.
Based on a regular expressions parser, mod_rewrite has complex yet flexible features, which allow you to manipulate the URL. You should have a basic knowledge of regular expressions.
First, configure your httpd.conf to both loading the module and allowing using .htaccess file.
# Loading module
LoadModule rewrite_module modules/mod_rewrite.so
# Allowing user_dir, change the default if any
# Comment this!
#UserDir Disable
UserDir "www"
# Some parameters in UserDir
#Allowing .htaccess directive
AllowOverride All
Options MultiViews Indexes FollowSymLinks
Restart your Apache server
service httpd restart
Suppose the directory is you are working on is /home/swobodin/www/Lab/rewrite
Let's start with a simple redirection
Create a HTML file called new.html and edit your .htaccess
# Start the engine
RewriteEngine On
# Set the rule
RewriteCond %{REQUEST_FILENAME} ! -f
RewriteCond %{REQUEST_FILENAME} ! -d
RewriteRule ^(.*)\.html$ /~>swobodin/www/Lab/rewrite/new.html [L]
It means the following:
RewriteCond sets a condition, %{REQUEST_FILENAME} is an Apache variable meaning (not too difficult to figure out) the requested file.
Any requested file that ends with html and is not a file (-f) neither a directory (-d) will be redirected to the file new.html. The L flag is like Perl's "last" or C "break", means no other rules can be added if a condition is set before.
If we had to translate the lines above to PHP, it would be like the following;
if (! is_file($_SERVER['REQUEST_URI']) && ! is_dir($_SERVER['REQUEST_URI'])) {
header("location: /~swobodin/www/Lab/rewrite/new.html");
}
?>
Now, point your browser to http://127.0.0.1/~swobodin/www/Lab/rewrite/anyfile.html
The URL doesn't change, but the content is new.html !
Let's make the operation more useful. Suppose we have req.php that accepts both id and item GET variables.
It should be like the following:
print "If you see this message then you have been successfully redirected.How if we changed the argument to an easier to memorize URL, while the directories don't physically exist?
\n";
if (isset ($_GET['id'])) {
print "id is ".$_GET['id']."
\n";
}
if (isset ($_GET['item'])) {
print "id is ".$_GET['i']."
\n";
}
?>
From:
http://127.0.0.1/~swobodin/www/Lab/rewrite/req.php?id=50&item=80
to
http://127.0.0.1/~swobodin/www/Lab/rewrite/50/80/
Edit .htaccess and set the following commands:
RewriteEngine OnPlease note: there's a method to make fake files/directories without using the mod_rewrite, but it's more complex and less reliable. It's worth to have a look at anyway:
ReWrite_Rule ^(.*)/(.*)$ /~swobodin/www/Lab/rewrite/req.php?id=$1&item=$2
We want to have the following URL
http://127.0.0.1/~swobodin/www/Lab/rewrite/entry/145
so that it displays: "Entry number 145"
Create a PHP file called "entry" without suffix.
$url = $_SERVER['PHP_SELF'];And force the plain text file entry to be executed as PHP file on the server; edit .htaccess:
$directory = basename(__FILE__);
$entry = preg_replace("/^.*$a2\/(.*$)/i",'\1',$directory);
// a regular expression to parse the entry number
print "Entry number $entry";
?>
Not really practical, but may be useful when no rewrite mode is available.
ForceType application/x-httpd-php
This was only an overview about the module. For further information, you may consult http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
Your favorite text editor ...?

Submitted by Swobodin on Mon, 2006-07-31 18:10. ::
The fastest way to mount a SAMBA directory on Fedora Core 5

Submitted by Swobodin on Mon, 2006-07-24 12:02. ::
First, look for SAMBA shared directories using the command
You will be asked for a password, type if any, else, leave it blank and hit Enter.
Once you got the network architecture, mount the directory as root. Note that from Fedora Core 5, smbfs is no longer used, and is replaced by cifs.
rw: Read/write mode.
uid, gid: user/group.
dmask, fmask : directory mask and file mask.
A password prompt will appear; if you want to specify username and password, the options will be like the following:
You can finally write the rules in /etc/fstab
smbtree
You will be asked for a password, type if any, else, leave it blank and hit Enter.
Once you got the network architecture, mount the directory as root. Note that from Fedora Core 5, smbfs is no longer used, and is replaced by cifs.
mount //192.168.1.5/SHARED /mnt/samba -tcifs -orw,uid=nobody,gid=nobody,dmask=000,fmask=000
rw: Read/write mode.
uid, gid: user/group.
dmask, fmask : directory mask and file mask.
A password prompt will appear; if you want to specify username and password, the options will be like the following:
mount //192.168.1.5/SHARED /mnt/samba -tcifs -orw,uid=nobody,gid=nobody,dmask=000,fmask=000,username=swobodin,password=
You can finally write the rules in /etc/fstab
//192.168.1.5/SHARED /mnt/samba cifs rw,uid=nobody,gid=nobody,dmask=000,fmask=000,username=swobodin,password=
Dumping sound live

Submitted by Swobodin on Wed, 2006-07-12 11:30. ::
Ever wished to record a vocal conversation in chat or phone, a radio show, a sound track, ... yet the software you were using doesn't allow you to save audio file?
Well, I can't really guarantee that you can recover those old tracks, but I can show you a way to save any output from the sound card!
The Advamced Linux Sound Architecture (ALSA) comes with useful tools; the one we need for our operation is called arecord.
arecord is a command-line soundfile recorder for the ALSA soundcard driver. It supports several file formats and multiple soundcards with multiple devices.
Start by recording everything typing
arecord filename.wav
By default, arecord outputs a wav file with the following parameters: Unsigned 8 bit, Rate 8000 Hz, Mono
; unless you specify different rules:
-t flag switches file type; available options are:
-f flag handles format, see the manual for more information
Well, I can't really guarantee that you can recover those old tracks, but I can show you a way to save any output from the sound card!
The Advamced Linux Sound Architecture (ALSA) comes with useful tools; the one we need for our operation is called arecord.
arecord is a command-line soundfile recorder for the ALSA soundcard driver. It supports several file formats and multiple soundcards with multiple devices.
Start by recording everything typing
arecord filename.wav
By default, arecord outputs a wav file with the following parameters: Unsigned 8 bit, Rate 8000 Hz, Mono
; unless you specify different rules:
-t flag switches file type; available options are:
- voc : Creative Labs voice data; you may convert it to wav using Portable Voice Format (pvf) tools
#record file
arecord -t voc out.voc
#convert it to pvf
voctopvf out.voc out.pvf
#convert it to wav
pvftowav out.pvf out.wav
#Clean up files
rm -fv *voc *pvf - raw: Generates raw audio files ready to be burned as audio tracks. To preview a raw file, simply redirect it to your sound device:
arecord -t raw out.raw
cat out.raw > /dev/dsp - au: Sun Audio format; ogg tools handle this sound format, as well as audacity.
- Microsoft WAVE
-f flag handles format, see the manual for more information
Tiny C Compiler

Submitted by Swobodin on Fri, 2006-07-07 11:08. ::
Tiny C Compiler (TCC) is a C compiler and interpreter; thus you can run your C program as a script without having to compilet it, which makes it portable. You can also make binary executable as for any other compiler including gcc; the advantages of tcc are:
As for the source, uncompress the tarball file, configure and compile it using gcc first
Optionally, you may want to compile the source with tcc itself (You will see the difference: It's too much faster!)
make clean
Done! Start to compile and run the codes in examples directory
Here's a simple C file
Compile it like the following
Or just run it as script
Tiny C Compiler also supports arguments and some gcc options, such as linking, adding an include path, etc.
For example
You may just run it like the following, even without binary compilation:
http://tinycc.org
- Small: The sizes of generated binaries are smaller than the ones compiled by gcc.
- Fast: too much faster while compiling/running.
- Unlimited: TCC is heading torward full ISOC99 compliance. hence it can compile itself.
- Safe: includes an optional memory and bound checker.
- Direct compilation: No need for assembly or linking.
- Supports C script: you just add to the header the following line:
#!/usr/local/bin/tcc -run
- libtcc is included, so you may discard standard libraries
As for the source, uncompress the tarball file, configure and compile it using gcc first
tar xvfz tcc-x.yy.tar.gz
cd tcc-x.yy
./configure && make
sudo make install
Optionally, you may want to compile the source with tcc itself (You will see the difference: It's too much faster!)
make clean
sed -ie 's/=gcc.*$/=tcc/g' config.mak
make
sudo make install
Done! Start to compile and run the codes in examples directory
Here's a simple C file
#include
int main() {
printf("Hello world\n");
return 0;
}
Compile it like the following
tcc -o hello hello.c
Or just run it as script
tcc -run hello.c
Tiny C Compiler also supports arguments and some gcc options, such as linking, adding an include path, etc.
For example
#include
#define _XOPEN_SOURCE
#include
int
main (int argc, char *argv[])
{
if (argc != 2)
{
printf ("usage: %s your_password\n", argv[0]);
return (-1);
}
char *encrypted = (char *) malloc (10);
printf ("%s\n", crypt (argv[1], "$1$"));
return 0;
}
You may just run it like the following, even without binary compilation:
tcc -lcrypt -run encrypt.c your_password
http://tinycc.org
Use of BibTeX
Submitted by kaiser on Mon, 2006-07-03 11:54. ::
Below I attached a tutorial written in TeX on how to use BibTeX.
You must have bibtex and pdflatex installed; then simply type
make
Else, you can read the PDF file included into the package.
Download tutorial
Going further with SQLite

Submitted by Swobodin on Sat, 2006-07-01 16:54. ::
SQLite is an Open Source light weight, portable, quick yet powerful C library that implements a self-contained, embeddable, zero-configuration SQL database engine.
SQLite comes with an interactive command line program similar to MySQL. It lacks of many features but it's too much faster than many databases when treating huge data.
SQLite does not a connection to a distant server, it just creates a local binary database file on which you may execute queries.
SQLite 3 is included within recent Fedora Core versions. To install SQLite library with the interactive program, use yum
yum install sqlite
Now, you can start to find out about it, it uses standard SQL queries and supports triggers.
To set an auto-incrementation field, you have to declare it as INTEGER PRIMARY KEY
For example:
Compilation
And then
An example of the code (From Pysqlite documentation)
http://www.sqlite.org
SQLite comes with an interactive command line program similar to MySQL. It lacks of many features but it's too much faster than many databases when treating huge data.
SQLite does not a connection to a distant server, it just creates a local binary database file on which you may execute queries.
SQLite 3 is included within recent Fedora Core versions. To install SQLite library with the interactive program, use yum
yum install sqlite
Now, you can start to find out about it, it uses standard SQL queries and supports triggers.
To set an auto-incrementation field, you have to declare it as INTEGER PRIMARY KEY
For example:
sqlite mydb.sqlite
sqlite> CREATE TABLE posts (id INTEGER PRIMARY KEY, author INTEGER, time TIMESTAMP, title VARCHAR(50), content TEXT, enabled BOOLEAN);
sqlite> INSERT INTO "posts" VALUES(NULL, 1, '2006-08-23 19:28:38', 'First try', 'Let''s try!', 1);
sqlite> SELECT * FROM "posts";
1|1|2006-08-23 19:28:38|First try|Let's try on!|1
sqlite> UPDATE "posts" SET author=2;
sqlite> /* Don't forget the dot (.) before the keywords */;
sqlite> .schema
CREATE TABLE posts (id INTEGER PRIMARY KEY, author INTEGER, time TIMESTAMP, title VARCHAR(50), content TEXT, enabled BOOLEAN);
sqlite> .dump
BEGIN TRANSACTION;
CREATE TABLE posts (id INTEGER PRIMARY KEY, author INTEGER, time TIMESTAMP, title VARCHAR(50), content TEXT, enabled BOOLEAN);
INSERT INTO "posts" VALUES(1, 2, '2006-08-23 19:28:38', 'First try', 'Let''s try on!', 1);
COMMIT;
sqlite> /*Dump data and structure to a file*/;
sqlite> .output file.sql
sqlite> .dump
sqlite> .output stdout
sqlite> /* Dump data into a HTML table (Not: not validated) */
sqlite> .mode html
sqlite> .output table.html
sqlite> .dump
sqlite> .quit
Using SQLite libraries
C
The C library comes like the following: (The example is token from SQLite documentation)#include
#include
static int callback(void *NotUsed, int argc, char **argv, char **azColName){
int i;
for(i=0; i
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
int main(int argc, char **argv){
sqlite3 *db;
char *zErrMsg = 0;
int rc;
if( argc!=3 ){
fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]);
exit(1);
}
rc = sqlite3_open(argv[1], &db);
if( rc ){
fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
exit(1);
}
rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg);
if( rc!=SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", zErrMsg);
}
sqlite3_close(db);
return 0;
}
Compilation
gcc -o sqlite-api sqlite.c -lsqlite
PHP
There's no SQLite 3 module for PHP, however, you may find at PEAR repository a PHP extension for SQLite 2. You don't need to have SQLite installed on your machine: Everything is included within the extension
if (!extension_loaded("sqlite")) die("Please install SQLite extension from PEAR repo");
$dbhandle = sqlite_open('mysqlitedb');
$query = sqlite_exec($dbhandle, "UPDATE users SET email='' WHERE username='jDoe'", $error);
if (!$query) {
exit("Error in query: '$error'");
} else {
echo 'Number of rows modified: ', sqlite_changes($dbhandle);
}
?>
Perl
You need to install the library from the extra repository:yum install perl-DBD-SQLite
And then
#!/usr/bin/perl -w
use strict;
use warnings;
use POSIX;
my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile","","");
Python
You need to install Pysqlite2 from the extra repositoryyum install python-sqlite2
An example of the code (From Pysqlite documentation)
from pysqlite2 import dbapi2 as sqlite
con = sqlite.connect("mydb")
cur = con.cursor()
SELECT = "select name_last, age from people order by age, name_last"
# 1. Iterate over the rows available from the cursor, unpacking the
# resulting sequences to yield their elements (name_last, age):
cur.execute(SELECT)
for (name_last, age) in cur:
print '%s is %d years old.' % (name_last, age)
# 2. Equivalently:
cur.execute(SELECT)
for row in cur:
print '%s is %d years old.' % (row[0], row[1])
http://www.sqlite.org
Record Everything you type in Shell

Submitted by Swobodin on Thu, 2006-06-22 13:34. ::
Sometimes when doing a huge work on the shell, you want to record everything you type and the screen displays; it's certainly possible to see the commands history and to output STDOUT and STDERR to a file, however, it would take a lot of effort to redirect commands; may be you make a mistake and use new file redirection (">") instead of appending (">>"), and all what you did goes away, besides, you are a human after all, and you may forget a redirection or several; let's not talk about associating commands in history file with the stdout and stderr files: it would be a torture!
Fortunately with the shell, you are not supposed to do everything by yourself.
script(1) makes a typescript of everything printed on your terminal.
if you want to dump all the output to a file
To append to the log file, use "-a" option..
More amazing, you can dump everything to a terminal! This requires that you own the terminal...
Terminals are listed like the following: The nain ones are called TTY1, TTY2, ... TTY7 (You can have 12 in fact).
After you open an X session, terminals inside GUI goes to /dev/pts . For example, /dev/pts/1, /dev/pts/1, etc.
To dump output to a console, make sure that it's yours
and dump the output there
This may also be useful when for example you connect via SSH to a machine as root to fix a damage, configure some files, ..., and to show the local user what you are doing, you can show him/her the terminal output.
Fortunately with the shell, you are not supposed to do everything by yourself.
script(1) makes a typescript of everything printed on your terminal.
if you want to dump all the output to a file
[swobodin@localhost arch]$ script shell_$(date '+%Y%m%d')
Script started, file is shell_20060823
[swobodin@localhost arch]$ ls -l
-rw-r--r-- 1 swobodin swobodin 57 Mar 31 2004 pass.php
-rwxrwxr-x 1 swobodin swobodin 90 May 2 2005 pearz.php
-rwxrwxr-x 1 swobodin swobodin 101 May 2 2005 pearz.php~
-rwxr-xr-x 1 swobodin swobodin 362 Jul 26 2004 Pid.php
-rwxr-xr-x 1 swobodin swobodin 66 Apr 4 2004 slash.php
-rw-r--r-- 1 swobodin swobodin 73 Mar 30 2004 sys.php
-rw-r--r-- 1 swobodin swobodin 84 Apr 23 2004 test.xml
[swobodin@localhost arch]$ exit
Script done, file is shell_20060823
[swobodin@localhost arch]$ cat shell_$(date '+%Y%m%d')
-rw-r--r-- 1 swobodin swobodin 57 Mar 31 2004 pass.php
-rwxrwxr-x 1 swobodin swobodin 90 May 2 2005 pearz.php
-rwxrwxr-x 1 swobodin swobodin 101 May 2 2005 pearz.php~
-rwxr-xr-x 1 swobodin swobodin 362 Jul 26 2004 Pid.php
-rwxr-xr-x 1 swobodin swobodin 66 Apr 4 2004 slash.php
-rw-r--r-- 1 swobodin swobodin 73 Mar 30 2004 sys.php
-rw-r--r-- 1 swobodin swobodin 84 Apr 23 2004 test.xml
To append to the log file, use "-a" option..
More amazing, you can dump everything to a terminal! This requires that you own the terminal...
Terminals are listed like the following: The nain ones are called TTY1, TTY2, ... TTY7 (You can have 12 in fact).
After you open an X session, terminals inside GUI goes to /dev/pts . For example, /dev/pts/1, /dev/pts/1, etc.
To dump output to a console, make sure that it's yours
ll /dev/pts/0
crw--w---- 1 swobodin tty 136, 0 Jun 22 11:57 0
and dump the output there
script /dev/pts/0
Script started, file is /dev/pts/0
exit
Script done, file is /dev/pts/0
This may also be useful when for example you connect via SSH to a machine as root to fix a damage, configure some files, ..., and to show the local user what you are doing, you can show him/her the terminal output.
ssh
's password:
[root@localhost ~]# script /dev/pts/1
Script started, file is /dev/pts/1
Script started on Thu 22 Jun 2006 12:44:16 PM CET
Where your from
Submitted by jilal on Wed, 2006-06-21 19:46. ::
1 comment | printer friendly page
Recent comments
8 weeks 6 days ago
9 weeks 5 days ago
10 weeks 5 days ago
11 weeks 2 days ago
11 weeks 5 days ago
13 weeks 10 hours ago
13 weeks 2 days ago
15 weeks 6 days ago
16 weeks 6 days ago
17 weeks 1 day ago