Tuesday, June 10, 2014

UNIX - Touch

touch - is a standard Unix program used to change a file's access and modification timestamps. It is also used to create a new empty file.

-a, change the access time only
-c, if the file does not exist, do not create it and do not report this condition
-d date_time, use the date_time specified to update the access and modification times
-m, change the modification time only
-r file, use the access and modification times of file

-t time, use the time specified (in the format below) to update the access and modification times

Unix - Special Variables

Variable Description

$0 The filename of the current script.
$n These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).

$# The number of arguments supplied to a script.
$* All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.

$@ All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1 $2.


$? The exit status of the last command executed.
$$ The process number of the current shell. For shell scripts, this is the process ID under which they are executing.


$! The process number of the last background command.

Unix - To lower/upper case

To lower/upper case

If you want to transform a string to upper or lower case, you can do so with the unix tr command. Here's a simple example.
#!/bin/sh

STR_ORIGINAL=aBcDeFgHiJkLmNoP
STR_UPPER=`echo $STR_ORIGINAL | tr a-z A-Z`
STR_LOWER=`echo $STR_ORIGINAL | tr A-Z a-z`

echo "Original: $STR_ORIGINAL"
echo "Upper   : $STR_UPPER"
echo "Lower   : $STR_LOWER"

Unix - Find in a string

Find in a string

Sometimes you need to find text in a string. Maybe you want to list files but print only the text appearing before the ".". So if the filename is asdf.txt, you would want to print only asdf. To do this, you will use expr index, and pass it the string followed by the text for which you are searching. Let's try an example:
#!/bin/sh

# Get the files:
FILES=`ls -1`

for FILE in $FILES
do
IDX=`expr index $FILE .`

if [ "$IDX" == 0 ]; then
IDX=`expr length $FILE`
else
IDX=`expr $IDX - 1`
fi

SUB=`expr substr $FILE 1 $IDX`
echo "Sub File: $SUB"
done

Advanced Unix shell scripting

Substrings

Often times a programmer needs to be able to get a substring from a variable at a given position. In unix you can use the expr command to do this with the substr parameter. 

Let's say that we have the text string "5283username$$2384/" and we want to get the text "username". To do this we need to read from position 5 for a length of 8. The parameters for substr are the input string, the starting position, and the length.

See the following example: 

INPUT="5283username$$2384/"

USER=`expr substr $INPUT 5 8`

echo "Sub: '$USER'"