Terminal Commands – Part 3

This post follows up on the previous 2 posts. Here we will look at some advanced commands. Note that this is by no means a comprehensive list. You can visit the online version of the man pages: Apple Man Pages

Here are the links for the previous posts.

Terminal Commands – Part 1

Terminal Commands – Part 2

The commands are explained with some common tasks in mind. Some of the steps are there to illustrate the usage of the commands. To find out other tasks that can be performed using these commands simply refer to the man pages.

FILE SYSTEM

diskutil

The diskutil command is a handy tool to run disk utility via the terminal. A full list of tasks that can be executed are available via the man command.

Example:

There could be situations where you have encrypted your USB drive & have forgotten the password for the same. While there is no way to retrieve the data, it is still possible for you to use the USB disk. Let’s use the diskutil command to do this.

– Launch terminal

– Make sure that the USB is properly connected

– Run the command diskutil cs list

– This lists all the core-storages that are connected to your system.

– Next to the Logical Volume Group select the alphanumeric id & copy it (make sure you select the correct logical volume group).

– Type the command diskutil cs delete <id>

– Replace the id with the alphanumerics id you copied earlier.

– This will completely remove the encrypted partition. As mentioned earlier you will loose all the data that is already there on the partition.

diskutil man page

fsck

File System Check command. This command is used to check different Filesystems by invoking the corresponding sub command.

fsck man page

hdiutil

hdiutil is used to perform some other tasks related to storage devices. A good example of this is the creation of different kinds of disk images.

Example:
Let us create a disk image for the ~/Documents directory

– Launch the terminal application

cd ~/

mkdir ImageDemo

hdiutil create -srcfolder ImageDemo ImageDemo.dmg

Apart from the above example, there are a lot of other tasks that can be performed using hdiutil. For full information run the man command.

hdiutil man page

mount

The mount command is used to mount a volume via the terminal. A volume can be mounted as a Read-Write or a read only. For full details on the functionality run the man mount command

Syntax: mount <options> <volume location>

mount man page

GETTING INFORMATION RELATED TO THE SYSTEM & FILES

uptime

Shows how long the system has been running.

uptime man page

ioreg

Get information out of the io registry.

Example:
Suppose we want to get information about the serial number. We would use the ioreg command.

– launch terminal

cd ~/Documents

ioreg -l | grep “IOPlatformSerialNumber”

Optionally you can pipe the information to a file & read it later.

ioreg man page

system_profiler

Used to get system related information. it can generate a small or a detailed report depending on what option is used. For full information access the man pages for the command.

system_profiler man page

top

Displays information about the various processes running within the system including the usage 7 state. To get more information about the full functionality visit the man pages.

top man page

METADATA

mdls

Used to get the metadata for a given file or folder. The data is displayed on the screen.

mdls man page

mdutil

Manages spotlight search indexes.

mdutil man page

NETWORKING

networksetup

This command is used to access the information that is found within the System Preferences > Network Preferences pane.

You can use this command to do some quick command line configuration of the network settings.

A good example is to manually configure the settings while booted in the OS X Recovery partition. Here is an Apple Support Document which talks about the same.

http://support.apple.com/kb/HT5034?viewlocale=en_US

networksetup man page

MISCELLANEOUS

tar

Used to compress file(s) into a single tar file or decompress.

Example:

This example demonstrates how to use the tar command.

– Launch terminal

cd ~/Documents

mkdir Docs

cd Docs

echo “A” | cat > file1

echo “A” | cat > file2

echo “A” | cat > file3

echo “A” | cat > file4

Now to compress all the files

tar -cvf compressedFiles.tar file*

To uncompress them all

tar -xvf compressedFiles.tar

tar man page

tmutil

Manage Time machine from the terminal. Useful command to manage time machine from the command line.

tmutil man page

fdesetup

Used to mange file-vault from the command line

fdesetup man page

Terminal Commands for OS X – Part 2

Continuing from the previous post on.

RENAMING FILES & FOLDERS
The way files/folders are renamed is by using the mv command. In the mv command make sure that the destination folder is the same as the source folder for your target, its just the target name that changes.

So if we have a folder called Documents & inside it we have a folder called Files. To rename Files to OfficeFiles we run the following command.

mv Files OfficeFiles

MODIFYING PERMISSIONS
Top modify the basic UNIX or POSIX permissions on a Mac we need to use the chmod command. The standard permissions apply to Users, Group & Everyone else. Each of these entities has 3 flags assigned to it: rwx Read-Write-Execute. Each flag is a boolean flag holding either true or false, indicated by 1 or 0.

So for example if we wanted to modify the permissions of the OfficeFiles folder to be read-write only for the user & read only for group & everyone else then the command would need the following information.
User: rwx = 110 -> 6
Group: rwx = 000 -> 0
Everyone else: rwx = 000 -> 0

So the command would look like: chmod 600 OfficeFiles
FOLDER PATHS & NAVIGATING FOLDERS
A good understanding of the folder structure within a Mac is necessary while dealing with terminal commands.
All folders with the Mac begin at root indicated by ‘/’
Root contains the following folders
Applications
Library
Systems
Users

rootFolderMost of the work that is done is done within the Users folder. In most cases users would not need to go to the other folders for their day to day work.

homeFolder

As you can see from the screenshots, the terminal shows more folders than are visible through finder.

rootFolderInTerminal

homeFolderInTerminal

Within the Users folder all the Home Folders for the different users on the machine are listed. Again, users typically have access only to their own login folder.

Each users Home Folder contains the following Folders
Documents
Downloads
Music
Pictures
Public
Desktop

Depending on your usage you may see a different view from the one shown below.

The following are some examples of navigating the File System.

1)Accessing the root folder

cd /

2)Accessing the home folder. Example home folder called admin

cd /Users/<home folder name>

cd /Users/admin

or cd ~/

NOTE: the ‘~/’ is a shortcut for accessing the home folder directly. Using the shortcut access will only be given to the home folder for the user currently logged in.

3)To access the OfficeFiles folder

cd ~/Documents/OfficeFiles

or

cd /Users/admin/Documents/OfficeFiles
EDITORS
There are a number of built in editors available within the Mac. Apart from TextEdit, which is a GUI based editor, there are many editors available for direct use from the terminal too.

Emacs:
Emacs is a basic text editor that is built into the mac. There are various versions available but those may not be built in. You may need to download them manually.

Here are some common emacs commands to perform operations. For an even bigger list visit http://www.cse.iitb.ac.in/~br/courses/cs699-autumn2013/refs/emacs-commands2.html

http://www.gnu.org/software/emacs/manual/html_mono/emacs.html#Commands

Vi:
This is yet another editor that is built into most UNIX like OS. This is the editor that is used when running the less or more commands.

Here are some common commands used in Vi.
http://www.tutorialspoint.com/unix/unix-vi-editor.htm

Apart from this there are other editors such as gedit & xemacs which has a GUI interface.

NETWORKING RELATED TERMINAL COMMANDS
1)ping
Used to test connectivity to a particular IP address
ping http://www.google.com

2)traceroute
Used to check the hop trace between your machine & destination
traceroute http://www.google.com

3)ipconfig
Used to get network interface related information
ipconfig getoption en1 <option>
There is a lot more information that can be gleaned using ipconfig. For a full list run the man command for ipconfig

4)ifconfig
Used to configure ifnormation related to network interface
ifconfig en0 inet <ip address> netmask <subnet mask>

5)lookup
There are different ways to get the forward & reverse lookup to happen
nslookup <domain name>
nslookup <ip address>

dig <domain name>
dig -x <ip address>
NOTE: Please use the man command to get more information.

Terminal Commands for OS X – Basic

This is the first part of the Terminal Commands topic. This article covers the basic commands which a user can use on the terminal.
To launch the terminal application simply navigate to /Applications/Utilities/Terminal. Alternatively, you can even search for the same using spotlight.

cd
This command is used to change the current directory we are. So if we want to navigate to a new folder we simply run the cd command.
Syntax:  cd <folder path>
Note that the folder path has to be the absolute path of the folder. Beginning from root. If you simply place the name for the folder, the OS is going to search for that folder within the current directory. The command won’t work if it doesn’t find the specified folder.

ls
This command is used to list the contents of the current directory.
Syntax: ls or ls <folder name>
There are a lot of switch based options available to get more detailed results.
-a shows hidden files
-l shows in a list format with more information
-r oldest entries first
-t most recently modified entries first
View the manual for more switches.

rm
This is the remove command. This command is used to remove one or more than one files &/or folders from the specified directory.
Syntax: rm <folder name>
To remove folders we need to use the -r switch.
NOTE: The rm command should be run with caution. Running the above command does not move the contents to trash. There is no way to undo the rm command. Also care must be given to the folder from which the command is run, make sure you are in the folder you wish to be in before running this command.

pwd
Present Working Directory. This command tells us the directory we are currently in.
Syntax: pwd

cp
This command is used to copy the specified file or folder to a specified location.
Syntax: cp <source file> <destination folder>
In order to copy folders we need to use the -r switch.

mv
This command is used to move files or folders to a specified location.
Syntax: mv <source file/folder> <destination folder>
This command can also be used to rename files & folders by giving a different name but keeping the destination the same. The destination folder is replaced with new name.

less
This command is used to display the contents of a file.
Syntax: less <name of file>
This command displays the contents of a file in simple text. It displays the content in a page by page format. To stop viewing the file simply type ‘q’.

chmod
This command is used to modify the ACLs of a specified file or folder.
Syntax: chmod <rwx-rwx-rwx> <file or folder name>
The rwx indicate read-write-execute permissions for the owner-group-everyone else. The permissions are given by either indicating 1 or 0 in place of each rwx. 1 indicating true, 0 indicating false. The resulting binary numbers should be replaced by their octal equivalents. So to give only the owner rwx permission on a file the command would need 111-000-000 which is 700, so the command would look like chmod 700 <file/folder name>. If we wanted to give rw permission to owner & r permission for group & everyone else then the command would look like 110-100-100 or 644, chmod 644 <file/folder name>.

mkdir
This command is used to create a directory in the current working directory.
Syntax: mkdir <directory/folder name>
This will create a directory in the present working directory. Do keep track of the current directory before creating a new one, to make sure you are creating it in the correct directory.

sudo
Super User Do.
Syntax: sudo <command to be executed by super user>
This command is used as a prefix before other commands when we want those commands to be executed as a super user (aka root user). You are required to authenticate as an administrator for the command to work. NOTE: Do exercise caution while using the sudo command. Root users don’t have the built is permission checks & security checks. Improper usage of sudo may leave your machine in an unusable state.

man
Terminal command manual.
Syntax: man <terminal command>
This command is used to open the manual for the different commands that are available within the system. It is a good starting point to understand the full functionality of the different commands along with examples of usage.

cat
The cat command is used to perform 3 different tasks: Display text files, copy text files, combine text files, create new text files.
Display Text Files
Syntax: cat <file name>
This will display the text files on the screen.

Copy Text Files
Syntax: cat <first file name> > <second file name>
This will copy the contents of the first file to the second file using the redirect ‘>’ operator.

Combine Text Files
Syntax: cat <first file name> <second file name> > <third file name>
This will combine the contents of the 2 files & save it in the third file.

Create New Files
Syntax: cat > <filename>
This will create a new file.

echo
Display given sentence on the screen.
Syntax: echo <sentence>

grep
Used to find a particular string within a file
Syntax: grep <string pattern> <file name>
This will look for the given string pattern in the specified file. You can use different switch options to modify your result. View the man pages for the same.

find
The find command is used to find files within the system.
Syntax: find <search path> <search criteria> <name of the file> <operation to perform>
Search path – specifies the folder where we want to search
Search Criteria – specifies what to search eg: name
Name of File – name of file to search
Operation to perform – how to show the results

Sign PDF Documents in Preview on a Mac

One often encounters a situation where we would like to sign a document that we have received over email & send it across back. Or it may just be the case that we have created a PDF document & now need to sign it & send it back. This post illustrates how we can do this without printing the document.

This feature is built into the ‘Preview’ application. There may be other applications that do this, but the advantage that ‘Preview’ has over other applications is that it is built into the OS.

The first step is to create a whole new signature that is saved with ‘Preview’

  1. Open the ‘Preview’ application.
  2. Launch the preferences window. This can be done using the comma keys or by clicking on Preview > Preferences in the toolbar, which is located at the topmost corner of the screen.1
  3. Click on the signatures tab.2
  4. Click on the create signature button.3
  5. You will see a window for capturing the signature that comes up. This window turns on the built-in iSight camera for capturing the signature.4
  6. Sign the signature you want on a blank white paper. Hold the white paper in such a way that the signature appears just above the white line. You should see a preview in the signature preview window.7
  7. Once you are satisfied with the signature preview click the accept button. You should see your signature listed in the signature tab. More signatures can be added if needed.9

Thats it. Now you have successfully added a signature to the ‘Preview’ application.

Now that we have added the signature lets use it.

  1. Open a PDF document in ‘Preview’.5
  2. In the toolbar located at the top of the screen click Tools > Annotate > Signature. A new toolbar will appear.6
  3. Click on the blue ‘S’ located on the toolbar. Select the signature you want, in case you have multiple signature.
  4. Drag the crosshair arrow at the place where you want the signature. You will see your signature come up. You can fine-tune the location & size of the signature by dragging the edges or moving the image with the mouse.
  5. Once you are done. Save the document.8

Done! You have now successfully signed a PDF document. You can now do this on any other document you wish. Once you have added a signature to the ‘Preview’ application you can use it again & again.

To use Interface Builder or not to use Interface Builder…

A lot of students who come to learn iOS App Development ask me this question. There are a lot of people who don’t even know that there is another way to develop apps. For those who are new to app development let us have a look at 2 approaches towards app development.

Interface Builder: Interface Builder is the mechanism for making an iOS App by simply dragging different view elements from the side bar & dropping them on to your app screen.

Screen shot of Interface Builder in Action

Screen shot of Interface Builder in Action

T

his way the developer can immediately see how the app is going to look without running a simulation. The GUI based design makes it very easy to configure the view components to your need very quickly. Remember that just because you choose to develop your app using Interface Builder doesn’t mean that you won’t have to write a single line of code. Far from it, you will still have to write code to get your app working.

Programatic Approach: The other approach is to make every thing on the fly. The developer writes code that is required to display the desired view components.

Screen shot of a programatic approach to making apps.

Screen shot of a programatic approach to making apps.

The view components are also configured in the program itself. In this approach the Interface Builder is not used at all.

Now for the million dollar question. Which is better? The thing is that it basically depends on what your end goal is.  If the app is a very simple app or a demonstrator of possible future apps/ideas, then it might be a good idea to use Interface Builder. However, if you wish to have an extremely high degree of control over your app & be able to do some really fancy stuff then you might want to consider the programatic approach.

Typically apps which require a higher degree of precision over the layout or performance would require many view components to be rendered using code. Games would be a good example of such a situation. However, if that is not the criteria then one can design using Interface Builder. This is not to say that apps developed using Interface Builder are less efficient but programming the view does give the developer a higher level of control.

In the end it all boils down to what you feel more comfortable with. People from a strong programming background may prefer to code it all. Hence, the focus shouldn’t be on which approach is better, it should be on how can I get the best possible app on the store.

Things to keep in mind while making mobile apps

Carrying on from an earlier post on Getting started with iOS App Development. Here are a few things to keep in mind while making mobile apps (or any software ).

  1. Resources: It is up to you the developer to get the resources required for your app. By resources I mean all artwork, images, documents, audio files that may be required as a part of your app. These resources have to be your own & not borrowed from google. Basically, you should own the rights to the resources.
  2. Marketing: Its a good idea to make your own app. But you also need to think about marketing. Come up with ways to spread the message about the app.
  3. Feedback: This comes a little later in the app dev cycle. But it is equally important. Make sure you get as many family members & friends as possible to give you a straight & honest feedback about your app. This will help you make some quick fixes or introduce new features you didn’t think about earlier .
  4. Devices: Once you are ready & satisfied with the simulations on the mac start testing the app on a real device. Depending on your app you may want to test on multiple devices with different versions of the OS installed on them. This can be handy if you want to target multiple devices & would like to cover maximum number of users. It could also be possible that the features you are using are not OS specific, in that case you may want to test your app on as many different versions as possible.
  5. Branding: This could also fall under the marketing section. Think of a catchy name for your app. Something that would cause a casual browser of apps to look at your app in further detail.
  6. Attention to detail: A very important point. Here is a link to an article I wrote about earlier. Attention to Details

Getting started with iOS App Development

A lot of people ask me about what all is required to make an app in iOS. There is a lot of documentation around which discusses what I am about to talk about, but I felt there was a need for a workflow which handled all the questions that come up.

This is a brief overview of how the whole thing works.

  • Sign up for the iOS Developer program.
  • Design & Test your app.
  • Publish your app to the iTunes store.

Thats all. Now lets get into the specifics of all those steps.

MAKING AN APP:

First & foremost, you DO NOT need to sign up for the developer program TO START developing. You can start making app with a free developer account. You need the paid version to test you app on a real device & for distributing your app on the app store.

Now that we have got that part cleared out. Lets move on to make an app. There are a few things you need to have with you before you begin

Mac OS X  You need a Mac computer with preferably the latest OS installed.

Screen Shot 2013-04-01 at 12.03.55 PM The next thing you need is Xcode. Xcode is an IDE which we use to design our apps. It is free to download from the Mac App Store.

Thats it. Thats all you need to get started.

Now before you start coding, there are a few things to look into. A successful app needs 2 things a great idea backed up with brilliant execution. Start of by thinking of what might really help the end user. Remember people will only download your app if it appeals to them or if it helps them in their day-to-day life.

Once you have the idea then you can move onto the next step which is the planning & scripting step. This is where you start thinking about the specifics of the app. What color combination will you use? Will the app require an internet connection? Will it support multitouch? Will there be a theme to the different view components?

Scripting is where you lay down the rules as to the flow of your app. It is often referred to as storyboarding. This is where you will draw the app & get the first look on how it should flow, the orientation of the buttons.

Having done this we are now ready to start coding. This is an iterative process. You will at this point have to test it frequently. It would also be a good idea to get a preliminary feedback from friends & family. This process will continue until you & your family/friends feel comfortable with your product.

DISTRIBUTING AN APP:

This is where things get a little murky for users. Once you have made the app you are ready to test it on a device & put it on the iTunes store. To do this we now have to sign up for the developer program.

So what is a developer program? A developer program is basically a membership to an online portal which enables you to do a lot of post coding steps. Here are some of them.

Testing – In order to test your app on devices you need to files a provisioning profile & a distribution profile. You can create these documents on the portal.

Distribution – To distribute your app on the iTunes store you need a distribution provisioning profile along with a distribution certificate. Also, there is another portal where you can upload your app to Apple servers for distribution.

DEVELOPER PROGRAM:

This brings us to the question, Which developer program should I enroll for? or Which Developer program am I eligible for. There are 3 programs available: iOS Developer Program, iOS Developer Enterprise Program, iOS Developer University Program.

iOS DEVELOPER PROGRAM:

This is a basic developer program. It costs $99 a year. Once you enroll for this program you can test apps on devices & upload apps onto the iTunes store. This program is ideal for individuals & small businesses.

 icon_enterprise_callout  iOS DEVELOPER ENTERPRISE PROGRAM:

This is the enterprise version of the program. It costs $299 a year. Once you enroll for this program you can test apps you develop on different devices & distribute apps within your enterprise. Note you cannot upload apps onto the iTunes Store, this program is for internal deployment only or in other words this is to enable you to make apps for you own employees. To be eligible for this program your company needs to have a D-U-N-S number. If your company does not have a D-U-N-S number then you can either apply to have one or opt for the basic iOS Developer Program.

https://developer.apple.com/ios/enroll/dunsLookupForm.action

You could also look up your D-U-N-S number with the link above to see if your company has a D-U-N-S number. You would also require the contact details of a person who has the authority to approve this enrollment.

icon-university-callout  iOS DEVELOPER UNIVERSITY PROGRAM:

This program has been designed mainly for Universities who want to introduce iOS Development as a part of their curriculum. The program is available for free. Again, just like the Enterprise Program, here to you need the contact details of a person who has the authority to approve this enrollment.

————————–

Once you have decided upon & enrolled into a developer program, all you have to do is to test your app on as many different devices with as many different versions of OS possible (depends on you app specifications & requirements). Then just go ahead & distribute your app via the iTunes Store.

C++ in iOS – 2

Continuing from the previous post. This one will look into a working example for the same. The code used here is pretty trivial. It is organized in the following sets of files. A c++ header file which contains the declaration of a class. A c++ implementation file (.cpp) where the member functions are implemented. An Objective-C++ header file which holds the C wrapper struct & an Objective-C wrapper object. An Objective-C++ implementation file (.mm) which implements the C struct & all the member functions for both the C struct as well as the Objective-C class.

CppStruct.h


#include <string>
class MyObject
{
     public:
          std::string getName();
          void setName(std::string tempName);
          MyObject();
      private:
           std::string name;
 };

CppStruct.cpp

#include "CppStruct.h"
#include <string>
#include <iostream>

std::string MyObject::getName()
{
     return name;
}

void MyObject::setName(std::string tempName)
{
     name = tempName;
}

MyObject::MyObject()
{
     name = "NIL";
}

CppStructWrapper.h

struct PersonWrapper;

@interface CppStructWrapper : NSObject
{
     struct PersonWrapper *obj;
}

-(void) makeAPerson;
-(void) setName:(NSString *) personName;
-(NSString *) getName;
@end

CppStructWrapper.mm

#import "CppStructWrapper.h"
#include "CppStruct.h"
#include <string>

@implementation CppStructWrapper

struct PersonWrapper
{
     MyObject *personObj;
     std::string getName();

     void setName(std::string tempName);
     PersonWrapper();
};

std::string PersonWrapper::getName()
{
     return personObj->getName();
}

void PersonWrapper::setName(std::string tempName)
{
     personObj->setName(tempName);
}

PersonWrapper::PersonWrapper()
{
     personObj = new MyObject;
}

-(id) init
{
     self = [super init];
     if(self)
     {
          obj = nil;
     }
     return self;
}

-(void) makeAPerson
{
     obj = new PersonWrapper;
}

-(void) setName:(NSString *) personName
{
     std::string temp([personName UTF8String]);
     obj->setName(temp);
}

-(NSString *) getName
{
     NSString *str = [[NSString alloc] initWithUTF8String:obj->getName().c_str()];
     return str;
}

@end

ViewController.m

//this code could be anywhere I have put it inside the ViewController.m within the init message.
#import "ViewController.h"
#import "CppStructWrapper.h"

-(id) init
{
     self = [super init];
     if(self)
     {
          CppStructWrapper *obj = [[CppStructWrapper alloc] init];
          [obj makeAPerson];
          [obj setName:@"ABC"];
          NSString *str = [obj getName];
          NSLog(@"%@",str);
     }
     return self;
}