PREVIOUS     NEXT

Determine if a file is writable by a Bourne script user

 From a Bourne shell script (sh, ksh, bash, ...), it is possible to test if a file exists and is writable by the user running the script. if [ -w testfile ] then   echo testfile is writable! else   echo non writable... fi... Read More

Determine if a file is readable by current Bourne shell script user

 A well contructed shell script, like any good program, should handle error conditions gracefully. Checking if a file is readable before attempting to read it allows a script to branch instead of abort or display an error message. if [ -r testfile ] then   cat testfile else   echo file is not readable fi... Read More

Bourne/bash shell scripts: if statement syntax

 Conditional expressions give programs life. The ability to branch makes shell scripts powerful. This recipe shows the basic if then else structure for sh, ksh, bash, zsh, etc. if [ condition_A ] then    code to run if condition_A true elif [ condition_B ] then    code to run if condition_A false and condition_B true else    code to run if both conditions false fi Multiple elif blocks can be strung together to make an elaborate set of conditional responses.... Read More

Hide password entry in Bourne/bash shell script

 Common practice for inputing passwords is to read the text without displaying it on the screen. The UNIX Bourne shell does not have this functionality as a command, but a combination of commands will make this work.The stty command sets numerous terminal parameters including whether or not characters should be echoed to the terminal. To turn off echoing, the command stty -echo can be used. Any subsequent user input (including commands typed at the shell) will not be echoed. To restore the echoing, use stty echo. However, it is poor programming to make the assumption that echo is on. In some cases, echoing of characters is done at the local terminal (in which case we cannot prevent echoing passwords) and the result of the second command will be that every character typed will appear twice. To avoid this, a neat stty trick is used in which the original state of stty is stored before the stty change and restored after the read. The following code will read a password into the variable sec... Read More

Bourne/bash shell script for loop syntax

 A for loop allows a program to iterate over a set of values. For loops in a Bourne shell script (sh, ksh, bash, zsh, etc.) are a useful means of iterating through files or other lists. This recipe describes the for loop syntax and provides some examples.The basic for loop syntax is: for var in list do    commands; done The list can be a specified set of values (1 2 3 4) or anything that will evaluate into a set of values (a wildcard expression will expand the matching filenames into a list). For example, '/usr/bin/[aeiou]*' will expand to the set of files in /usr/bin starting with a vowel (this, of course, comes up all the time). The commands enclosed between do and done will be executed once for each item in the list. The current value from the set can be accessed with the variable $var. To separate a log file into multiple files based on the month (assuming that the log format contains the three letter month abbreviation): #!/bin/sh logfile="/var/adm/messages" for... Read More

Bourne/bash shell script: while loop syntax

 A while loop allows execution of a code block an arbitrary number of times until a condition is met. This recipe describes the while loop syntax for the various Bourne shells (sh, ksh, bash, zsh, etc.) and provides examples.General syntax: while [ condition ] do     code block; done Any valid conditional expression will work in the while loop. The following code asks the user for input and verifies the input asking for a y or n and will repeat the process until a y answer is received. verify="n" while [ "$verify" != y ] do     echo "Enter option: "     read option     echo "You entered $option.  Is this correct? (y/n)"     read verify done Another useful while loop is a simple one, and infinite loop. If the conditional is "1" the loop will run until something else breaks it (such as the break keyword): while [ 1 ] do     ps -ef | grep [s]e... Read More

Bourne/bash shell script functions

 Writing functions can greatly simplify a program. If a chunk of code is used multiple times in different parts of a script, the code can be enclosed within a function and run using only the function name.The following example decribes the use of functions in a Bourne shell script. #!/bin/sh sum() {    x=`expr $1 + $2`    echo $x } sum 5 3 echo "The sum of 4 and 7 is `sum 4 7`" When run, the script will output the value 8 (the sum of 5 and 3) followed by the text "The sum of 4 and 7 is 11" on the next line. Within the function, optional arguments passed to the function (as in the 5 3 following the function call of sum at the bottom) can be accessed like arguments to a shell script. $1 accesses the first parameter, $2 accesses the second parameter, and $@ accesses all parameters. A more elaborate example will extend the sum function to add together more than two values: #!/bin/sh sum() {    if [ -z "$2" ... Read More

bash shell script declaring/creating arrays

 The use of array variable structures can be invaluable. This recipe describes several methods for delcaring arrays in bash scripts.The following are methods for declaring arrays: names=( Jennifer Tonya Anna Sadie ) This creates an array called names with four elements (Jennifer, Tonya, Anna, and Sadie). names=( "John Smith" "Jane Doe" ) This creates two array elements, each containing a space. colors[0] = red colors[3] = green colors[4] = blue This declares three elements of an array using nonsequential index values and creates a sparse array (there are no array elements for index values 1 or 2). filearray=( `cat filename | tr '\n' ' '`) This example places the contents of the file filename into an array. The tr command converts newlines to spaces so that multiline files will be handled properly. names=( "${names[@]}" "Molly" ) This example adds another element to an existi... Read More

bash shell script iterate through array values

 Having an array of variables is of no use unless you can use those values somehow. This recipe shows a few methods for looping through the values of an array in the bash shell.Given the array definition: names=( Jennifer Tonya Anna Sadie ) The following expression evaluates into all values of the array: ${names[@]} and can be used anywhere a variable or string can be used. A simple for loop can iterate through this array one value at a time: for name in ${names[@]} do    echo $name    # other stuff on $name done This scrip will loop through the array values and print them out, one per line. Additional statements can be placed within the loop body to take further action, such as modifying each file in an array of filenames. Sometimes it is useful to loop through an array and know the numeric index of the array you are using (for example, so that you can reference another array with the same index). The same loop in the exam... Read More

bash shell script accessing array variables

 The bash shell allows a number of methods for accessing elements of variable arrays. This recipe demonstrates some of these techniques.Given the array defined by the following code: names=( Jennifer Tonya Anna Sadie Molly Millie) The individual elements in the array can be accessed by their numeric index (remember that they start counting a zero) with: ${names[0]}  -> Jennifer ${names[3])  -> Sadie All of the elements can be accessed at the same time (which is useful in a for loop) with the following: ${names[@]} ${names[*]} The number of elements in the array can be obtained with: ${#names[@]}  -> 6 A range of elements can easily be specified with the following syntax: ${names[@]:2:3}  -> Anna Sadie Molly ${names[@]:3}  ->  Sadie Molly Millie The first example starts at element 2 (the third element... Read More

bash array operations

 sometimes we need to remove one element from an array for example we remove the element 2 (third) from array array=("hello" "i" "like" "bash") i=2 array=(${array[@]:0:$i} ${array[@]:$(($i + 1))})... Read More

queue and stack using array

 here is a series of operation on array, we can use these functions to implement a queue or stack that can help us morepush: array=("${array[@]}" $new_element) pop: array=(${array[@]:0:$((${#array[@]}-1))}) shift: array=(${array[@]:1}) unshift array=($new_element "${array[@]}") function del_array { local i for (( i = 0 ; i < ${#array[@]} ; i++ )) do if [ "$1" = "${array[$i]}" ] ;then break fi done del_array_index $i } function del_array_index { array=(${array[@]:0:$1} ${array[@]:$(($1 + 1))}) }... Read More

simple function for print colorful text

 function to print text with colors(not contain all the colors) can be extened easily function print_color {    local text=$1    local fg=$2    local bg=$3        #change to right form    case "$fg" in       red)   fg="31m" ;;       green)   fg="32m" ;;                yellow) fg="33m" ;;       blue)   fg="34m" ;;       white)   fg="37m" ;;       black)   fg="30m" ;;       *)      fg="37m" ;;    esac    case "$bg" in       red)   bg="41m" ;;                gree... Read More

Simple Menu for User Input

 This script will create an input screen in BASH that allows the user to enter information just as they would in a window. This is to show the use of simple functions as well as the tput command. "tput cup" allows the developer to place the cursor anywhere on the screen. There are many more commands that tput recognizes, see the man page for more information. #!/bin/bash ## Clears the screen and builds the user input screen function screen() { clear cat <<EOF #################################################################### ##                 Main Screen for Input                          ## #################################################################### ##                                                        &nb... Read More

C++: Differences between C++ and C#

 Key differences between C# and C++It was a surprise that there was no thread for C++ recipes. Though C++ and C# are quite similar there are some very key and major differences. -I find C# resembles the style of java more than that of C++ i many ways. (I will be following this up with some coding recipes, to hopefully start a C++ reciped thread) Method/Function Declarations: C++: public: Constructor() { } void aMemberFunction() { } void aFunctionDeclaration(); private: void someOtherFunction() { } int aVariable; C#: private aVariable; public void aMemberFunction() { } public void aFunctionDeclaration(); private void someOtherFunction() { } Class Declaration: For those who know what a managed class is: C++: __gc class A_Class{ }; *NOTE that C++ classes end with a ; C#: automatically done so: class A_Class{ } Inheritence: C++: will allow multiple inheritence. eg. allows a method to be overriden many times in subclasses (derived classes). C#: supports inheritence, but not multiple, only 1 ... Read More

C++: Main Operator Overloading

 How to Overload the common operators: =, +, -, *Overloading an operator allows for custom operations on your own objects. *Say you want to add to person objects (ex. marriage)? -then you overload the + operator and define what is to be done when you add the objects. *For all my examples i will be using Person as the class which is my personally defined object. + Operator: The + operator takes 2 operands if it is declared outside of the Person class: //+Operator Overloader Person& operator+(const Person& p1, const Person& p2){    //code goes goes in here } The + operator takes 1 operand if it is declared inside the Person class: //+Operator Overloader Person& operator+(const Person& p2){    //code goes goes in here } *The object p1 can be accesed as a pointer as well with the keyword this. - Operator: The - operator takes 2 operands if it is declared outside of the Person class: //-Operator Overloader Person& operator-(const Pe... Read More

C++: Operator Overloading (slightly more complex)

 How to Overload the operators: ++(int), (int)++, --(int), (int)--The key is to know the action of these operators on the integers they are supplied for: For coding examples i will again be using Person as my example class. Perhaps ++ or -- increments or decrements the number of friends a particular person has. ex: int i = 0; ++i = 1; i++ = 1; //result is old value i = 2; //next time i is used, reveals the new value --i = 1; i-- = 1; result is still old value i = 0; //next time i is used, reveals the new value No parameters are supplied in either case the prefix versions are straight forward: Prefix ++ | ++(int): //++Operator Overloader - prefix    Person& operator++(){    this->friends = this->friends+1; //assuming Person class has a field friends.    return *this; return in the case of an assignment as well } Prefix -- | --(int): //--Operator Overloader - prefix    Person& operator--(){    this->... Read More

C++: Operator Overloading (even a little more complex)

 How to Overload the operators: +=, -=, *=, /=, %=Very similar to overloading the +,-,* operators within a class, as they all take a single parameter as such: As with all the other Person will be the custom class. Perhaps these operations combine the friends of 2 people to the friends of one of the persons. += Operator: Person& operator+=(const Person& p1){      this->friends = this->friends + p1.friends;      return *this; } -= Operator: Person& operator-=(const Person& p1){      this->friends = this->friends - p1.friends;      return *this; } *= Operator: Person& operator*=(const Person& p1){      this->friends = this->friends * p1.friends;      return *this; } /= Operator: Person& operator/=(const Person& p1){      this->friends = this->friends / p1.friends;      return *this;... Read More

Assembly: The Registers and Segments (MASM/TASM)

 The name and type of the registers and segments usable by a 32-bit processor (Easily converted by a naming convention to 16-bit and even 64-bit)Since there are no other recipes on Assembly Language, it would be irrational to start anywhere but the basics of hardware in assembly programming. I myself do not use a Pentium Processor, but since the assembler i am writting for is specific to Pentium some names may be off. When using MASM or TASM the naming conventions will work no matter the Processor you have as long as it is in the corresponding size (eg. 32-bit, 64-bit etc) The Registers: Visual Representation: --------------------------------------------- |11111111111111111111|22222222222|3333333333| --------------------------------------------- This applies to EAX, EBX, ECX and EDX: *EAX will be the example -The entire register (32-bits) containing 1's 2's and 3's is EAX -The section filled with 1's is the upper or left 16-bits of EAX, which cannot be accessed directly -The other half ... Read More

Assembly: Flags

 The EFlags register, what they, what they do and when they are set.The flags are located in a single 32-bit register (EFlags), each a single bit, thus holding a value of 1 true, or 0 false. I will list the flags by name, location in the register and use: *location will be a bit from 0-31 00: CF Carry Flag - becomes one if an addition, multiplication, AND, OR, etc results in a value larger than the register meant for the result 02: PF Parity Flag - becomes 1 if the lower 8-bits of an operation contains an even number of 1 bits 04: AF Auxiliary Flag - Set on a carry or borrow to the value of the loer order 4 bits 06: ZF Zero Flag - becomes 1 if an operation results in a 0 writeback, or 0 register 07: SF Sign Flag - is 1 if the value saved is negative, 0 for positive 08: TF Trap Flag - allows for the stopping of code within a segment (allows for single stepping/debugging in programming) 09: IF Interrupt Flag - when this flag is set, the processor begins 'listening' for external interupts ... Read More

 

 

Pages : 1 2 3 4 5 6 7