Tuesday, July 23, 2013

svn some commandlines switches


1. to preserve check-in date when checkout:

svn checkout --config-option config:miscellany:use-commit-times=yes

2. in jenkins, to check out several directories in different places:


Assuming you're using Subversion to checkout your projects, you need to specify the "Local module directory" to something other than the default for each path you are checking out.
For example;
If you have svn://myrepo/myproject/plugins and svn://myrepo/myproject/tests, the configuration would be along the lines of;
Modules:
Repository URL : svn://myrepo/myproject/plugins
Local module directory (optional) : plugins

Repository URL : svn://myrepo/myproject/tests
Local module directory (optional) : tests
This would then inform Jenkins that it has two paths to checkout and into separate locations.
If you are trying to checkout a project into the subfolder of another working copy, you may have to use svn:externals on the parent directory.
3. for svn error "svnsync failed to get lock on destination repos currently held by user ..." it had to delete the lock in order to make it work again "svn propdel --revprop -r0 svn:sync-lock file:///var/www/svn/repository-1 "

Tuesday, July 16, 2013

MySQL Commands

http://www.pantz.org/software/mysql/mysqlcommands.html

Below when you see # it means from the unix shell. When you see mysql> it means from a MySQL prompt after logging into MySQL.

To login (from unix shell) use -h only if needed.

# [mysql dir]/bin/mysql -h hostname -u root -p

Create a database on the sql server.

mysql> create database [databasename];

List all databases on the sql server.

mysql> show databases;

Switch to a database.

mysql> use [db name];

To see all the tables in the db.

mysql> show tables;

To see database's field formats.

mysql> describe [table name];

To delete a db.

mysql> drop database [database name];

To delete a table.

mysql> drop table [table name];

Show all data in a table.

mysql> SELECT * FROM [table name];

Returns the columns and column information pertaining to the designated table.

mysql> show columns from [table name];

Show certain selected rows with the value "whatever".

mysql> SELECT * FROM [table name] WHERE [field name] = "whatever";

Show all records containing the name "Bob" AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name = "Bob" AND phone_number = '3444444';

Show all records not containing the name "Bob" AND the phone number '3444444' order by the phone_number field.

mysql> SELECT * FROM [table name] WHERE name != "Bob" AND phone_number = '3444444' order by phone_number;

Show all records starting with the letters 'bob' AND the phone number '3444444'.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444';

Show all records starting with the letters 'bob' AND the phone number '3444444' limit to records 1 through 5.

mysql> SELECT * FROM [table name] WHERE name like "Bob%" AND phone_number = '3444444' limit 1,5;

Use a regular expression to find records. Use "REGEXP BINARY" to force case-sensitivity. This finds any record beginning with a.

mysql> SELECT * FROM [table name] WHERE rec RLIKE "^a";

Show unique records.

mysql> SELECT DISTINCT [column name] FROM [table name];

Show selected records sorted in an ascending (asc) or descending (desc).

mysql> SELECT [col1],[col2] FROM [table name] ORDER BY [col2] DESC;

Return number of rows.

mysql> SELECT COUNT(*) FROM [table name];

Sum column.

mysql> SELECT SUM(*) FROM [table name];

Join tables on common columns.

mysql> select lookup.illustrationid, lookup.personid,person.birthday from lookup left join person on lookup.personid=person.personid=statement to join birthday in person table with primary illustration id;

Creating a new user. Login as root. Switch to the MySQL db. Make the user. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO user (Host,User,Password) VALUES('%','username',PASSWORD('password'));
mysql> flush privileges;

Change a users password from unix shell.

# [mysql dir]/bin/mysqladmin -u username -h hostname.blah.org -p password 'new-password'

Change a users password from MySQL prompt. Login as root. Set the password. Update privs.

# mysql -u root -p
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere');
mysql> flush privileges;

Recover a MySQL root password. Stop the MySQL server process. Start again with no grant tables. Login to MySQL as root. Set new password. Exit MySQL and restart MySQL server.

# /etc/init.d/mysql stop
# mysqld_safe --skip-grant-tables &
# mysql -u root
mysql> use mysql;
mysql> update user set password=PASSWORD("newrootpassword") where User='root';
mysql> flush privileges;
mysql> quit
# /etc/init.d/mysql stop
# /etc/init.d/mysql start

Set a root password if there is on root password.

# mysqladmin -u root password newpassword

Update a root password.

# mysqladmin -u root -p oldpassword newpassword

Allow the user "bob" to connect to the server from localhost using the password "passwd". Login as root. Switch to the MySQL db. Give privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> grant usage on *.* to bob@localhost identified by 'passwd';
mysql> flush privileges;

Give user privilages for a db. Login as root. Switch to the MySQL db. Grant privs. Update privs.

# mysql -u root -p
mysql> use mysql;
mysql> INSERT INTO db (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,Create_priv,Drop_priv) VALUES ('%','databasename','username','Y','Y','Y','Y','Y','N');
mysql> flush privileges;

or

mysql> grant all privileges on databasename.* to username@localhost;
mysql> flush privileges;

To update info already in a table.

mysql> UPDATE [table name] SET Select_priv = 'Y',Insert_priv = 'Y',Update_priv = 'Y' where [field name] = 'user';

Delete a row(s) from a table.

mysql> DELETE from [table name] where [field name] = 'whatever';

Update database permissions/privilages.

mysql> flush privileges;

Delete a column.

mysql> alter table [table name] drop column [column name];

Add a new column to db.

mysql> alter table [table name] add column [new column name] varchar (20);

Change column name.

mysql> alter table [table name] change [old column name] [new column name] varchar (50);

Make a unique column so you get no dupes.

mysql> alter table [table name] add unique ([column name]);

Make a column bigger.

mysql> alter table [table name] modify [column name] VARCHAR(3);

Delete unique from table.

mysql> alter table [table name] drop index [colmn name];

Load a CSV file into a table.

mysql> LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);

Dump all databases for backup. Backup file is sql commands to recreate all db's.

# [mysql dir]/bin/mysqldump -u root -ppassword --opt >/tmp/alldatabases.sql

Dump one database for backup.

# [mysql dir]/bin/mysqldump -u username -ppassword --databases databasename >/tmp/databasename.sql

Dump a table from a database.

# [mysql dir]/bin/mysqldump -c -u username -ppassword databasename tablename > /tmp/databasename.tablename.sql

Restore database (or database table) from backup.

# [mysql dir]/bin/mysql -u username -ppassword databasename < /tmp/databasename.sql

Create Table Example 1.

mysql> CREATE TABLE [table name] (firstname VARCHAR(20), middleinitial VARCHAR(3), lastname VARCHAR(35),suffix VARCHAR(3),officeid VARCHAR(10),userid VARCHAR(15),username VARCHAR(8),email VARCHAR(35),phone VARCHAR(25), groups VARCHAR(15),datestamp DATE,timestamp time,pgpemail VARCHAR(255));

Create Table Example 2.

mysql> create table [table name] (personid int(50) not null auto_increment primary key,firstname varchar(35),middlename varchar(50),lastnamevarchar(50) default 'bato');
MYSQL Statements and clauses
ALTER DATABASE

ALTER TABLE

ALTER VIEW

ANALYZE TABLE

BACKUP TABLE

CACHE INDEX

CHANGE MASTER TO

CHECK TABLE

CHECKSUM TABLE

COMMIT

CREATE DATABASE

CREATE INDEX

CREATE TABLE

CREATE VIEW

DELETE

DESCRIBE

DO

DROP DATABASE

DROP INDEX

DROP TABLE

DROP USER

DROP VIEW

EXPLAIN

FLUSH

GRANT

HANDLER

INSERT

JOIN

KILL

LOAD DATA FROM MASTER

LOAD DATA INFILE

LOAD INDEX INTO CACHE

LOAD TABLE...FROM MASTER

LOCK TABLES

OPTIMIZE TABLE

PURGE MASTER LOGS

RENAME TABLE

REPAIR TABLE

REPLACE

RESET

RESET MASTER

RESET SLAVE

RESTORE TABLE

REVOKE

ROLLBACK

ROLLBACK TO SAVEPOINT

SAVEPOINT

SELECT

SET

SET PASSWORD

SET SQL_LOG_BIN

SET TRANSACTION

SHOW BINLOG EVENTS

SHOW CHARACTER SET

SHOW COLLATION

SHOW COLUMNS

SHOW CREATE DATABASE

SHOW CREATE TABLE

SHOW CREATE VIEW

SHOW DATABASES

SHOW ENGINES

SHOW ERRORS

SHOW GRANTS

SHOW INDEX

SHOW INNODB STATUS

SHOW LOGS

SHOW MASTER LOGS

SHOW MASTER STATUS

SHOW PRIVILEGES

SHOW PROCESSLIST

SHOW SLAVE HOSTS

SHOW SLAVE STATUS

SHOW STATUS

SHOW TABLE STATUS

SHOW TABLES

SHOW VARIABLES

SHOW WARNINGS

START SLAVE

START TRANSACTION

STOP SLAVE

TRUNCATE TABLE

UNION

UNLOCK TABLES

USE

String Functions
AES_DECRYPT

AES_ENCRYPT

ASCII

BIN

BINARY

BIT_LENGTH

CHAR

CHAR_LENGTH

CHARACTER_LENGTH

COMPRESS

CONCAT

CONCAT_WS

CONV

DECODE

DES_DECRYPT

DES_ENCRYPT

ELT

ENCODE

ENCRYPT

EXPORT_SET

FIELD

FIND_IN_SET

HEX

INET_ATON

INET_NTOA

INSERT

INSTR

LCASE

LEFT

LENGTH

LOAD_FILE

LOCATE

LOWER

LPAD

LTRIM

MAKE_SET

MATCH    AGAINST

MD5

MID

OCT

OCTET_LENGTH

OLD_PASSWORD

ORD

PASSWORD

POSITION

QUOTE

REPEAT

REPLACE

REVERSE

RIGHT

RPAD

RTRIM

SHA

SHA1

SOUNDEX

SPACE

STRCMP

SUBSTRING

SUBSTRING_INDEX

TRIM

UCASE

UNCOMPRESS

UNCOMPRESSED_LENGTH

UNHEX

UPPER

Date and Time Functions
ADDDATE

ADDTIME

CONVERT_TZ

CURDATE

CURRENT_DATE

CURRENT_TIME

CURRENT_TIMESTAMP

CURTIME

DATE

DATE_ADD

DATE_FORMAT

DATE_SUB

DATEDIFF

DAY

DAYNAME

DAYOFMONTH

DAYOFWEEK

DAYOFYEAR

EXTRACT

FROM_DAYS

FROM_UNIXTIME

GET_FORMAT

HOUR

LAST_DAY

LOCALTIME

LOCALTIMESTAMP

MAKEDATE

MAKETIME

MICROSECOND

MINUTE

MONTH

MONTHNAME

NOW

PERIOD_ADD

PERIOD_DIFF

QUARTER

SEC_TO_TIME

SECOND

STR_TO_DATE

SUBDATE

SUBTIME

SYSDATE

TIME

TIMEDIFF

TIMESTAMP

TIMESTAMPDIFF

TIMESTAMPADD

TIME_FORMAT

TIME_TO_SEC

TO_DAYS

UNIX_TIMESTAMP

UTC_DATE

UTC_TIME

UTC_TIMESTAMP

WEEK

WEEKDAY

WEEKOFYEAR

YEAR

YEARWEEK

Mathematical and Aggregate Functions
ABS

ACOS

ASIN

ATAN

ATAN2

AVG

BIT_AND

BIT_OR

BIT_XOR

CEIL

CEILING

COS

COT

COUNT

CRC32

DEGREES

EXP

FLOOR

FORMAT

GREATEST

GROUP_CONCAT

LEAST

LN

LOG

LOG2

LOG10

MAX

MIN

MOD

PI

POW

POWER

RADIANS

RAND

ROUND

SIGN

SIN

SQRT

STD

STDDEV

SUM

TAN

TRUNCATE

VARIANCE

Flow Control Functions
CASE

IF

IFNULL

NULLIF

Command-Line Utilities
comp_err

isamchk

make_binary_distribution

msql2mysql

my_print_defaults

myisamchk

myisamlog

myisampack

mysqlaccess

mysqladmin

mysqlbinlog

mysqlbug

mysqlcheck

mysqldump

mysqldumpslow

mysqlhotcopy

mysqlimport

mysqlshow

perror

Perl API - using functions and methods built into the Perl DBI with MySQL
available_drivers

begin_work

bind_col

bind_columns

bind_param

bind_param_array

bind_param_inout

can

clone

column_info

commit

connect

connect_cached

data_sources

disconnect

do

dump_results

err

errstr

execute

execute_array

execute_for_fetch

fetch

fetchall_arrayref

fetchall_hashref

fetchrow_array

fetchrow_arrayref

fetchrow_hashref

finish

foreign_key_info

func

get_info

installed_versions


last_insert_id

looks_like_number

neat

neat_list

parse_dsn

parse_trace_flag

parse_trace_flags

ping

prepare

prepare_cached

primary_key

primary_key_info

quote

quote_identifier

rollback

rows

selectall_arrayref

selectall_hashref

selectcol_arrayref

selectrow_array

selectrow_arrayref

selectrow_hashref

set_err

state

table_info

table_info_all

tables

trace

trace_msg

type_info

type_info_all

Attributes for Handles

PHP API - using functions built into PHP with MySQL
mysql_affected_rows

mysql_change_user

mysql_client_encoding

mysql_close

mysql_connect

mysql_create_db

mysql_data_seek

mysql_db_name

mysql_db_query

mysql_drop_db

mysql_errno

mysql_error

mysql_escape_string

mysql_fetch_array

mysql_fetch_assoc

mysql_fetch_field

mysql_fetch_lengths

mysql_fetch_object

mysql_fetch_row

mysql_field_flags

mysql_field_len

mysql_field_name

mysql_field_seek

mysql_field_table

mysql_field_type

mysql_free_result

mysql_get_client_info

mysql_get_host_info

mysql_get_proto_info

mysql_get_server_info

mysql_info

mysql_insert_id

mysql_list_dbs

mysql_list_fields

mysql_list_processes

mysql_list_tables

mysql_num_fields

mysql_num_rows

mysql_pconnect

mysql_ping

mysql_query

mysql_real_escape_string

mysql_result

mysql_select_db

mysql_stat

mysql_tablename

mysql_thread_id

mysql_unbuffered_query

Monday, July 15, 2013

FAQs: svn/maven/ant/elcipse/


Subversion FAQ:
http://subversion.apache.org/faq.html

maven technical FAQ
http://maven.apache.org/general.html

maven Eclipse FAQ
http://maven.apache.org/maven-1.x/plugins/eclipse/faq.html

maven ant FAQ
http://ant.apache.org/faq.html

maven ANT tasks FAQ
http://maven.apache.org/ant-tasks/

Eclipse FAQ
http://wiki.eclipse.org/index.php/Eclipse_FAQs














Continuous Integration with Jenkins and Xcode

http://grayunicorn.com/?p=91

Last week (15 November 2012) I gave a short talk on setting up a continuous integration environment with Jenkins at Melbourne Cocoaheads. This is pretty much the content, converted into a blog post. Some said afterwards they would like more detail on various parts, so here is the whole thing with the shell script at the end. I hope you find it useful. I have to give a lot of thanks to all the other bloggers who wrote about their own experiences in doing this and to Stack Overflow.

MOTIVATION

First up, why would you do this? There are two big problems that this setup solves. First and most broadly speaking, continuous integration solves the problem of a broken build where nobody really knows how it got broken, which change broke it or how long it has been like that. If you let your project get into that state then it will be a miracle if you ever deliver anything, dealing with this issue is a huge part of success when working in a team. Because the build is performed every time anyone submits to the repository you will know right away that there is a problem and you can fix it right away. You can also apply some appropriate penalty to the person that did it – they can buy the team a coffee or something,pour encourager les autres1.
Secondly and more closely tied in with iOS development is that you can have your automated build sign and deploy a build so that anyone can point their iOS device at your distribution server with mobile Safari and have it install your build using Over The Air (OTA) provisioning. This is a feature of iOS available since release 4. You, the developer, will no longer have to deal with Important People tapping you on the shoulder asking for a build – you can direct them to your server. Remote testers can easily grab a build too.
There are some services that do this for you. Two I know of are Hockey and Testflight but this article deals with neither. They work well and provide a lot of extra features, particularly around bug and tester management, but it’s good to know what’s going on underneath. When you’ve done this setup you may choose to move on to one of those services for those extra features.

BUILD ON SUCCESS

Before getting started with this process, make sure you can do a successful Archive build in your regular work environment. If you can’t then it isn’t going to be any easier attempting to do it headless and automatically. That means all private keys, developer certificates, provisioning profiles and Xcode functioning together happily – sometimes this is not a trivial task. As a little refresher, here’s how all the developer pieces come together in code signing.
Screen Shot 2012 11 22 at 1 40 59 PM

VIRTUALLY RISK-FREE

Having configured Jenkins and OTA provisioning once or twice before I hesitated to install Jenkins and jump into command line changes on the machine I work on every day. Instead I installed a clean install of OS X 10.8 (Mountain Lion) using VMware Fusion, version 4.1.4 – couldn’t be easier. OS X came from the Mac App Store, the .dmg was converted to a CDR and VMware treated it as a boot CD. According to the Mac OS X 10.8.2 EULA, you are licensed to do this if you bought your copy from the Mac App Store.2
In addition to not potentially screwing up the machine on which you earn a living, virtualisation allows you to make a snapshot of your Virtual Machine (VM) – a saved game, if you like. Any time you know you have got something right you can pause the machine and take another snapshot. Any time things go badly wrong you can revert. The cost of this is nothing but disk space.
First up, the new VM needs Xcode installed. When done it is a good idea to license Xcode for all the users on the machine using the terminal:
sudo xcodebuild -license
The reason for this is that your build system will not be interactive, it can’t pop up the click-to-accept license dialog. About 7,109 presses of the space bar will be required before you can type “agree” to accept the license for all users on the system. I would never advocate using ‘G’ to make less skip straight to the end of the license agreement, you should read it all. (This is the first of many useful bits of information from an excellent session from WWDC 2012, hereafter simply called “404″3)
Next up, java. Theoretically java should be installed for you automatically when Jenkins tries to start. Once I installed Jenkins and it did not start, reason unknown. Now I type “java” at the command prompt and cause it to be installed before installing Jenkins. This will download and install java from the Mac App Store, nice and easy.
Before installing Jenkins I like to create the “jenkins” user. If you install Jenkins first the user is created but not as a regular, interactive user. Creating the user will make it easier to deal with some keychain operations later. You can create this user in the normal way with System Preferences. I made “jenkins” an administrator but it probably does not have to be.
Finally, time to install Jenkins itself. Because of my VM strategy I downloaded the Jenkins package on the host machine then copied it into the VM via a shared folder. If things go wrong this will save you from having to download it again. The Jenkins installer is fairly simple and nothing needs to be changed though you might want to look at the customizebutton to check that settings have not changed since I wrote this. Jenkins should be made to run as “jenkins”, the user you just created.
Following a successful Jenkins installation the Jenkins console should pop up in your browser – but this isn’t successful just yet. As of version 1.489, Jenkins includes a property list that must be edited first. At the console,
sudo launctl unload /Library/LoadDaemons/org.jenkins-ci.plist
then edit it to point to user “jenkins” actual home folder, (/Users/jenkins) and
sudo launctl load /Library/LoadDaemons/org.jenkins-ci.plist
Screen Shot 2012 11 22 at 1 48 44 PMJenkins is now configured to load when the system starts and should be running! If you launch a browser and enter http://127.0.0.1:8080 you should see the Jenkins console, ready to go to work.
In your clean system + Xcode you have git installed, but Jenkins can’t find it yet. You need to go to “Manage Jenkins” and specify the path. That path will be
/Applications/Xcode.app/Contents/Developer/usr/bin/git.
Jenkins supports SVN as installed, but I’m using git. For git users, you will want to install the Jenkins Git plugin. Github users will also want to install GitHub and GitHub API plugins. The way Jenkins uses git is to clone the repository you want to build before each build commences. I guess you could do this with a simple copy or ftp also, but I hope you are using some kind of revision control.
Before configuring the Jenkins build job, user “jenkins” needs a bit of setup. In your day-to-day environment, the one where you can successfully build an Archive of your project for distribution – remember that “Build on Success” section? – you have a keychain containing your developer credentials, and “jenkins” does not. You need to export them and then import them into a keychain for jenkins to use during the build. Your private key and your distribution certificate are required to make an OTA build, so export those and transfer them into the jenkins account using your public folder or similar.
A note about privacy – your private key is private, and important. Don’t leave it in your public folder. There is discussion on StackOverflow about how sharing a key like this is actually a bad idea, but I don’t know how to do it better.
Switch to the jenkins account and it’s time for some terminal magic:
security create-keychain -p jenkins JenkinsCI
security default-keychain -s JenkinsCI
security import -k JenkinsCI -P security import -k JenkinsCI
These commands create a new keychain named “JenkinsCI”, set it to be the default keychain, and then import the private key and distribution certificate you have transferred in to this account. The password “jenkins” is used throughout. During the build these assets will be used to sign the code with your developer credentials.
The provisioning profile is the last developer artefact needed. In your own account you will find it in ~/Library/MobileDevice/Provisioning Profiles, where Xcode puts it. You might choose to put that in the same place in the jenkins account, or you might choose to check it in with the code in the repository. Either way it must be available during the final stage of the build.
Now the configuration of the Jenkins job can begin. Each job in Jenkins is a series of steps that you define to produce some useful outcome. Here the outcome is a downloadable, installable iOS package on an accessible web server. Start by clicking “New Job” in the Jenkins console.

NEW JOB

This job is configured as a “Free-style software project”. A Multi-configuration project is shown in 4043 but this is only slightly different, a little simpler. There are six main phases to configure and once you have chosen a name for this job you are done with stage one. It remains to fetch code from the repository, build it, sign it and upload it. Finally you will set up when the job will execute.

FETCH

Assuming you are a git user, in the Source Code Management section of job configuration you can just select git and then enter the repo location, such ashttps://github.com/[GitHub account]/[Project Name].git/ – on every project in your GitHub repository you will find the clone path at the top of the repo page. If your repos are not public you will need to deal with creating an ssh key for your jenkins user in your GitHub account4 – or use HTTPS, or any method that works your your repo. At the start of every job execution Jenkins will clone the entire git repository and use it for the build.

BUILD

At this point it is time to be sure that jenkins has access to the keychain created for this build. In the Build section of job configuration you need to add a build step, “Execute shell”. You’ll get a window that accepts shell commands which will be run. The first command to enter is
security unlock-keychain -p jenkins JenkinsCI
As you might guess this unlocks the keychain, allowing the rest of the script access to developer artefacts as required.
In this script one very important variable set for you here is $WORKSPACE – it is set by Jenkins and is your pointer into the place where everything happens. It is used many times in the build commands.
Before building with Xcode in Jenkins, another important variable should be set. Thexcode-select command sets the default installation of Xcode that will be used. TheDEVELOPER_DIR variable can override xcode-select, so it is a good idea to be sure it is set to the right value before proceeding even though in this case there is only one Xcode installed. In future you might lift this script to run on some machine with more than one.
The build itself is deceptively simple:
xcodebuild \ 
    -project [Project Name].xcodeproj \ 
    -target [Target Name] \ 
    -configuration Release \ 
    -sdk iphoneos \ 
    CODE_SIGN_IDENTITY="${SIGNING_IDENTITY}"
The command xcodebuild is the main command used to execute builds from the command line with Xcode. My project is a project rather than a workspace, so I am specifying the .xcodeproj rather than the .workspace here. The target is the target name as you would see it in Xcode. The configuration is Release (but it could be Debug) and the sdk is iPhone rather than simulator.
Initially I had a command that looked a lot more like what is presented in 4043 but I got an error message that indicated the code signing identity was not set. Why this happened I do not know, but specifying the code signing identity, like
SIGNING_IDENTITY="iPhone Distribution: [Developer Name]" fixed it. Now Xcode is building your code.

SIGN

When the build has finished you have a .app file, which isn’t very useful. Because it is built for the iphoneos sdk it doesn’t run on the simulator and because it isn’t signed it doesn’t run on a device. Let’s sign it.
The other command used with Xcode on the command line is xcrun – it is a two-phase thing, finding and then executing commands included with the Xcode distribution. To sign,xcrun is using a perl script included with Xcode called PackageApplication.
xcrun -sdk iphoneos PackageApplication \
    -o "${WORKSPACE}/[Target Name].ipa" \
    -verbose "${WORKSPACE}/build/Release-iphoneos/[Target Name].app" \
    -sign "${SIGNING_IDENTITY}" \
    --embed "${PROVISIONING_PROFILE_DIR}/${PROVISIONING_PROFILE}"
It can take a lot of options. The ones I found necessary are the output, where you specify where the .ipa archive will be place. The input, which is the .app built in the xcodebuildstage. The signing identity, also the same as the xcodebuild stage. Finally the provisioning profile, which you may have copied into the jenkins account or you may have committed with your code.
At this stage you may get an error – I did. Some searching revealed the cause of the error is a misconfigured Xcode installation, a soft link that should be present is not. The message is “Object file format invalid or unsuitable” which may lead you to think that the failure has something to do with the object file format. Bad error message!
It is fixed with this variable set in the script:
export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
Then – happiness. You should see “Finished: SUCCESS” in the Jenkins console output, and if you have been executing the job along with the description then the ball will be blue.

UPLOAD

After all that, OTA deployment is easy. There are three parts necessary before you can get a successful download to a device. The html, which must include a link with the itms-services:scheme, linking to the property list; the property list, which must contain the location of the IPA archive created in the Sign phase; and the IPA archive itself, the payload. If all these things are together on an accessible web server, a device whose UDID is included in the provisioning profile will be able to install the app. While you have created the IPA with this process you will probably create the html and plist manually and commit it to the source repository.
cURL5 is a great tool included with OS X. If you have ever worked with web services you may have used it to take a look at raw JSON or XML to figure out where interesting data is. What I didn’t know is that it can send data too. Sending files via ftp turned out to be simple. one of those rare trial-and-success experiences:
curl ${HOSTING_ADDRESS}${HOSTING_PATH} \
    -u ${HOSTING_NAME}:${HOSTING_PWD} \
    -Q "TYPE I" \
    -T ${WORKSPACE}/${TARGET_NAME}.ipa
Most of this should be very easy to understand. You have a host address and a path on that host where you want the html, plist and IPA to be placed. You know the name and password of an account on that server which has the required privileges to upload to it. You have the thing to send, specified by the -T argument – here the IPA is being transferred. A final note about the ftp protocol: it is ancient and assumes everything is 7-bit text unless you specify otherwise. If you transfer binaries without specifying “TYPE I” then the binary will become corrupted. For the html and plist assets this -Q argument can be omitted.
And you’re done! if all went well you should now be able to connect to your sever and install the app.

BUILD TRIGGERING

Hang on, this isn’t continuous integration yet, it only happens when you click “Schedule a build”. It should happen whenever code is pushed to the repository. This is easily done. The most easy way to do it is to poll the repository at intervals to see if anything changed. In the Build Triggers section of job configuration, Poll SCM allows you to set a schedule for this polling. Once every five minutes is specified by “*/5 * * * *”.
If you feel that polling in general is bad (and it is) and you are using GitHub, AND your build machine is accessible to GitHub (i.e. is on the public internet) then you can have GitHub notify your build machine when a job should be executed. Mine isn’t so I didn’t try this.6
Either way your final test is to push to your repository and wait to see if Jenkins starts a build. Make some change that you can see on your device, let it go through the whole process and download the result. Ah, satisfying.

NEXT…

This has been a very basic kind of how-to article. A lot more can be done to automate build, packaging and deployment and shell masters will find plenty of room to improve what I have shown here. It would be good practise to archive each deployed build. Multiple versions and configurations could be built at each build trigger. Automated testing could be run. Build lights7 could be set to show the result of each build. You could convert the VM to a physical machine to make use of a mini or similar as a build server.

THE SOURCE

Shell commands used inside Jenkins

HOSTING_NAME="[your account name on your deployment server]"
HOSTING_PWD="[your password on your deployment server]"
HOSTING_ADDRESS="ftp://ftp.[your server's address]/"
HOSTING_PATH="[path you will serve the build from]"
#
# interesting to know the path
#
echo ${WORKSPACE} 
#
# your provisioning profile can be called, and stored, as you like
#
TARGET_NAME="[Your target name]"
SIGNING_IDENTITY="iPhone Distribution: [Developer Name]"
PROVISIONING_PROFILE_DIR="/Users/jenkins/Library/MobileDevice/Provisioning Profiles"
PROVISIONING_PROFILE="[Target]_Ad_Hoc.mobileprovision"
#
# always set for xcodebuild
#
export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer
#
# Lucky I found this on Stack Overflow. My build wasn't working until I did.
#
export CODESIGN_ALLOCATE="/Applications/Xcode.app/Contents/Developer/usr/bin/codesign_allocate"
#
# Unlock the keychain containing code signing keys and certificates
#
security unlock-keychain -p jenkins JenkinsCI
#
# Do the actual build
#
xcodebuild \
    -project [Project Name].xcodeproj \
    -target ${TARGET_NAME} \
    -configuration Release \
    -sdk iphoneos \
    CODE_SIGN_IDENTITY="${SIGNING_IDENTITY}"
#
# sign the .app so that it is ready for OTA
#
xcrun -sdk iphoneos PackageApplication \
    -o "${WORKSPACE}/${TARGET_NAME}.ipa" \
    -verbose "${WORKSPACE}/build/Release-iphoneos/${TARGET_NAME}.app" \
    -sign "${SIGNING_IDENTITY}" \
    --embed "${PROVISIONING_PROFILE_DIR}/${PROVISIONING_PROFILE}"
#
# place the new assets on the server so everyone can get them
#
# index.html
curl ${HOSTING_ADDRESS}${HOSTING_PATH} \
    -u ${HOSTING_NAME}:${HOSTING_PWD} \
    -T ${WORKSPACE}/Crawler/OTA/index.html
# plist
curl ${HOSTING_ADDRESS}${HOSTING_PATH} \
    -u ${HOSTING_NAME}:${HOSTING_PWD} \
    -T ${WORKSPACE}/Crawler/OTA/${TARGET_NAME}.plist
# IPA
curl ${HOSTING_ADDRESS}${HOSTING_PATH} \
    -u ${HOSTING_NAME}:${HOSTING_PWD} \
    -Q "TYPE I" \
    -T ${WORKSPACE}/${TARGET_NAME}.ipa

Sample (simple) html pointing to plist

<H3><a href="itms-services://?action=download-manifest&url=http://[server address].com/[path]/[Target name].plist">Download Target (Universal)</a></H3>

Property List identifying the location of the IPA

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
 <key>items</key>
 <array>
  <dict>
   <key>assets</key>
   <array>
    <dict>
     <key>kind</key>
     <string>software-package</string>
     <key>url</key>
     <string>http://www.[server address].com/[path]/[Target].ipa</string>
    </dict>
   </array>
   <key>metadata</key>
   <dict>
    <key>bundle-identifier</key>
    <string>[Bundle ID from your AppName-Info.plist file]</string>
    <key>bundle-version</key>
    <string>1.0</string>
    <key>kind</key>
    <string>software</string>
    <key>title</key>
    <string>[Target]</string>
   </dict>
  </dict>
 </array>
</dict>
</plist>
And that’s it – I hope you get something out of this post. Comments are disabled due to an infinitely high spam-to-actual-comment ratio in the past, but email is welcome. On twitter I’m @aeberbach, to email use the same name at iCloud.
1. Voltaire wrote in Candide, of Admiral Byng’s execution: “In this country, it is wise to kill an admiral from time to time to encourage the others.”
2. Apple Mac OS X 10.8.2 EULA – see section 2 (iii).
3. Apple WWDC 2012 Session 404, Building from the Command Line with Xcode – this is a very practical and useful session.



HowTo: Linux / UNIX List Just Directories Or Directory Names

http://www.cyberciti.biz/faq/linux-list-just-directories-or-directory-names/


Display or list all directories

Type the following command:
$ ls -l | egrep `^d'

Display or list only files

Type the following command:
$ ls -l | egrep -v `^d'
grep command used to searches input. It will filter out directories name by matching first character d. To reverse effect (just to display files) you need to pass -v option. It invert the sense of matching, to select non-matching lines.

Task: Create aliases to save time

You can create two aliases as follows to list only directories and files.
alias lf="ls -l | egrep -v '^d'"
alias ldir="ls -l | egrep '^d'"

Put above two aliases in your bash shell startup file:
$ cd
$ vi .bash_profile

Append two lines:
alias lf="ls -l | egrep -v '^d'"
alias ldir="ls -l | egrep '^d'"

Save and close the file.
Now just type lf - to list files and ldir - to list directories only:
$ cd /etc
$ lf

Output:
-rw-r--r--   1 root root      2149 2006-09-04 23:25 adduser.conf
-rw-r--r--   1 root root        44 2006-09-29 05:11 adjtime
-rw-r--r--   1 root root       197 2006-09-04 23:48 aliases
-rw-------   1 root root       144 2002-01-18 13:43 at.deny
-rw-r--r--   1 root root       162 2006-09-22 23:24 aumixrc
-rw-r--r--   1 root root        28 2006-09-22 23:24 aumixrc1
....
..
....
List directory names only:
$ cd /etc
$ ldir
Output:
drwxr-xr-x   4 root root      4096 2006-09-22 16:41 alsa
drwxr-xr-x   2 root root      4096 2006-09-20 20:59 alternatives
drwxr-xr-x   6 root root      4096 2006-09-22 16:41 apm
drwxr-xr-x   3 root root      4096 2006-09-07 02:51 apt
drwxr-xr-x   2 root root      4096 2006-09-08 01:46 bash_completion.d
....
.....
.

find command

The find command can be used as follows to list all directories in /nas, enter:
find /nas -type d
find /nas -type d -ls
find . -type d -ls
Sample outputs:
1070785    8 drwxrwxrwt   8 root     root         4096 Jul  5 07:12 .
1070797    8 drwx------   2 root     root         4096 Jul  4 07:22 ./orbit-root
1070843    8 drwxr-xr-x   2 root     root         4096 Jun 16 18:55 ./w
1070789    8 drwxr-xr-x  10 root     root         4096 Jun 17 14:54 ./b
1071340    8 drwxr-xr-x   2 root     root         4096 Jun 16 18:55 ./b/init.d
1071581    8 drwxr-xr-x   3 root     root         4096 Jun 16 18:55 ./b/bind
1071584    8 drwxr-xr-x   2 root     root         4096 Jun 16 18:55 ./b/bind/bak
1071617    8 drwxr-xr-x   2 root     root         4096 Jun 16 18:55 ./b/fw
1071628    8 drwxr-xr-x   8 root     root         4096 Jun 16 18:55 ./b/scripts

If you would like to be kept up to date with our posts, you can follow us on Twitter,FacebookGoogle+, or even by subscribing to our RSS Feed.


Eric April 26, 2007 at 1:07 pm
To get just file names without the long list data:
ls -l | grep ‘^d’ | awk ‘{ print $9 }’
Or
for foo in *; do if [ -d $foo ]; then print -n ” $foo”; else false; fi; done
2Lingerance September 18, 2007 at 7:39 am
find . -type d -maxdepth 1
3mysurface September 21, 2007 at 12:15 am
ls -d */
or for hidden directories
ls -d .*/
4vivek September 21, 2007 at 12:52 pm
Thanks for contributing all other tips :)
5Vinayak September 26, 2007 at 5:56 am
Thanks a lot for nice recipe… :-)
6Michel Roig October 1, 2007 at 2:48 pm
To get just the subdirectories names
find . -type d -maxdepth 1 -exec basename {} \;
However, in this case you also get the directory itself! To avoid this, add mindepth 1:
find . -type d -maxdepth 1 -mindepth 1 -exec basename {} \;
7Eugenio November 18, 2007 at 3:12 pm
For some reasons on FAT fs
ls -d */
is not working. But this works on any filesystem:
ls -d ./*/
8Suresh M January 4, 2008 at 10:52 am
echo */
9Al January 11, 2009 at 5:19 pm
mysurface — you are the man!
10biodafes January 21, 2009 at 1:18 am
(folders)
ls -F | grep /
(files)
ls -F | grep -v /
11Mahantesh Biradar January 30, 2009 at 5:13 am
Lists all the subdirectories in the current directory..
ls -R | grep ./
12Gareth Reeman May 1, 2009 at 6:19 pm
can some1 please help me i need to know what the significant effects are of the following characters in unix filenames. 2 dots / 1 dot / tilde or “squiggle”
..
.
~
13Vivek Gite May 1, 2009 at 8:47 pm
. Current directory
.. Parent directory
~ Your home directory
14Dennis Quek May 5, 2009 at 7:35 am
Can you just list the directories name, without the permission, datetime, and etc … ?
15kopla May 8, 2009 at 10:22 am
Thanx, nice post. I was just thinking of doing it with awk but couldnt get the wildcard working. Now I am one step ahead in my shell knowledge ^^
To Dennis Quek above :
A rather dirty solution but does the job.
ls -l | egrep ‘^d’ | awk ‘$1=” “‘ | awk ‘$1=” “‘ | awk ‘$1=” “‘ | awk ‘$1=” “‘ | awk ‘$1=” “‘ | awk ‘$1=” “‘| awk ‘$1=” “‘| awk ‘$1=” “‘
(forgive me if seeing this code gives someone a heart attack, all i can say is that I’m still learning :P )
I would love if someone can give my code a neater look :)
16Ashish June 20, 2011 at 3:58 pm
A cleaner Recipe for the same using AWK :
ls -l | egrep ‘^d’ | awk ‘{ print $9}’
another alternate is bit clumsy :
ls -l | egrep ‘^d’ | awk ‘$1=” “,$2=” “‘ | awk ‘$1=” “,$2=” “‘ | awk ‘$1=” “,$2=” “‘ | awk ‘$1=” “,$2=” “‘
Another Simpler and Faster way out to get the Desired result :
ls -l|grep ‘^d’
17kopla May 8, 2009 at 10:34 am
oops! didnt read the other comments. Already many nice solutions have been posted :P
18jagan June 30, 2009 at 12:29 pm
i used to the $ du command to retrieve all directory names.
$ du
19Aditya July 28, 2009 at 2:38 pm
> i used to the $ du command to retrieve all directory names.
Jagan,
du is used to calculate Disk Usage. I want to know did you tweak this command to display directory listing in pwd. Please explain.
20anon October 7, 2009 at 6:36 pm
$ /bin/ls -l | grep “^d” | cut -d’ ‘ -f8
it’s a neat trick on linux systems.
i’m using /bin/ls and not ls because it may be aliased
21Amit Nagwanshi October 20, 2009 at 5:30 am
one can list directory i simple and easy way by :
1. ls -ltr | grep -e d
2. ls -ld */
3. du
third one is the most easiest way. :-)
22Amr October 23, 2009 at 7:58 am
I tried with both GNU ls and BSD one and the best option is as someone else posted above:
ls -ld */
23Mohammed asif December 9, 2009 at 11:29 am
i renamed a directory name with a space in between the directory name within GUI(Graphical User Interface)
which is allowed and now in the shell prompt i.e. in the terminal command mode i want to enter the directory which has a space in between but it does not allows to enter into that directory it says “INVALID DIRECTORY”
is their any alternative solution or trick to enter into the directory with the name having space.please explain
the directory name is “file data”
i tried with — $cd file data but it didnt work out.
24Sirdude February 25, 2010 at 6:27 pm
nice stuff!
i learned a lot from the original post, but the comments are a treasure trove!
one thing about the original post, you have a back tick instead of a single quote in the 1st two snippets
ls -l | egrep `^d’ for example should be ls -l | egrep ‘^d’ for the copy / pasters
thanks again ;)
25newbee1 March 3, 2010 at 6:52 pm
if you wanted to pull a date from the directory to only list files from datea/timea through dateb/timeb (say March 2 at 6:00 AM to March 8 at 6:00 AM) and move into a new file the output, how is this accomplished? I tried this but no output
#!/bin/bash
FILES=’ls -A1′
OUTFILE=”c:/temp/RRDfilesinrange.txt”
STARTDATE=’date –utc –date “2010-02-27 06:00:00″ %s’
ENDDATE=’date –utc –date “2010-03-02 06:00:00″ %s’
cd C: temp/tsfr-complete
for f in $FILES
do
if [ -f $f ]; then
FDATE=’stat -c “%Z” $f’
if [ $FDATE -ge $STARTDATE ]; then
if [ $FDATE -le $ENDDATE ]; then
‘echo $f >> $OUTFILE’
fi
fi
fi
done
26Davis April 27, 2010 at 2:17 am
How do you get the directory listing to display only: the file name, the user that owns the file and that user’s permissions?
27balarajangeetha August 4, 2010 at 2:34 pm
//Mohammed asif December 9, 2009
is their any alternative solution or trick to enter into the directory with the name having space.please explain//
did you try
cd “file data”
or
cd ‘file data’
( i.e. directory name with double quotes or single quote)
you yourself have given the hint :-)
28danio August 23, 2010 at 10:20 am
@Davis:
ls -l | awk ‘{ print $1,$3,$9 }’
29Volomike October 8, 2010 at 2:53 am

alias ldir="ls -d -1 */ | tr -d '/'"
ldir
30dccrowley February 15, 2011 at 11:19 am
works :)) Thanks
31alireza October 21, 2010 at 8:20 am
Hello.
I would like to do some batching in my linux but I couldn’t find any way of initializing an array containing folder’s location information. In short, I have data in two folders located at:
/home/alireza/Desktop/DTIBetula101019/B2509.30
/home/alireza/Desktop/DTIBetula101019/B2509.50
and I want to make an array following by a loop to do some specific command inside each folder seprately like this:
fn_list= (‘/home/alireza/Desktop/DTIBetula101019/B2509.30′,’/home/alireza/Desktop/DTIBetula101019/B2509.50′)
for fn in ${fn_list}
do
cd $fn
fsl4.1-fslmerge -t big4D 2501.45-DTI1-s007 2501.45-DTI2-s008 2501.45-DTI3-s009
done
can anybody help me to figure out how to specify an array that can pointed to a folder which can be reused during a for loop?
Thanks
/Alireza
32asl.marc January 6, 2011 at 6:53 pm
alias lsdir=’ls -d ./*/ | cut -d / -f 2′
lsdir
for i in `lsdir` ; do du -ks $i; done
33SilversleevesX September 21, 2011 at 3:26 pm
Commenting on Eric’s ls | grep | awk combination:
Cygwin (1.7.9) displays 8, not 9, fields in
    ls -l
.
So change his “awk ‘{print 9}’” to awk ‘{print 8}’ and you’ll get more than a bunch of deadspace in mintty.
Just in case it wasn’t already obvious. *S*
BZT
34Ramesh Kumar J May 30, 2012 at 10:50 am
ls -lrt | grep /
35Prasad June 30, 2012 at 6:32 am
From all the above I feel the best way is …
ls -ld */
36James Friedman October 30, 2012 at 9:53 am
Thank you for a very helpful and useful post – much appreciated… – James
37Adrian April 4, 2013 at 9:34 am
A sed version:
ls -F1 | grep ‘/’ | sed ‘s/\///’
38Nageswara Rao Orsu May 21, 2013 at 11:29 am
ls -d */ or ls -ld */ (Use these commands to display only directories in current user)
cd /etc
ls -ld */ ( Use these two commands to display only directories for all users including root)
39mammy boy May 24, 2013 at 10:28 pm
list of directories:
ls -alp /