Showing posts with label linux. Show all posts
Showing posts with label linux. Show all posts

Thursday, May 25, 2017

PHP Script - detect whether running under Linux or Windows?

PHP script - detect whether running under Linux or Windows or other Operating System? I don't have so much knowledge but can overcome with some solution. "PHP_OS" will solve this issue. Below is function to check if OS is Windows or not:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    echo 'Windows!';
} else {
    echo 'Other Than Windows!';
}

PHP_OS will output below list of Operating System, not full list but I think it's almost all.
  • CYGWIN_NT-5.1
  • Darwin
  • FreeBSD
  • HP-UX
  • IRIX64
  • Linux
  • NetBSD
  • OpenBSD
  • SunOS
  • Unix
  • WIN32
  • WINNT
  • Windows
You can see on Wikipedia for more information.


Sunday, August 25, 2013

HowTo Format Date For Display or Use In a Shell Script

How do I format date to display on screen on for my shell scripts as per my requirements on Linux or Unix like operating systemsYou need to use the standard date command to format date or time. You can use the same command with the shell script.
 The syntax is
  1. date +FORMAT 
  2. date +"%FORMAT"
  3. date +"%FORMAT%FORMAT" 
  4. date +"%FORMAT-%FORMAT"

Task: Display date in mm-dd-yy format

Open a terminal and type the following date command:
$ date +"%m-%d-%y"Sample output:
02-27-07
To turn on 4 digit year display:
$ date +"%m-%d-%Y"Just display date as mm/dd/yy format:
$ date +"%D"

Task: Display time only

Type the following command:
$ date +"%T"Outputs:
19:55:04
To display locale's 12-hour clock time, enter:
$ date +"%r"Outputs:
07:56:05 PM
To display time in HH:MM format, type:
$ date +"%H-%M"Sample outputs:
00-50

How do I save time/date format to the shell variable?

$ NOW=$(date +"%m-%d-%Y"To display a variable use echo / printf command:
$ echo $NOW

A sample shell script

#!/bin/bash
NOW=$(date +"%m-%d-%Y")
FILE="backup.$NOW.tar.gz"
echo "Backing up data to /nas42/backup.$NOW.tar.gz file, please wait..."
# rest of script
# tar xcvf /nas42/backup.$NOW.tar.gz /home/ /etc/ /var
 

A complete list of FORMAT control characters supported by the date command

FORMAT controls the output. It can be the combination of any one of the following:
%FORMAT StringDescription
%%a literal %
%alocale's abbreviated weekday name (e.g., Sun)
%Alocale's full weekday name (e.g., Sunday)
%blocale's abbreviated month name (e.g., Jan)
%Blocale's full month name (e.g., January)
%clocale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%Ccentury; like %Y, except omit last two digits (e.g., 21)
%dday of month (e.g, 01)
%Ddate; same as %m/%d/%y
%eday of month, space padded; same as %_d
%Ffull date; same as %Y-%m-%d
%glast two digits of year of ISO week number (see %G)
%Gyear of ISO week number (see %V); normally useful only with %V
%hsame as %b
%Hhour (00..23)
%Ihour (01..12)
%jday of year (001..366)
%khour ( 0..23)
%lhour ( 1..12)
%mmonth (01..12)
%Mminute (00..59)
%na newline
%Nnanoseconds (000000000..999999999)
%plocale's equivalent of either AM or PM; blank if not known
%Plike %p, but lower case
%rlocale's 12-hour clock time (e.g., 11:11:04 PM)
%R24-hour hour and minute; same as %H:%M
%sseconds since 1970-01-01 00:00:00 UTC
%Ssecond (00..60)
%ta tab
%Ttime; same as %H:%M:%S
%uday of week (1..7); 1 is Monday
%Uweek number of year, with Sunday as first day of week (00..53)
%VISO week number, with Monday as first day of week (01..53)
%wday of week (0..6); 0 is Sunday
%Wweek number of year, with Monday as first day of week (00..53)
%xlocale's date representation (e.g., 12/31/99)
%Xlocale's time representation (e.g., 23:13:48)
%ylast two digits of year (00..99)
%Yyear
%z+hhmm numeric timezone (e.g., -0400)
%:z+hh:mm numeric timezone (e.g., -04:00)
%::z+hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::znumeric time zone with : to necessary precision (e.g., -04, +05:30)
%Zalphabetic time zone abbreviation (e.g., EDT)
SEE ALSO:

Thursday, August 22, 2013

Using php execute command/run another php file wihtout waiting for result

<?php
session_start();
$_SESSION["student_name"] = "Pritom Kumar Mondal";

$_SESSION["roll"] = "College: 2150, Varsity: 060238";
echo "Start time: " date('h:i:s');
$phpCommandLocation "C:\\xampp\\php\\php.exe";
$phpFileLocation    "C:\\xampp\\htdocs\\test1\\call.php";
$logLocation        "C:\\tmp\\result.log";
$argvList = " session_id=".session_id(); /*You can send session id*/ 
$argvList.= " name=".rawurlencode("Pritom Kumar Mondal");
$command            $phpCommandLocation " -f "           .
    $phpFileLocation . $argvList " 1>>" $logLocation " 2>&1 &"; 
pclose(popen("start /B " $command"r"));
echo 
"<BR>End time: " date('h:i:s'); 

?>

And output is:
Start time: 11:07:26
End time: 11:07:26

And call.php looks like:
<?php
foreach($argv as $argvString) {
    $argvStringList = explode("=", $argvString);
    if($argvStringList[0] == "session_id") {
        session_id($argvStringList[1]);
        session_start();

        /* Start session with received session id, BINGO... */
    }
}
$string 
"\r\n-------------------------------\r\nStart time: " date('h:i:s'); 

$string .= "\r\nStart sleeping for 5 seconds."; 
sleep(5); 
$string .= "\r\nEnd time: " date('h:i:s');
 file_put_contents("data.txt" 
    "SOMETHING WENT GOOD...................\r\n" 
    $string);
echo 
$string; 

echo "\r\nReceived argv list: ";
print_r($argv); /* Printing argv as array */
echo "\r\nPrevious index.php session variables in currently executed php: ";
print_r($_SESSION); /* Printing argv as array */
?>
Yellow background showing that this script wait for 5 seconds.

The C:\\tmp\\result.log is:
-------------------------------
Start time: 11:07:28
Start sleeping for 5 seconds.

End time: 11:07:33
Received argv list: 
Array
(
    [0] => C:\xampp\htdocs\test1\call.php
    [1] => session_id=gjbf54ql8dhuvg0njsgt4hh8n7
    [2] => name=Pritom%20Kumar%20Mondal%2C%20Roll%3D2525

Previous index.php session variables in currently executed php:
Array
(
    [
student_name] => Pritom Kumar Mondal
    [roll] => College: 2150, Varsity: 060238
)


There are a few thing that are important here.

First of all: put the full path to the php binary, because this command will run under the apache user, and you will probably not have command alias like php set in that user.

Seccond: Note 2 things at the end of the command string: the '2>&1' and the '&'. The '2>&1' is for redirecting errors to the standard IO. And the most important thing is the '&' at the end of the command string, which tells the terminal not to wait for a response.

Third: Make sure you have 777 permissions on the 'result.log' file

If you use linux operating system just write:
<?php
exec
($command " > /dev/null &"); 

?>

Wednesday, June 19, 2013

bash split string into array

IFS=', ' read -a array <<< "$string" /* array is the variable name */
To access an individual element:
echo "${array[0]}"
To iterate over the elements:
for element in "${array[@]}"
do
    echo "$element"
done
To get both the index and the value:
for index in "${!array[@]}"
do
    echo "$index ${array[index]}"
done
The last example is useful because Bash arrays are sparse. In other words, you can delete an element or add an element and then the indices are not contiguous.
unset "array[1]"
array[42]=Earth

How to set a BASH variable equal to the output from a command?

In addition to the backticks, you can use $(), which I find easier to read, and allows for nesting.
OUTPUT=$(ls -1)
echo $OUTPUT
 
 
You can use eval to execute a string:
eval $illcommando
 

Sunday, February 24, 2013

shell script echo new line to file


var1="Hello"
var2="World!"
logwrite="$var1\n$var2"
echo -e "$logwrite"  >> /Users/username/Desktop/user.txt
Explanation:
The \n escape sequence indicates a line feed. Passing the -e argument to echo enables interpretation of escape sequences.
It may even be simplified further:
var1="Hello"
var2="World!"
echo -e "$var1\n$var2"  >> /Users/username/Desktop/user.txt
or even:
echo -e "Hello\nWorld! "  >> /Users/username/Desktop/user.txt

How to tell if a string is not defined in a bash shell script

#!/bin/bash

if [ -z $1 ]; then
        echo 'Enter something please.';
        exit 1;
fi;

How To Manually Create Zone Files For Domain Names In Linux Server


http://www.wallpaperama.com/forums/how-to-manually-create-zone-files-for-domain-names-in-linux-server-t1698.html

How To Manually Create Zone Files For Domain Names In Linux Server

today i am going to teach how you can add a domain name to your web server using BIND. these is my case:
  • i have a fedora core linux web server with apache and bind9
  • my bind is chroot jailed, if you have a directory called "chroot" in /var/named then you are also chroot jail
  • i have a domain name poitint to my server.
  • i have access to root
  • i have access to linux shell (via ssh)
these are my properties (example)
  1. My domain name: wallpaperama.com
  2. My nameserver for wallpaperama.com is: ns1.wallpaperama.com
  3. My email address is myemail@example.com
  4. My linux server ip address is: 70.238.57.57
  5. My linux server hostname is: ns1.wallpaperama.com


STEP 1. login to your shell as root

STEP 2. send this command to create our first file called : wallpaperama.com.hosts
nano /var/named/chroot/var/named/wallpaperama.com.hosts
this will open a blank file called wallpaperama.com.hosts with our text editor called nano. you can use vi if you want to, if you want to use vi, then replace the command with: vi /var/named/chroot/var/named/wallpaperama.com.hosts

STEP 3. Now that you have wallpaperama.com.hosts file, add the following information:
$ttl 38400
wallpaperama.com.    IN      SOA     localhost.localdomain. myemail@example.com. (
                        1184045571
                        10800
                        3600
                        604800
                        38400 )
wallpaperama.com.    IN      NS      localhost.localdomain.
www.wallpaperama.com.        IN      A       70.238.57.57

now if you look at the information, all you have to do is replaced the following with your own information:
wallpaperama.com (replace any wallpaperama.com with whatever your DOMAIN NAME is)
myemail@example.com (replace myemail@example.com with whatever your EMAIL name is)
70.238.57.57 (replace 70.238.57.57 with whatever your IP ADDRESS name is)
1184045571 (this has to be a unique number you haven't used before. some people use the curretn time and date, for example 200707011535 with is the year = 2007, month = 07, day = 01, hour = 15, minute = 35)
NOTE: its important to you keep the same format as it is on the example above. Make sure you use the same format exactly as it appears above. what i mean by the format is to make sure the { } ; are in the same line as my example, otherwise, when you restart your DNS server, it will fail. i tell you cuz it failed on me once.


STEP 4. Now you need to edit the named.conf file, send this command:
nano /var/named/chroot/etc/named.conf
it should look something like this:
options {
        directory "/etc";
        pid-file "/var/run/named/named.pid";
        };

zone "." {
        type hint;
        file "/etc/db.cache";
        };

zone "anydomain.com" {
        type master;
        file "/var/named/anydomain.com.hosts";
        };

STEP 5. now you need to edit named.conf to add your domain name. so in my example, i will be adding wallpaperama.com and now, this is how named.conf should look like:
options {
        directory "/etc";
        pid-file "/var/run/named/named.pid";
        };

zone "." {
        type hint;
        file "/etc/db.cache";
        };

zone "anydomain.com" {
        type master;
        file "/var/named/anydomain.com.hosts";

zone "wallpaperama.com" {
        type master;
        file "/var/named/wallpaperama.com.hosts";
        };
As you can see all i did was added wallpaperama.com at the bottom of the file:
type master; (this is a master zone )
file "/var/named/wallpaperama.com.hosts"; (this is the location of the file where we created the wallpaperama.com.hosts on STEP 4.
NOTE: make sure you use the same format exactly as it appears above. what i mean by the format is to make sure the { } ; are in the same line as my example, otherwise, when you restart your DNS server, it will fail. i tell you cuz it failed on me once.

STEP 6. Now that you have all the correct files, you will need to restart your DNS server for the changes to take affect. so restart your DNS server with the following command:
/etc/init.d/named restart


Now open your website on your browser and you should see your webserver.

this is what i got:


Ok, the next step would be to point to a directory specially for my domain instead of getting the default apache page right.

so this is how you do it: click on this link on how to add virtual domain names in apache server

Thursday, December 13, 2012

Run Bash Script Using Java And Get Debug And Error Output

String command = "sudo /usr/bin/some_name.sh";
System.out.println("runBashScriptCommand: " + command);
try {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(command);
    printBufferedReaderOutputFromProcess(process);
    process.waitFor();
    return "true";
} catch (Exception ex) {
    System.out.println("EX:" + ex.toString());
    return ex.toString();
}

private void printBufferedReaderOutputFromProcess(Process p) {
    try {
        String s = null;
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        System.out.println("\n\npHere is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception ex) {
        System.out.println("printBufferedReaderOutputFromProcess:" + ex.toString());
    }
}

Tuesday, December 11, 2012

Move all files except one

File Structure:
/root/tmp/test
[root@dswing test]# ll
total 12
-rw-r--r-- 1 root root    2 Dec 12 13:41 a.txt
-rw-r--r-- 1 root root    4 Dec 12 13:42 b.txt
-rw-r--r-- 1 root root    0 Dec 12 13:43 c.txt
drwxr-xr-x 2 root root 4096 Dec 12 13:50 ks

Command:
find /root/tmp/test/ -maxdepth 1 -mindepth 1 -type f -not -name c.txt | grep -i txt$ | xargs -i cp -af {} /root/tmp/test/ks

Description:
-maxdepth 1 makes it not search recursively.  
-mindepth 1 makes it not include the /root/tmp/test/ path itself into the result.
-type f means search only for file type.
-not -name c.txt means all files except c.txt
grep -i txt$ means files name ends with txt. 

Put a.txt -file to the end of b.txt -file

In a bash script such append.sh file, write the following code: 
#!/bin/bash
A=/root/tmp/test/a.txt
B=/root/tmp/test/b.txt
cat $A >> $B


The >> redirects the output of the cat command (which output file A) to the file B. But instead of overwriting contents of B, it appends to it. If you use a single >, it will instead overwrite any previous content in B.

Check if a program exists from a bash script

$ command -v foo >/dev/null 2>&1 || { 
  echo >&2 "I require foo but it's not installed.  Aborting."; exit 1;  
}
OR 
$ type foo >/dev/null 2>&1 || { 
  echo >&2 "I require foo but it's not installed.  Aborting."; exit 1;  
}
OR 
$ hash foo 2>/dev/null || { 
  echo >&2 "I require foo but it's not installed.  Aborting."; exit 1;  
}

Resize a list of images in line command

for file in *.jpg; do 
  convert -resize 800x600 -- "$file" "${file%%.jpg}-resized.jpg"; 
done
 
OR 
 
ls *.jpg|sed -e 's/\..*//'|xargs -I X convert X.jpg whatever-options X-resized.jpg 
 
 
# .jpg files, 10% size, no rename, it will overwrite the old pictures
#!/bin/bash
for i in *.jpg; do convert $i -resize 10% $(basename $i .jpg).jpg; done

How to output MySQL query results in csv format

SELECT 'Order Id', 'Product Name', 'Quantity'
UNION
(
SELECT order_id,product_name,qty
FROM orders
INTO OUTFILE 'C:\\tmp\\orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
)

How to do something with bash when a text line appear to a file

Use command
tail -f file.log | grep --line-buffered "my pattern" | while read line
do
  echo $line
done
The --line-buffered is the key here, otherwise the read will fail.

Delete all but the 4 newest directories

ls -atrd */ | head --lines=-4 | xargs rm -rf

Bash One Liner: copy template_*.txt to foo_*.txt

Say I have three files (template_*.txt):
  • template_x.txt
  • template_y.txt
  • template_z.txt
I want to copy them to three new files (foo_*.txt).
  • foo_x.txt
  • foo_y.txt
  • foo_z.txt
for f in template_*.txt; do cp $f foo_${f#template_}; done
or
for file in template_*.txt ; do 
  cp $file `echo $file | sed 's/template_\(.*\)/foo_\1/'` ;  
done