Archive | How To

Tags: , , , ,

Bash For Loops

Posted on 27 March 2013 by Johnny

ow do I use bash for loop to repeat certain task under Linux / UNIX operating system? How do I set infinite loops using for statement? How do I use three-parameter for loop control expression?

A ‘for loop’ is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script.

For example, you can run UNIX command or task 5 times or read and process list of files using a for loop. A for loop can be used at a shell prompt or within a shell script itself.

for loop syntax

Numeric ranges for syntax is as follows:

for VARIABLE in 1 2 3 4 5 .. N
do
	command1
	command2
	commandN
done

OR

for VARIABLE in file1 file2 file3
do
	command1 on $VARIABLE
	command2
	commandN
done

OR

for OUTPUT in $(Linux-Or-Unix-Command-Here)
do
	command1 on $OUTPUT
	command2 on $OUTPUT
	commandN
done

Examples

This type of for loop is characterized by counting. The range is specified by a beginning (#1) and ending number (#5). The for loop executes a sequence of commands for each member in a list of items. A representative example in BASH is as follows to display welcome message 5 times with for loop:

#!/bin/bash
for i in 1 2 3 4 5
do
   echo "Welcome $i times"
done

Sometimes you may need to set a step value (allowing one to count by two’s or to count backwards for instance). Latest bash version 3.0+ has inbuilt support for setting up ranges:

#!/bin/bash
for i in {1..5}
do
   echo "Welcome $i times"
done

Bash v4.0+ has inbuilt support for setting up a step value using {START..END..INCREMENT} syntax:

#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do
     echo "Welcome $i times"
 done

Sample outputs:

Bash version 4.0.33(0)-release...
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

Three-expression bash for loops syntax

This type of for loop share a common heritage with the C programming language. It is characterized by a three-parameter loop control expression; consisting of an initializer (EXP1), a loop-test or condition (EXP2), and a counting expression (EXP3).

for (( EXP1; EXP2; EXP3 ))
do
	command1
	command2
	command3
done

A representative three-expression example in bash as follows:

#!/bin/bash
for (( c=1; c<=5; c++ ))
do
   echo "Welcome $c times"
done

Sample output:

Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times

How do I use for as infinite loops?

Infinite for loop can be created with empty expressions, such as:

#!/bin/bash
for (( ; ; ))
do
   echo "infinite loops [ hit CTRL+C to stop]"
done

Conditional exit with break

You can do early exit with break statement inside the for loop. You can exit from within a FOR, WHILE or UNTIL loop using break. General break statement inside the for loop:

for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (disaster-condition)
  then
	break       	   #Abandon the loop.
  fi
  statements3          #While good and, no disaster-condition.
done

Following shell script will go though all files stored in /etc directory. The for loop will be abandon when /etc/resolv.conf file found.

#!/bin/bash
for file in /etc/*
do
	if [ "${file}" == "/etc/resolv.conf" ]
	then
		countNameservers=$(grep -c nameserver /etc/resolv.conf)
		echo "Total  ${countNameservers} nameservers defined in ${file}"
		break
	fi
done

Early continuation with continue statement

To resume the next iteration of the enclosing FOR, WHILE or UNTIL loop use continue statement.

for I in 1 2 3 4 5
do
  statements1      #Executed for all values of ''I'', up to a disaster-condition if any.
  statements2
  if (condition)
  then
	continue   #Go to next iteration of I in the loop and skip statements3
  fi
  statements3
done

This script make backup of all file names specified on command line. If .bak file exists, it will skip the cp command.

#!/bin/bash
FILES="$@"
for f in $FILES
do
        # if .bak backup file exists, read next file
	if [ -f ${f}.bak ]
	then
		echo "Skiping $f file..."
		continue  # read next file and skip cp command
	fi
        # we are hear means no backup file exists, just use cp command to copy file
	/bin/cp $f $f.bak
done

Comments (0)

Executing PHP scripts over HTTP Using Cron Jobs

Tags: , , ,

Executing PHP scripts over HTTP Using Cron Jobs

Posted on 23 March 2013 by Johnny

In programming there are a number of ways to execute on an idea and get a result, executing a php file on your web server is no different. Below I will provide examples of how to execute a php script or other type of script over http using configurable cron jobs.

Just about all webhosts also provide a method of adding cronjobs through their control panels including cpanel and plesk.

Method 1: Execute the script using php from the crontab

Just like how you call your shell script (As show in our crontab 15 examples article), use the php executable, and call the php script from your crontab as shown below.

To execute myscript.php every 1 hour do the following:

# crontab -e
00 * * * * /usr/local/bin/php /home/john/myscript.php

Method 2: Run the php script using URL from the crontab

If your php script can be invoked using an URL, you can lynx, or curl, or wget to setup your crontab as shown below.

The following script executes the php script (every hour) by calling the URL using the lynx text browser. Lynx text browser by default opens a URL in the interactive mode. However, as shown below, the -dump option in lynx command, dumps the output of the URL to the standard output.

00 * * * * lynx -dump http://www.randomlinux.com/myscript.php

The following script executes the php script (every 5 minutes) by calling the URL using CURL. Curl by default displays the output in the standard output. Using the “curl -o” option, you can also dump the output of your script to a temporary file as shown below.

 

 

*/5 * * * * /usr/bin/curl -o temp.txt http://www.randomlinux.com/myscript.php

The following script executes the php script (every 10 minutes) by calling the URL using WGET. The -q option indicates quite mode. The “-O temp.txt” indicates that the output will be send to the temporary file.

*/10 * * * * /usr/bin/wget -q -O temp.txt http://www.randomlinux.com/myscript.php

The -o and -O flags are only necessary if you want to log the output of the script that is being executed if this information is not needed these flags can be ignored.

Comments (0)

Adding Aliases to your .bashrc

Tags: , ,

Adding Aliases to your .bashrc

Posted on 21 March 2013 by Johnny


Ever wonder how you can make shortcuts for some of those long cumbersome Linux commands?  You can by making an alias for it.  What is an alias?  It is a shortcut, let me demonstrate.  Say you want to restart Gnome Network Manager.  To do that you would type the following in a terminal:

sudo /etc/init.d/networking restart

Now you could make an alias called
netre to save yourself some typing and this tutorial will show you how.

Remember this tutorial is for BASH and not SH, CSH, Korn, etc. and more specifically for use with Ubuntu.  I cannot guarantee that this will work with other Linux distributions.

The first thing you will need to do if open your .bashrc file located in your home directory.  To do this type the following in a terminal:

gedit ~/.bashrc

This will bring up the Gedit text editor with the contents of the bashrc file.  Netx step is to locate the Alias definitions in the file.  You will need to uncomment the if statement to activate the alias definitions in a file or just add them directly in the .bashrc file.  The cleaner approach is to add them in a separate file for separation.  We will proceed with putting all your aliases in  separate file.  As you can see from the example listing I have uncommented the if statement to put all my definitions in a separate file.  Once this is done seave and exit gedit.

# 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

The next step is to create a new file called .bash_aliases in your home directory.  You can substitute another name other than .bash_aliases if you like.  To create the new file type the following in a terminal:

gedit ~/.bash_aliases

This will once again bring up the Gedit text editor with a blank text file.  We can now sart adding aliases to the file.  The format for adding an alias is as follows:

alias <desired alias>=’<linux_command>’

Here is an example:

alias netre=’sudo /etc/init.d/networking restart’

Make sure you use the tick mark ‘ when enclosing the linux command.  Once you are done adding the command hit the “Save” button.  Now the next time you bring up a terminal and type netre you will restart network manager.

You can add numerous alias commands to the file for your command line happiness.

Comments (0)

Tags: , , , , , ,

dtv.py – The Linux Command Line DirecTV Remote

Posted on 23 February 2013 by Chris

It’s safe to say that I spend a lot of time on the command line, and really prefer to do as much as possible from there.  So, it only makes since to be able to control my DVR from the command line too.  So, I created dtv.py, the DirecTV command line remote.  As of now, you can operate almost all of the buttons that would be on the remote, as well as get information about different channels and see a scrolling list of what is on all of the channels

.

Download:

dtv.py66 downloads

 

You will need to edit the following line in the script to add the IP address of the DirecTV box to the script.

 

####### Put the IP of your DVR here! #######

boxip = ’192.168.1.125′

You can also set your favorite channels for the -f flag in the favorites section of the script.

## Put your favorite channels here, seperated by spaces ##

favs = ’2 13 20 26 39 249′

 

Here are the different commands that you can run as of now.

 

usage: dtv.py [-h] [-v] [-i channel] [-c] [-t channel] [-a start,end]
[-b BUTTON] [-f] [--devlist]
optional arguments:

-h, –help show this help message and exit
-v, –version show program’s version number and exit
-i channel, –info channel
Shows info for a channel.
-c, –current Shows info for currently tuned channel
-t channel, –tune channel
Tune to a channel
-a start,end, –all start,end
Show a scrolling list what what’s on a range of
channels. Must specify a comma separated start and end
channel.
-b BUTTON, –button BUTTON
Press a button as you would on a physical remote. Can
use a comma to separate button presses
-f, –favs Show what is on your favorite channels
–devlist Show list of options available from the DVR. Only good
for development

 

There is more to come and feature requests are very welcome!

Comments (0)

How to install a .deb file from the command line

Tags: , , , , , ,

How to install a .deb file from the command line

Posted on 17 August 2012 by Chris

So you have downloaded a .deb file with a program that you would like to install. Most distros that are using a graphical interface will have a package manager that you can use to install these. But if you’re like me, you prefer to do it from the command line. To install it from there, you will need to use the dpkg command, using the -i flag, which does the install. In this example, I have dowloaded Google chrome for Linux from their website and am installing it on Ubuntu.

root@Desktop:/home/user/Downloads# dpkg -i google-chrome-stable_current_i386.deb 

Selecting previously unselected package google-chrome-stable.
(Reading database ... 296976 files and directories currently installed.)
Unpacking google-chrome-stable (from google-chrome-stable_current_i386.deb) ...
Setting up google-chrome-stable (21.0.1180.79-r151411) ...
update-alternatives: using /usr/bin/google-chrome to provide /usr/bin/x-www-browser (x-www-browser) in auto mode.
update-alternatives: using /usr/bin/google-chrome to provide /usr/bin/gnome-www-browser (gnome-www-browser) in auto mode.
Processing triggers for man-db ...
Processing triggers for desktop-file-utils ...
Processing triggers for bamfdaemon ...
Rebuilding /usr/share/applications/bamf.index...
Processing triggers for gnome-menus ...
Processing triggers for menu ...

If that finishes with no errors, then the package should be installed. In this case, I can now open Google Chrome though the Window manager’s menu or through the terminal.

Comments (1)

Tags: , ,

Download the RandomLinux.com Android app!

Posted on 10 June 2012 by Chris

Download v1 of the RandomLinux.com Android app! Stay up to date on everything that’s Linux right from your phone or tablet!

Download below!

Continue Reading

Comments (0)

Tags: , , , , , ,

How to install Samba on Ubuntu – Automated installation script available

Posted on 05 June 2012 by Chris

Samba is an open source software suite which provides file and print services. This can be installed using a few commands, or using our installation script at the bottom of this post.

 

The first thing that you need to do is install the Samba and samba-common packages.

sudo apt-get install samba samba-common

You will then want to make sure that python-glade2 is installed.

sudo apt-get install python-glade2

After that, you will want to install the Samba configuration tool.

sudo apt-get install system-config-samba

You then need to add a user account for the Samba user. You can use any name you would like.

sudo useradd sambauser

You will also want to create a user for you to log into your Samba server when you connect.

sudo smbpasswd -a sambauser

You will also want to run the Samba Configuration tool to set up the folders that you want to share. You can find that in your system’s app tray or you can start it by using the following command.

sudo system-config-samba

You are also able to download the installation script we created to help you automate installing that. This was tested on Ubuntu 12.04, so I cannot guarantee that it will work on anything but that. If you need it to work on your OS, let us know what you’re using and we’ll get a script set up for it.

Download the installation script here:

installsamba.sh444 downloads

You need to make the permissions for this executable (something like chmod 755 installsamba.sh), then run:

sh installsamba.sh

Let us know how it works for you! If you like it and it helps you, feel free to share!

If you would like to see the source code for that, you can see it here:

installsamba.sh Source

Enjoy!

Comments (1)

Add and Remove PHP Modules on cPanel Servers Without Recompiling Apache

Tags: , , , , , , , ,

Add and Remove PHP Modules on cPanel Servers Without Recompiling Apache

Posted on 16 May 2012 by Chris

 

If you are running a cPanel server, you are able to use EasyApache to add and remove many PHP extensions. cPanel has the ability to also install and uninstall PHP modules on the fly using the phpextensionmgr, which can be found at /scripts/phpextensionmgr. You are able to see the usage and option by using the –help flag, as shown below.

root@devbox [~]# /scripts/phpextensionmgr --help
Usage:
    phpextensionmgr [options] [action] [extension]

        Options:
          --help       Help message
          --prefix     Installation prefix for PHP (normally /usr/local or /usr/local/php4)

        Actions:
          install      Install or update the extension
          uninstall    Uninstall the extension
          status       Display the installation status of the extension
          list         Show available extensions

 

As you can see, you are able to install, uninstall, display whether or not the extension is installed, or list all of the available modules. Running the list command as below will show all of the modules that are available to be added on your server.

root@devbox [~]# /scripts/phpextensionmgr list 
Available Extensions:
EAccelerator
IonCubeLoader
Zendopt
Xcache
SourceGuardian
PHPSuHosin

You can also find the status of a single module by using the status flag.

root@devbox [~]# /scripts/phpextensionmgr status Xcache
Updating md5sum list
Fetching http://httpupdate.cpanel.net/cpanelsync/easy/targz.yaml (connected:0).......
(request attempt 1/12)...Using dns cache file /root/.HttpRequest/httpupdate.cpanel.net
......searching for mirrors (mirror search attempt 1/3)......
mirror search success......connecting to 69.72.212.10...
@69.72.212.10......connected......receiving...100%......request success......Done
Downloading tarball for Xcache
Fetching http://httpupdate.cpanel.net/cpanelsync/easy/targz/Cpanel/Easy/Xcache.pm.tar.gz (connected:0).......
(request attempt 1/12)......connecting to 69.72.212.10...@69.72.212.10......connected......
receiving...100%......request success......Done
Determining status of Xcache
Xcache extension is NOT installed

 

If we wanted to install Xcache, we would use the install flag, which will take care of the entire install process.  Keep in mind that we are only using Xcache as an example and it’s usage will depend on your server configuration as well.

root@devbox [~]# /scripts/phpextensionmgr install Xcache
Installing Xcache
Determining PHP version
Configuring for:
PHP Api Version:         20090626
Zend Module Api No:      20090626
Zend Extension Api No:   220090626
Will now run system( ./configure,--with-php-config=/usr/local/bin/php-config )
checking for egrep... grep -E
checking for a sed that does not truncate output... /bin/sed
checking for cc... cc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables... 
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether cc accepts -g... yes
checking for cc option to accept ANSI C... none needed
.....
.....
(More compiling stuff)
....
....
/bin/sh /home/cpeasyapache/phpextensions/xcache/xcache-1.3.2/libtool --mode=install cp ./xcache.la /home/cpeasyapache/phpextensions/xcache/xcache-1.3.2/modules
cp ./.libs/xcache.so /home/cpeasyapache/phpextensions/xcache/xcache-1.3.2/modules/xcache.so
cp ./.libs/xcache.lai /home/cpeasyapache/phpextensions/xcache/xcache-1.3.2/modules/xcache.la
PATH="$PATH:/sbin" ldconfig -n /home/cpeasyapache/phpextensions/xcache/xcache-1.3.2/modules
----------------------------------------------------------------------
Libraries have been installed in:
   /home/cpeasyapache/phpextensions/xcache/xcache-1.3.2/modules

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,--rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------

Build complete.
Don't forget to run 'make test'.

Got ret value 0 from system( make )
Will now run system( make,install )
Installing shared extensions:     /usr/local/lib/php/extensions/no-debug-non-zts-20090626/
Got ret value 0 from system( make,install )
Will now run system( make,clean )
find . -name \*.gcno -o -name \*.gcda | xargs rm -f
find . -name \*.lo -o -name \*.o | xargs rm -f
find . -name \*.la -o -name \*.a | xargs rm -f 
find . -name \*.so | xargs rm -f
find . -name .libs -a -type d|xargs rm -rf
rm -f libphp.la   modules/* libs/*
Got ret value 0 from system( make,clean )
Xcache extension activated
./cpanel-install exiting with exit code 0

If you wanted to remove that module, you could do so with the uninstall flag.

root@devbox [~]# /scripts/phpextensionmgr uninstall Xcache
Uninstalling Xcache
Removing xcache from /usr/local/lib/php.ini

 

Using /scripts/phpextensionmgr can help you to add, remove, find the status of particular modules and list the available modules.  In you day to day work, this can help you to save time by not needing to run EasyApache to install the PHP modules which can save time and unnecessary load on your server.

 

 

 

Comments (0)

Tags: , , , , , , ,

Fix workspace switching on Gnome 3.4 after updating

Posted on 03 May 2012 by Chris

If you have recently updated to Ubuntu 12.04 with Gnome as your desktop and are using dual monitors, you have probably noticed that only one of the screens switch workspaces and the other stays fixed. Before, you were able to fix this by using the gconf-editor, however now when you make changes to that, it is no longer working and the changes are not being applied. To fix the monitors when that does not work, you need to run the following command, which will disable workspaces-only-on-primary, which is basically doing the same thing as is done in the gconf-editor.

Run this command as the user that you are logged in as (not using sudo or as root in the command line)

gsettings set org.gnome.shell.overrides workspaces-only-on-primary false

You should not receive any output when you run the command and the changes should be applied immediately without needing to log out. You will now be able to change workspaces correctly on both monitors.

Comments (0)

Tags: , , , ,

Find the version of Gnome that you are using

Posted on 03 May 2012 by Chris

To find the version of the Gnome desktop, you simply have to run the following command:

gnome-shell --version

You should get some output that looks like this:

randomlinux@Desktop:~$ gnome-shell --version
GNOME Shell 3.4.1

Comments (0)





Download v1 of the RandomLinux.com Android app! Stay up to date on everything that's Linux right from your phone or tablet! Download below!