You are here: ApiroTech > Programming > Shell script

 
 
 

Shell script

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

csh/C 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 csh, the C shell.Basic if statement syntax: if (condition) then     commands endif The addition of one or more else keywords offers additional flexibility: if (condition) then     commands else if (other condition) then     commands else     commands endif... Read More

csh/C shell scripts: for loop syntax

 A for loop allows a program to iterate over a set of values. For loops in a C shell script 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: foreach var (list)    commands; end 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/csh logfile="/var/adm/messages" foreach mon (Sun Mon Tu... Read More

Sending multiple lines of input to a program

 Using a 'here document' it is possible to send multiple lines of input to a program from a shell script. A here document uses the << I/O redirector followed by a code. The subsequent lines are redirected to the program until the specified code. The basic syntax is: program << CoDe Line of input More input extra input CoDe The code needs to be something that would not occur in the text. This technique is useful for working with interactive programs like ftp. In the following example, a file specified in a shell variable ($filename) is retrieved from an ftp server: filname=important.file.gz ftp -n ftp.server.name << TheEnd user username password cd directory/subdir get $filename quit TheEnd... Read More

Bourne/bash shell scripts: case statement

 The case statement is an elegant replacement for if/then/else if/else statements when making numerous comparisons. This recipe describes the case statement syntax for the Bourne shells (sh, ksh, bash, zsh, etc.). case "$var" in     value1)          commands;          ;;     value2)          commands;          ;;     *)          commands;          ;; esac The case statement compares the value of the variable ($var in this case) to one or more values (value1, value2, ...). Once a match is found, the associated commands are executed and the case statement is terminated. The optional last comparison *) is a default case and will match anything. For example, branching on a command line parameter to the script, such as 'start' or 'stop' with a runtime control script. The following example uses... Read More

A simple script that waits for a process to complete and then executes a command

 It is often necessary under unix/linux to wait for certain processes to complete before running other processes. At best this can cause needless delays and wasted time, while in the worst cases someone may actually forget to run some final processing.The script we are going to create is a simple script that will loop while waiting for a process to complete, and then execute the commands provided in the argument. We'll name our script waitforpid.sh and it will accept two arguments as follows: PID = Process ID to watch COMMAND = Commands to execute after the process completes We'll begin with some simple script setup, initialization, and parameter checking. As both of the parameters are required, we elected to keep the handling simple rather than going with something like xargs. We also added a delay variable to simplify the timing of the loop. This value is in seconds and you may change it to whatever value you like. For purposes of this script we left it to 5 seconds. #!/bin/sh #Grab t... Read More

 

 

Pages : 1