Linux Ask!

Linux Ask! is a Q & A web site specific for Linux related questions. Questions are collected, answered and audited by experienced Linux users.

Jun 032011
 

How to echo string to standard error (stderr)?

Answer:

To echo string to the standard error (stderr), rather than the standard output (stdout), you can define the following function in your shell (put in your ~/.bashrc file)

# function echo2() { echo "$@" 1>&2; }

Then you can execute the command like:

# echo2 test

Jun 012011
 

Simple for loop in Bash shell

Answer:

A simple for loop in Bash shell would like the following. You can use it wisely to skip a lot of repetitive tasks.

#!/bin/bash

for i in {1..10}
do
   echo "I am command No. $i"
done
May 182011
 

Add Personal Package Archives (PPA) to the current repository in Ubuntu

Answer:

add-apt-repository is a helper script which adds an external APT repository to either /etc/apt/sources.list or a file in /etc/apt/sources.list.d/. It can also import the keys needed.

To get this tool, just a single command:

# sudo apt-get install python-software-properties

That is it.

Apr 142011
 

Validate email address using PHP

Answer:

To validate an email address using PHP, you can use the code below. (It is from www.ilovejackdaniels.com/php/email-address-validation , it is not perfect, but better than most of the average solutions found in the Internet)

<?php

function check_email_address($email) {
  // First, we check that there's one @ symbol, 
  // and that the lengths are right.
  if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
    // Email invalid because wrong number of characters 
    // in one section or wrong number of @ symbols.
    return false;
  }
  // Split it into sections to make life easier
  $email_array = explode("@", $email);
  $local_array = explode(".", $email_array[0]);
  for ($i = 0; $i < sizeof($local_array); $i++) {
    if
(!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&
↪'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
$local_array[$i])) {
      return false;
    }
  }
  // Check if domain is IP. If not, 
  // it should be valid domain name
  if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) {
    $domain_array = explode(".", $email_array[1]);
    if (sizeof($domain_array) < 2) {
        return false; // Not enough parts to domain
    }
    for ($i = 0; $i < sizeof($domain_array); $i++) {
      if
(!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|
↪([A-Za-z0-9]+))$",
$domain_array[$i])) {
        return false;
      }
    }
  }
  return true;
}
Mar 222011
 

Sending a UTF8 encoded CSV from PHP

Answer:

It is easy to generate a CSV file using the fputcsv function. One of a very common problems is even the file is UTF-8 encoded, Microsoft Excel is still unable to identiy the file as UTF-8.

To solve this, you need to add the UTF-8 BOM to the beginning of the file.

E.g.

<?php 

echo "\xEF\xBB\xBF" . $csvdata; // Assume $csvdata contains the CSV string you want to output