Tag Archives: command line

Ubuntu Server: How to Create a Symbolic Link Tips, Tricks and Tutorials 05 JUN 2015

Just as a quick note to myself because I’m doing this more often in server setups these days (which nevertheless is still infrequent enough that I need to drop notes for myself) – to create a symbolic link (symlink) on an Ubuntu server via the terminal, in particular to link to a folder, I need to use the ln command combined with the -s switch (The ln link command has a whole lot of uses, but we’re interested in symbolic links here).

The syntax is as follows:

ln -s <real folder> <link folder>

What the above achieves is a pseudo <link folder> which whatever you do inside it, actually happens in <real folder>. Nifty.

You can verify the symbolic link with the command ls -l which will show an arrow to where the link points.

red chain link

Related Link: http://manpages.ubuntu.com/manpages/vivid/man1/ln.1.html

Windows: How to Comment out a Line in a Batch File Tips, Tricks and Tutorials 27 JAN 2014

20091016-Windows-Command-PromptAs a reminder to myself so that I don’t have to Google it each and every time I need to work on a Windows Server (in other words, very seldom), there are three ways of adding comments into batch files (.bat) in Windows.

The first, most recognised way (standards-compliant, documented statement) is by making use of the REM statement. Any line in your batch file that starts with REM (which stands for REMark) is completely ignored by the batch interpreter.

Of course, because the way in which batch files are processed by COMMAND.COM and CMD.EXE, i.e. the batch file is read, the command is executed, and then the batch file is reread in order to execute the next command, rinse and repeat until the end of the file, REM statements do in essence slow down the execution of a batch file – though taking into account today’s processing power, this slowdown is negligible (unless of course your batch file is SUPER long!).

REM Comment - This bat-file moves all files

At this point it might be useful to remind yourself that by default the batch interpreter will print out each command before it is processed. Since REM commands don’t do anything, it’s safe to print them without any side effects. If however you want to avoid printing a command, including the REM statement, prefix it with @, or, to apply that setting throughout the program, run @echo off. (It’s echo off to avoid printing further commands; the @ is to avoid printing that command prior to the echo setting taking effect.)

The second way of commenting out a line in a batch file is by utilizing a clever trick that in essence has you converting your comment line into a label by prefixing it with a double colon (::). The first colon tells the batch interpreter that the following text is a label, while the second colon invalidates the label status but then forces the interpreter to still treat the line as a label anyway. This trick has the advantage of not slowing down the interpreter because it doesn’t have to stop to interpret the command statement like it has to for a REM statement – it simply jumps to the next line of the file without having to first reread the whole file again!

:: Comment - This bat-file moves all files

However, this trick does not allow you to start a comment mid line as labels always start at the first non-whitespace character in a command line. Also, code blocks are a pitfall for this trick as commands grouped by parentheses are interpreted as a single command line by the batch interpreter, which then obviously invalidates our ‘fake’ label as just mentioned above – your comment most likely won’t be sitting at the start of the concatenated command line!

Finally you can write multiple lines of comments (or comment blocks) by making use of the ability to jump over your lines of comment using the GOTO statement. In practice:

GOTO EndComment
Comment - This bat-file moves all files
Line 2 - Written by Craig
Line 3 - 2014-01-27
:EndComment

Note, it is probably a good idea to help others understand what is going on by using a descriptive GOTO label name.

And there you go, three different ways of adding comment lines into your .bat batch file.

Related Link: http://www.robvanderwoude.com/comments.php

Tech Tip: Retain your windows desktop environment on any device (PC/Mac/Linux/Android/iOS) by remote accessing your citrix xendesktop from CloudDesktopOnline at an unbelievable citrix xendesktop pricing. To enhance your experience with desktop in the cloud try out dedicated GPU hosting from Apps4Rent to fulfill your graphics requirements.

Ubuntu Server: How to Attach and Mount a Hard Drive Tips, Tricks and Tutorials 24 JAN 2014

ubuntu orange logoThe other day we needed to pull data off a restored VM running an older LTS version of Ubuntu Server. My IT contact helpfully attached a small 500 MB drive to the VMware vSphere server and then left me to do the rest. This is what was needed to be done:

I first ran the fdisk utility to get a listing of devices currently seen by the system.

sudo fdisk -l

This gave me a list of all devices, from which I was able to determine the size and logical name assigned to the newly added disk, in this case a 500mb drive located as /dev/sdb.

Unfortunately for me, this time around the drive wasn’t actually picked up as being formatted, and as such I needed to first partition the disk using fdisk:

sudo fdisk /dev/sdb 

fdisk will display the following menu:

  Command (m for help): m <enter>
  Command action
   a   toggle a bootable flag
   b   edit bsd disklabel
   c   toggle the dos compatibility flag
   d   delete a partition
   l   list known partition types
   m   print this menu
   n   add a new partition
   o   create a new empty DOS partition table
   p   print the partition table
   q   quit without saving changes
   s   create a new empty Sun disklabel
   t   change a partition's system id
   u   change display/entry units
   v   verify the partition table
   w   write table to disk and exit
   x   extra functionality (experts only)

  Command (m for help):

We want to add a new partition. Type “n” and press enter.

  Command action
   e   extended
   p   primary partition (1-4)

We want a primary partition. Enter “p” and enter.

  Partition number (1-4):

Since this will be the only partition on the drive, number 1. Enter “1” and enter.

If it asks about the first cylinder, just type “1” and enter. (We are making 1 partition to use the whole disk, so it should start at the beginning.)

Now that the partition is entered, choose option “w” to write the partition table to the disk. Type “w” and enter.

If all went well (i.e. “The partition table has been altered!” appeared), you now have a properly partitioned hard drive that’s ready to be formatted. Since this is the first partition, Linux will recognize it as /dev/sdb1, while the disk that the partition is on is still /dev/sdb.

Next up, I needed to format the new partition.

There are a variety of options you could choose from, but seeing as I was working with Ubuntu server, ext3 made sense for this particular use case:

sudo mkfs -t ext3 /dev/sdb1

Of course, if you prefer to use something that would work under both Ubuntu and Windows, then FAT32 remains a good option:

sudo mkfs -t fat32 /dev/sdb1

(Note I had to do the whole partition and format thing because of the nature of drive plugged in. If this had not been the case, the system would have recognised the drive appropriately – as seen in the fdisk listing – and you would be able to skip straight to this mount part of the walkthrough).

With the disk partitioned, formatted and now ready for use, the next step is to actually make it usable on the system, in other words mount it.

First up, create a mount point, basically the path through which you will access it. (I would recommend using a mount point with “/media”, as it is the default used by Ubuntu.)

sudo mkdir /media/external

Now to actually mount the drive:

sudo mount /dev/sdb1 /media/external

Note, depending on the filesystem of your attached drive, you might have to alter the mount string accordingly. If the filesystem is FAT16 or FAT32 (like it is for most USB flash drives), and we want to mount it at /media/external (having already created the mount point):

sudo mount -t vfat /dev/sdb1 /media/external -o uid=1000,gid=1000,utf8,dmask=027,fmask=137

The options following the “-o” allow your user to have ownership of the drive, and the masks allow for extra security for file system permissions. If you don’t use those extra options you may not be able to read and write the drive with your regular username.

Otherwise if the device is formatted with NTFS, run:

sudo mount -t ntfs-3g /dev/sdb1 /media/external

And you should be good to go, happily copying data to and from /media/external. When you are done and need to plug out the device, first unmount it using:

sudo umount /media/external

or:

sudo umount /dev/sdb1

Note that the unmount command will fail if your current working directory is in the /media/external path. You need to step out of the disk if you want to unmount it! :)

Related Links: https://help.ubuntu.com/community/Mount/USB, https://help.ubuntu.com/community/InstallingANewHardDrive

How to Delete a Folder using the Windows Command Line Software & Sites 30 MAY 2013

blue-folder-iconIf you find yourself stuck in the Windows Command line environment and have an itching desire to delete some of your folders, here is the command to do it: RMDIR.

If like me you are one of the older guys reading this, then you would probably have fingered the old (DOS) DELTREE as the command to use, but seeing as this was technically replaced ages ago, the correct answer is in fact RMDIR, which is responsible for removing a directory (and with switches, an entire directory tree, folders, files and all!).

Given a folder called ‘annoying’, you can banish it by running:

rmdir c:\annoying

Of course this will fail if ‘annoying’ isn’t empty. To get around this and delete the entire directory tree, in other words a recursive file and folder delete, we employ the /s switch:

rmdir /s c:\annoying

And if we don’t want to be prompted or bothered again by what is about to happen, we force the command into quiet mode with the /q switch:

rmdir /s /q c:\annoying

Nifty.

Related Link: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/rmdir.mspx

How to Create a Zend Framework Project that Uses Modules CodeUnit 01 APR 2011

If your website can be logically split into a number of different functionalities, it makes sense to group those functionalities accordingly. In Zend terminology we are talking about modules, literally the folder splitting of logically grouped pieces of functionality. However, by default a generated Zend Framework project isn’t modular and to get the thing properly modularized, here’s what you have to do.

Using Zend Framework 1.11.4:

First, create your project like you normally would via the command line interface:

zf create project moduleproject
cd moduleproject

Next, create your default module. This will house module that will handle all requests to the root of your site, in other words http://moduleproject/helloworld or http://moduleproject/

zf create module default

Now add the all important index and error controllers:

zf create controller Index index-action-included[=1] default
zf create controller Error -m default

Replace the contents of the generated error controller with the following contents: (c:moduleprojectapplicationmodulesdefaultcontrollersErrorController.php)

class Default_ErrorController extends Zend_Controller_Action
{

    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');
        
        if (!$errors || !$errors instanceof ArrayObject) {
            $this->view->message = 'You have reached the error page';
            return;
        }
        
        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $priority = Zend_Log::NOTICE;
                $this->view->message = 'Page not found';
                break;
            default:
                // application error
                $this->getResponse()->setHttpResponseCode(500);
                $priority = Zend_Log::CRIT;
                $this->view->message = 'Application error';
                break;
        }
        
        // Log exception, if logger available
        if ($log = $this->getLog()) {
            $log->log($this->view->message, $priority, $errors->exception);
            $log->log('Request Parameters', $priority, $errors->request->getParams());
        }
        
        // conditionally display exceptions
        if ($this->getInvokeArg('displayExceptions') == true) {
            $this->view->exception = $errors->exception;
        }
        
        $this->view->request   = $errors->request;
    }

    public function getLog()
    {
        $bootstrap = $this->getInvokeArg('bootstrap');
        if (!$bootstrap->hasResource('Log')) {
            return false;
        }
        $log = $bootstrap->getResource('Log');
        return $log;
    }


}

Next create an error view that will be used by Error controller: (c:moduleprojectapplicationmodulesdefaultviewsscriptserrorerror.phtml)

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Zend Framework Default Application</title>
</head>
<body>
<h1>An error occurred</h1>
<h2><?php echo $this->message ?></h2>

<?php if (isset($this->exception)): ?>

<h3>Exception information:</h3>
<p>
<b>Message:</b> <?php echo $this->exception->getMessage() ?>
</p>

<h3>Stack trace:</h3>
<pre><?php echo $this->exception->getTraceAsString() ?>
</pre>

<h3>Request Parameters:</h3>
<pre><?php echo $this->escape(var_export($this->request->getParams(), true)) ?>
</pre>

<?php endif ?>

</body>
</html>

Finally, add the following line in the production section of your application.ini file: (c:moduleprojectapplicationconfigsapplication.ini)

resources.modules[] =

Set your environment so that errors are display and then first hit your project URL to make sure it is showing up correctly, i.e. http://moduleproject/. Next, hit a non-existent URL like http://moduleproject/fail and look at the resulting error page. If the request parameters reads array( … ‘module’ => default’ … ) then you’re finished.

You now have a completely modularized project, which you can add to by running

zf create module module2
zf create controller index -m module2

Nifty.

How to Create a Zend Project from the Command Line with zf Tips, Tricks and Tutorials 16 MAR 2011

To generate an empty project shell using the Zend Framework is pretty easy thanks to the powerful zf command line utility.

To create a project, simply open a command line window, browse to the directory in which you want to create your Zend Framework project and enter:

zf create project "My Project"

zend-zf-logowhere My Project is the name of the project you want to generate. Note that for project names containing spaces, you can make use of double quotes to enclose. Also, zf (or rather the Zend bin directory) should be added to your system PATH in order to give it global visibility and thus make it easier to use.

The program will create a directory matching the name of your given project, and populate it with all the necessary Zend shell structures. You should at a minimum have application, docs, library, public and tests folders in the root, as well as a .zfproject.xml file. In the public folder, check that there is a .htaccess file containing the following rules:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Finally, you need to either symlink the library folder to that of the installed Zend framework’s library folder on the system, or just copy the Zend framework library folder’s contents into the library folder of your new project directory.

Done.

How to Start or Stop MySQL Server on Ubuntu via the Command Line CodeUnit 07 JUL 2010

To stop a MySQL server instance on an Ubuntu linux install via the command line is as simple as entering:

sudo /etc/init.d/mysql stop

Alternatively, to start a MySQL server instance you can simply submit a start command like so:

sudo /etc/init.d/mysql start

Incidentally, if you want to check on the status of a currently running MySQL server instance, you can make use of the status switch:

sudo /etc/init.d/mysql status

Oh, and if you want to install MySQL on the ubuntu machine, simply make use of the usual apt-get suspect and enter:

sudo apt-get install mysql-server

Useful little things to remember if you are working in a terminal only environment, don’t you think? :P

Ubuntu Terminal: How to Quickly Create a SQL Dump File from a MySQL Database CodeUnit 05 JUL 2010

Backing up your MySQL database or generating a copy of it to shift around is quite a simple affair thanks to the powerful mysqldump command that ships with MySQL.

To generate a backup sqldump, simply execute:

mysqldump -h localhost -u [MySQL user, e.g. root] -p[database password] -c --add-drop-table --add-locks --all --quick --lock-tables [name of the database] > sqldump.sql

Note the lack of a space between -p and the password! Obviously if you don’t have a password assigned, simply omit the -p switch.

And that is it, all done! :)

Note, restoring a database from a mysqldump is as simple as: mysql -u [MySQL user, e.g. root] -p[database password] < sqldump.sql

Ubuntu Terminal: How to Quickly GZip a File CodeUnit 01 JUL 2010

File archiving is a particularly simple affair and there are quite a few different archive algorithms to pick and choose from. GZip (.gz) has for long been associated with Linux as one of its main archiving algorithms and so today’s quick command line tip highlights how to quickly create a zipped file on your system.

Simply enter the following to gzip your file:

gzip [filenameToZip] -c -v > [zippedFileName]

Conversly, to unzip a file is as simple as entering:

gunzip [zippedFileName] -c -v > [unzippedFileName]