37
  Unix KornShell Quick Reference Contents Command Language I/O redirection and pipe Shell variables Pattern matching Control characters 1. The environment 2. Most usual commands Help Directory listing Creating a directory Changing directory Comparing files Access to files copying files and directories deleting files & directory moving files & directories Visualizing files linking fil es & directories Compiling & Linking Debugging a program Archive library Make Job control miscellaneous History & Command line editing 3. Creating KORNshell scripts The different shells Special shell variables 4. 1 of 37 9/7/2015 9:05 πμ

Unix KornShell Quick Reference

Embed Size (px)

DESCRIPTION

Unix KornShell Quick Reference

Citation preview

  • Unix KornShell Quick Reference

    ContentsCommand Language

    I/O redirection and pipeShell variablesPattern matchingControl characters

    1.

    The environment2.Most usual commands

    HelpDirectory listingCreating a directoryChanging directoryComparing filesAccess to filescopying files and directoriesdeleting files & directorymoving files & directoriesVisualizing fileslinking files & directoriesCompiling & LinkingDebugging a programArchive libraryMakeJob controlmiscellaneousHistory & Command line editing

    3.

    Creating KORNshell scriptsThe different shellsSpecial shell variables

    4.

    1 of 37 9/7/2015 9:05

  • special charactersEvaluating shell variablesThe if statementThe logical operatorsMath operatorsControlling executionDebug modeExamples

    Example 1 : loops, cases ...Example 2 : switchesExample 3Example 4Example 5

    List of Usual commands5.List of Administrator commands6.

    Command Language

    I/O redirection and pipe

    % command running in foreground (interactive)% command >file redirects stdout to file% command 2>err_file redirects stderr to err_file% command >file 2>&1 redirects both stdout and stderr on file% (command > f1) 2>f2 send stdout on f1, stderr on f2% command >>file appends stdout to file% command

  • stderr : to print on it in a script, use the option -u2 in command print

    Shell variables

    # Warning : no blank before of after the = sign # Integers : n=100 ; x=&n integer t typeset -r roues=4 # definition of a CONSTANT (read only) typeset -i2 x # declares x as binary integer typeset -i8 y # declares y as octal integer typeset -i16 z # guess what ? # Strings : lettre="Q" ; mot="elephant" phrase="Hello, word" print "n=$n ; lettre=$lettre ; mot=$mot ; phrase=$phrase" typeset -r nom="JMB" # string constant # Arrays : one dimensional arrays of integers or strings # automatically dimensionned to 1024 animal[0]="dog" ; animal[1]="horse" ; animal[3]="donkey" set -A flower tulip gardenia " " rose print ${animal[*]} print ${flower[@]} print "cell#1 content : ${flower[1]}

    Pattern matching

    +------------------------+------------------------------------------------+| Wild card | matches |+------------------------+------------------------------------------------+| ? | any single char || [char1char2... charN] | any single char from the specified list || [!char1char2... charN] | any single char other than one from the || | specified list || [char1-charN] | any char between char1 and charN inclusive || [!char1-charN] | any char other than between char1 and charN || | inclusive || * | any char or any group of char (including none) || ?(pat1|pat2...|patN) | zero or one of the specified patterns || @(pat1|pat2...|patN) | exactly one of the specified patterns || *(pat1|pat2...|patN) | zero, one or more of the specified patterns || +(pat1|pat2...|patN) | one or more of the specified patterns || !(pat1|pat2...|patN) | any pattern except one of the specif. patterns |+------------------------+------------------------------------------------+

    3 of 37 9/7/2015 9:05

  • Tilde Expansion : ~ your home directory (ls ~) ~frenkiel home directory of another user ~+ absolute pathname of the working directory ~- previous directory (cd ~-) ( or cd -)

    Control characters

    < ctrl_c> Cancel the currently running process (foreground) < ctrl_z> Suspend the currently running process then : > bg : to send it in background or > fg : continue in foreground or > kill -option : sends signals (such as TERMINATE) ex > kill -9 pid : to kill a background job kill -l : to find out all the signals supported by your system. < ctrl_d> End of file character $ stty to see what are the KILL & characters

    The environment +-----------------------------------------------+-----------------------+ | environmental characteristic | child inherit this ? | +-----------------------------------------------+-----------------------+ | parent's access rights to files, directories | yes | | the files that parent has opened | yes | | parent's ressource limits (type ulimit) | yes | | parent's response to signal | yes | | aliases defined by parent | NO (expect opt -x) | | functions defined by parent | if exported (*) | | variables defined by parent | if exported (*) | | KornShell variables (except IFS) | if exported (*) | | KornShell variable IFS | if NOT exported | | parent's option settings (type set -o) | no | +-----------------------------------------------+-----------------------+ (*) Not needed if a 'set -o allexport' statement has told the KornShell to export all these variables and functions

    To export a variable :

    2.

    4 of 37 9/7/2015 9:05

  • $ export LPDEST=pshpa

    $ echo $LPDEST ---> pshpa $ echo LPDEST ---> LPDEST

    Dot Scripts : a script that runs in the parent's environment, so it is not a child of the caller. A dot script inherits ALL of the caller's environment. Toinvoke a dot script, just preface the name of the script with a dot and a space :

    $ ficus.ksh # invoke this script as a regular script. $ . ficus.fsh # invoke the same script as a dot script.

    Aliases : An alias is a nickname for a KornShell statement or script, a user program or a command. Example:

    $ alias del='rm -i' # whenever you type 'del', it's replace by 'rm -i' $ alias # to see a list of all aliases $ unalias del # remove an alias

    It is recommanded (but not mandatory) to write the local variable names in lower case letters and those of global variables in upper case letters.Sequence of KornShell start-up scripts : The KornShell supports 3 start-up scripts. The first 2 are login scripts; they are executed when you log in. Athird one runs whenever you create a KornShell or run a KornShell script.

    - /etc/profile - $HOME/.profile Use this file to : - set & export values of variables - set options such as ignoreeof that you want to apply to your login shell only - specify a script to execute when yu log out Example : set -o allexport # export all variables PATH=.:/bin:/usr/bin:$HOME/bin # define command search path CDPATH=.:$HOME:$HOME/games # define search path for cd FPATH=$HOME/mathlib:/usr/funcs # define path for autoload PS1='! $PWD> ' # define primary prompt PS2='Line continues here> ' # define secondary prompt HISTSIZE=100 # define size of history file ENV=$HOME/.kshrc # pathname of environment script TMOUT=0 # KornShell won't be timed out VISUAL=vi # make vi the comm. line editor set +o allexport # turn off allexport feature - script whose name is hold in the KornShell variable ENV Use this file to : - define aliases & functions that apply for interactive use only - set default options that you want to apply to all ksh invocations - set variables that you want to apply to the current ksh invoc. Example :

    5 of 37 9/7/2015 9:05

  • # The information in this region will be accessible to the KornShell # command line and scripts. alias -x disk='du' # -x makes alias accessible to scripts

    case $- in *i*) # Here you are NOT in a script alias copy='cp';; esac

    KornShell Reserved variables :

    +-----------+-----------------------------------+-------------------+------+ | Variable | What this variable holds | Default | Who | | | | | sets | +-----------+-----------------------------------+-------------------+------+ | CDPATH | directories that cd searches | none | U | | COLUMNS | terminal width | 80 | SA | | EDITOR | pathname of command line editor | /bin/ed | U,SA | | ENV | pathname of startup script | none | U,SA | | ERRNO | error number of most recently | none | KSH | | | failed system call | | | | FCEDIT | pathname of history file editor | /bin/ed | U,SA | | FPATH | path of autoload functions | none | U | | HISTFILE | pathname of history file | $HOME/.sh_history | U,SA | | HISTFILE | nb of command in history file | 128 | U,SA | | HOME | login directory | none | SA | | IFS | set of token delimiters | white space | U | | LINENO | current line number within | none | KSH | | | script or function | | | | LINES | terminal height | 24 | SA | | LOGNAME | user name | none | SA | | MAIL | patname of master mail file | none | SA | | MAILCHECK | mail checking frequency | 600 seconds | U,SA | | MAILPATH | pathnames of master mail files | none | SA | | OLDPWD | previous current directory | none | KSH | | OPTARG | name of argument to a switch | none | KSH | | OPTIND | option's ordinal position on | none | KSH | | | command line | | | | PATH | command search directories | /bin:/usr/bin | U,SA | | PPID | PID of parent | none | KSH | | PS1 | command line prompt | $ | U | | PS2 | prompt for commands that | > | U | | | extends more than 1 line | | | | PS3 | prompt of 'select' statements | #? | U | | PS4 | debug mode prompt | + | U | | PWD | current directory | none | U | | RANDOM | random integer | none | KSH |

    6 of 37 9/7/2015 9:05

  • | REPLY | input repository | none | KSH | | SECONDS | nb of seconds since KornShell | none | KSH | | | was invoked | | | | SHELL | executed shell (sh, csh, ksh) | none | SA | | TERM | type of terminal you're using | none | SA | | TMOUT | turn off (timeout) an unused | 0 (unlimited) | KSH | | | KornShell | | | | VISUAL | command line editor | /bin/ed | U,SA | | $ | PID of current process | none | KSH | | ! | PID of the background process | none | KSH | | ? | last command exit status | none | KSH | | _ | miscellaneous data | none | KSH | +-----------+-----------------------------------+-------------------+------+ | Variable | What this variable holds | Default | Who | | | | | sets | +-----------+-----------------------------------+-------------------+------+ Where U : User sets this variable SA : system administrator KSH: KornShell

    To get a list of exported objetcts available to the current environment :

    $ typeset -x # list of exported variables $ typeset -fx # list of exported functions

    To get a list of environment variables :

    $ set

    Most usual commands

    Help

    > man command Ex: > man man > man -k keyword list of commands related to this keyword > apropos keyword locates commands by keyword lookup > whatis command brief command description

    Directory listing

    3.

    7 of 37 9/7/2015 9:05

  • > ls [opt] -a list hidden files -d list the name of the current directory -F show directories with a trailing '/' executable files with a trailing '*' -g show group ownership of file in long listing -i print the inode number of each file -l long listing giving details about files and directories -R list all subdirectories encountered -t sort by time modified instead of name

    Creating / Deleting a directory

    > mkdir dir_name > rmdir dir_name (directory must be empty)

    Changing directory

    > cd pathname > cd > cd ~tristram > cd - # return to the previous working directory

    > pwd # display the path name of the working directory

    Comparing files

    > diff f1 f2 text files comparison > sdiff f1 f2 idem in 2 columns > diff dir1 dir2 directory comparison > cmp f1 f2 for binary files > file filename determine file type > comm f1 f2 compare lines common to 2 sorted files

    Access to files

    user group others r w x rwx rwx 4 2 1 > ls -l display access permission

    8 of 37 9/7/2015 9:05

  • > chmod 754 file change access (rwx r-x r--) > chmod u+x file1 gives yourself permition to execute file1 > chmod g+re file2 gives read and execute permissions for group members > chmod a+r *.pub gives read permition to everyone > umask 002 (default permissions : inverse) removes write permission for other in this example > groups username to find out which group 'username' belongs to > ls -gl list the group ownwership of the files > chgrp group_name file/directory_name change the group ownwership

    copying files and directories

    > cp [-opt] source destination > cp source path_to_destination copy a file into another > cp *.txt dir_name copy a file to another directory > cp -r dir1 dir2 copy several files into a directory > cat fil1 fil2 > fil3 concatenates fil1 and fil2, and places the result in fil3

    deleting files & directory

    > rm [opt] filename > rm -r dir_name > rmdir dirname

    moving files & directories

    > mv [opt] file1 file2 > mv [opt] dir1 dir2 > mv [opt] file dir

    Visualizing files

    > cat file1 file2 ... print all files on stdout > more file print 'file' on stdout, pausing at each end of page > pg file idem, with more options > od file octal dump for a binary file > tail file list the end of a file (last lines) > tail -n file idem for the last n lines

    9 of 37 9/7/2015 9:05

  • > tail -f file idem, but read repeatedly in case the file grows > tail +n file read the fisrt n lines of 'file' > head give first few lines

    linking files & directories

    > ln [-opt] source linkname The 2 names (source & linkname) address the same file or directory > ln part1.txt ../helpdata/sect1 /public/helpdoc/part1 This links part1.txt to ../helpdata/sect1 and /public/helpdoc/part1. > ln -s sdir/file . makes a symbolic link between 'file' in the subdirectory 'sdir' to the filename 'file' in the current directory > ln ~sandra/prog.c . To make a link to a file in another user's home directory > ln -s directory_name(s) directory_name To link one or more directories to another dir. > ln -s $HOME/accounts/may . To link a directory into your current directory Examples : > ln -s /net/cdfap2/user/jmb cdfap2 > ln -s ~frenkiel/cdf/man/manuel pfmanuel

    Compiling & Linking

    Use "man xxx" to have a precise description of the following commands :

    > cc C compiler > f77 Fortran compiler > ar archive & library maintainer > ld link editor > dbx symbolic debugger Examples : > cc hello.c executable : a.out > f77 hello.f idem > cc main.c func1.c func2.c sevaral files > cc hello.c -o hello redefine the executable name > cc -c func1.c compilation only, then : > cc main.c func1.o -o prog

    10 of 37 9/7/2015 9:05

  • Job control

    > nohup command run a command immune to hangups, logouts, and quits > at, batch execute commands at a later time (see 'man at') > jobs [-lp] [job_name] Display informations about jobs > kill -l Display signal numbers ans names > kill [-signal] job... Send a signal to the specified jobs > wait [job...] Wait for the specified jobs to terminate (or for all child processes if no argument) > ps List executing processes

    miscellaneous

    > who [am i] lists names of users currently logged in > rwho idem for all machines on the local network > w idem + what they are doing > whoami your userid > groups names of the groups you belong to > hostname name of the host currently connected > finger names of users, locally or remotly logged in > finger name information about this user > finger name@cdfhp3 > mail electronic mail > grep searching strings in files > sleep sleep for a given amount of time (shell scripts) > sort sort items in a file > touch change the modification time of a file > tar compress all files in a directory (and its subdirectories) into one file > type tells you where a command is located (or what it is an alias for) > find pathname -name "name" -print seach recursively from pathename for "name". "name" can contain wild chars. > findw string search recursively for filenames containing 'string' > file fich tries to guess the type of 'fich' (wild chars allowed) > passwd changing Pass Word > sh -x command Debugging a shell script > echo $SHELL Finding out which shell you are using /.../sh Bourne shell /.../csh C shell /.../tcsh TC shell

    11 of 37 9/7/2015 9:05

  • /.../ksh Korn shell /.../bash Bourne Again SHell > df gives a list of available disk space > du gives disk space used by the current directory and all its subdirectories > time command execute 'command' and then, gives the elapse time > ruptime gives the status of all machines on the local network > telnet host for remote login > rlogin host idem for machines running UNIX > stty set terminal I/O options (without args or with -a, list current settings) > tty, pty get the name of the terminal > write user_name send a message (end by < ctrl_d --> to a logged user > msg y enable message reception > msg n disable message recpt. > mes status of mes. recept. > wall idem write, but for all logged users. > date display date and time on standard output > ulimit set or display system ressource limits > whence command find pathname corresponding to 'command' > whence -v name gives the type of 'name' (built-in, alias, files ...) > tee [-a] file reads standard input, writes to standard output and file. Appends to 'file' if option -a > wc file Counts lines, words and chars in 'file'

    for other commands, looks in appendix or in directories such as :

    /bin /usr/bin /usr/ucb /usr/local/bin

    History & Command line editing

    > history > history 166 168 # list commands 166 through 168 > history -r 166 168 # idem in reverse order > history -2 # list previous 2 commands > history set # list commands from most recent set command > r # repeat last command > r cc # repeat most recent command starting with cc > r foo=bar cc # idem, changing 'foo' to 'bar' > r 215 # repeat command 215 > r math.c=cond.c 214 # repeat command 214, but substitute cond.c # for math.c

    12 of 37 9/7/2015 9:05

  • You can edit the command line with the 'vi' or 'emacs' editor :

    Put the following line inside a KornShell login script : FCEDIT=vi; export FCEDIT $ set -o emacs > fc [-e editor] [-nlr] [first [last]] * display (-l) commands from history file * Edit and re-execute previous commands (FCEDIT if no -e). 'last' and 'first' can be numbers or strings $ fc # edit a copy of last command $ fc 271 # edit, then re-execute command number 271 $ fc 270 272 # group command 270, 271 & 272, edit, re-execute

    Creating KORNshell scripts

    The different shells

    /bin/csh C shell (C like command syntax) /bin/sh Bourne shell (the oldest one) /bin/ksh Korn shell (variant of the previous one) + public domain (tcsh, bash, ...)

    Special shell variables

    There are some variables which are set internally by the shell and which are available to the user:

    $1 - $9 these variables are the positional parameters. $0 the name of the command currently being executed. $argv[20] refers to the 20th command line argument $# the number of positional arguments given to this invocation of the shell. $? the exit status of the last command executed is given as a decimal string. When a command completes successfully, it returns the exit status of 0 (zero), otherwise it returns a non-zero exit status. $$ the process number of this shell - useful for including in filenames, to make them unique.

    4.

    13 of 37 9/7/2015 9:05

  • $! the process id of the last command run in the background. $- the current options supplied to this invocation of the shell. $* a string containing all the arguments to the shell, starting at $1. $@ same as above, except when quoted : "$*" expanded into ONE long element : "$1 $2 $3" "$@" expanded into THREE elements : "$1" "$2" "$3" shift : $2 -> $1 ...)

    special characters

    The special chars of the Korn shell are : $ \ # ? [ ] * + & | ( ) ; ` " '- A pair of simple quotes '...' turns off the significance of ALL enclosed chars- A pair of double quotes "..." : idem except for $ ` " \- A '\' shuts off the special meaning of the char immediately to its right. Thus, \$ is equivalent to '$'.- In a script shell : # : all text that follow it up the newline is a comment \ : if it is the last char on a line, signals a continuation line qui suit est la continuation de celle-ci

    Evaluating shell variables

    The following set of rules govern the evaluation of all shell variables.

    $var signifies the value of var or nothing, if var is undefined. ${var} same as above except the braces enclose the name of the variable to be substituted. +-------------------+---------------------------+-------------------+ | Operation | if str is unset or null | else | +-------------------+---------------------------+-------------------+ | var=${str:-expr} | var= expr | var= ${string} | | var=${str:=expr} | str= expr ; var= expr | var= ${string} | | var=${str:+expr} | var becomes null | var= expr | | var=${str:?expr} | expr is printed on stderr | var= ${string} | +-------------------+---------------------------+-------------------+

    The if statement

    14 of 37 9/7/2015 9:05

  • The if statement uses the exit status of the given command

    if test then commands (if condition is true) else commands (if condition is false) fi

    if statements may be nested:

    if ... then ... else if ... ... fi fi

    Test on numbers :

    ((number1 == number2)) ((number1 != number2)) ((number1 number2)) ((number1 > number2)) ((number1 = number2)) ((number1 >= number2)) Warning : 5 different possible syntaxes (not absolutely identical) : if ((x == y)) if test $x -eq $y if let "$x == $y" if [ $x -eq $y ] if [[ $x -eq $y ]]

    Test on strings: (pattern may contain special chars)

    [[string = pattern]] [[string != pattern]] [[string1 string2]] [[string1 > string2]] [[ -z string]] true if length is zero [[ -n string]] true if length is not zero Warning : 3 different possible syntaxes : if [[ $str1 = $str2 ]] if [ "$str1" = "$str2" ] if test "$str1" = "$str2"

    Test on objects : files, directories, links ...

    15 of 37 9/7/2015 9:05

  • examples : [[ -f $myfile ]] # is $myfile a regular file? [[ -x /usr/users/judyt ]] # is this file executable? +---------------+---------------------------------------------------+ | Test | Returns true if object... | +---------------+---------------------------------------------------+ | -a object | exist; any type of object | | -f object | is a regular file or a symbolic link | | -d object | is a directory | | -c object | is a character special file | | -b object | is a block special file | | -p object | is a named pipe | | -S object | is a socket | | -L object | is a symbolic (soft) link with another object | | -k object | object's "sticky bit" is set | | -s object | object isn't empty | | -r object | I may read this object | | -w object | I may write to (modify) this object | | -x object | object is an executable file | | | or a directory I can search | | -O object | I ownn this object | | -G object | the group to which I belong owns object | | -u object | object's set-user-id bit is set | | -g object | object's set-group-id bit is set | | obj1 -nt obj2 | obj1 is newer than obj2 | | obj1 -ot obj2 | obj1 is older than obj2 | | obj1 -ef obj2 | obj1 is another name for obj2 (equivalent) | +---------------+---------------------------------------------------+

    The logical operators

    You can use the && operator to execute a command and, if it is successful, execute the next command in the list. For example:

    cmd1 && cmd2

    cmd1 is executed and its exit status examined. Only if cmd1 succeeds is cmd2 executed. You can use the || operator to execute a command and, if itfails, execute the next command in the command list.

    cmd1 || cmd2

    Of course, ll combinaisons of these 2 operators are possible. Example :

    cmd1 || cmd2 && cmd3

    16 of 37 9/7/2015 9:05

  • Math operators

    First, don't forget that you have to enclose the entire mathematical operation within a DOUBLE pair of parentheses. A single pair has a completelydifferent meaning to the Korn-Shell.

    +-----------+-----------+-------------------------+ | operator | operation | example | +-----------+-----------+-------------------------+ | + | add. | ((y = 7 + 10)) | | - | sub. | ((y = 7 - 10)) | | * | mult. | ((y = 7 * 4)) | | / | div. | ((y = 37 / 5)) | | % | modulo | ((y = 37 + 5)) | | | shift | ((y = 2#1011 2)) | | >> | shift | ((y = 2#1011 >> 2)) | | & | AND | ((y = 2#1011 & 2#1100)) | | ^ | excl OR | ((y = 2#1011 ^ 2#1100)) | | | | OR | ((y = 2#1011 | 2#1100)) | +-----------+-----------+-------------------------+

    Controlling execution

    goto my_label ...... my_label: ----- case value in pattern1) command1 ; ... ; commandN;; pattern2) command1 ; ... ; commandN;; ........ patternN) command1 ; ... ; commandN;; esac where : value value of a variable pattern any constant, pattern or group of pattern command name of any program, shell script or ksh statement example 1 : case $advice in [Yy][Ee][Ss]) print "A yes answer";; [Mm]*) print "M followed by anything";; +([0-9)) print "Any integer...";; "oui" | "bof") print "one or the other";; *) print "Default";; example 2 : Creating nice menus

    17 of 37 9/7/2015 9:05

  • PS3="Enter your choice :" select menu_list in English francais do case $menu_list in English) print "Thank you";; francais) print "Merci";; *) print "???"; break;; esac done ----- while( logical expression) do .... done while : # infinite loop .... done while read line # read until an EOF (or ) do .... done fname # redirect input within this while loop until( logical expression) do .... done fout # redirect both input and output ----- for name in 1 2 3 4 # a list of elements do .... done for obj in * # list of every object in the current directory do .... done for obj in * */* # $PWD and the next level below it contain do .... done ----- break; # to leave a loop (while, until, for) continue; # to skip part of one loop iteration # nested loops are allowed in ksh ---- select ident in Un Deux # a list of identifiers do case $ident in Un) ....... ;;

    18 of 37 9/7/2015 9:05

  • Deux) ..... ;; *) print " Defaut" ;; esac done

    Debug mode

    > ksh -x script_name ou, dans un 'shell script' : set -x # start debug mode set +x # stop debug mode

    Examples

    Example 1 : loops, cases ...

    #!/bin/ksh USAGE="usage : fmr [dir_name]" # how to invoke this script print " +------------------------+ | Start fmr shell script | +------------------------+ " function fonc { echo "Loop over params, with shift function" for i do print "parameter $1" # print is equivalent to echo shift done # Beware that $# in now = 0 !!! } echo "Loop over all ($#) parameters : $*" for i do echo "parameter $i" done #---------------------- if (( $# > 0 )) # Is the first arg. a directory name ? then dir_name=$1 else print -n "Directory name:" read dir_name fi

    19 of 37 9/7/2015 9:05

  • print "You specified the following directory; $dir_name" if [[ ! -d $dir_name ]] then print "Sorry, but $dir_name isn't the name of a directory" else echo "-------- List of directory $dir_name -----------------" ls -l $dir_name echo "------------------------------------------------------" fi #---------------------- echo "switch on #params" case $# in 0) echo "command with no parameter";; 1) echo "there is only one parameter : $1";; 2) echo "there are two parameters";; [3,4]) echo "3 or 4 params";; *) echo "more than 4 params";; esac #---------------------- fonc echo "Parameters number (after function fonc) : $#" #------- To read and execute a command echo "==> Enter a name" while read com do case $com in tristram) echo "gerard";; guglielmi) echo "laurent";; dolbeau) echo "Jean";; poutot) echo "Daniel ou Claude ?";; lutz | frenkiel) echo "Pierre";; brunet) echo "You lost !!!"; exit ;; *) echo "Unknown guy !!! ( $com )"; break ;; esac echo "==> another name, please" done #------ The test function : echo "Enter a file name" read name if [ -r $name ] then echo "This file is readable" fi if [ -w $name ] then echo "This file is writable" fi if [ -x $name ] then echo "This file is executable"

    20 of 37 9/7/2015 9:05

  • fi #------ echo "--------------- Menu select ----------" PS3="Enter your choice: " select menu_list in English francais quit do case $menu_list in English) print "Thank you";; francais) print "Merci.";; quit) break;; *) print " ????";; esac done print "So long!"

    Example 2 : switches

    #!/bin/ksh USAGE="usage: gopt.ksh [+-d] [ +-q]" # + and - switches while getopts :dq arguments # note the leading colon do case $arguments in d) compile=on;; # don't precede d with a minus sign +d) compile=off;; q) verbose=on;; +q) verbose=off;; \?) print "$OPTARG is not a valid option" print "$USAGE";; esac done print "compile=$compile - verbose= $verbose"

    Example 3

    ############################################################### # This is a function named 'sqrt' function sqrt # square the input argument { ((s = $1 * $1 )) } # In fact, all KornShell variables are, by default, global # (execpt when defined with typeset, integer or readonly) # So, you don't have to use 'return $s' ############################################################### # The shell script begins execution at the next line

    21 of 37 9/7/2015 9:05

  • print -n "Enter an integer : " read an_integer sqrt $an_integer print "The square of $an_integer is $s"

    Example 4

    #!/bin/ksh ############ Using exec to do I/O on multiple files ############ USAGE="usage : ex4.ksh file1 file2" if (($# != 2)) # this script needs 2 arguments then print "$USAGE" exit 1 fi

    ############ Both arguments must be readable regular files if [[ (-f $1) && (-f $2) && (-r $1) && (-r $2) ]] then # use exec to open 4 files exec 3 nomatch # open file "nomatch" for output else # if user enters bad arguments print "$ USAGE" exit 2 fi while read -u3 lineA # read a line on descriptor 3 do read -u4 lineB # read a line on descriptor 4 if [ "$lineA" = "$lineB" ] then # send matching line to one file print -u5 "$lineA" else # send nonmatching lines to another print -u6 "$lineA; $lineB" fi done

    print "Done, today : $(date)" # $(date) : output of 'date' command date_var=$(date) # or put it in a variable print " I said $date_var" # and print it...

    Example 5

    ############ String manipulation examples ##################

    22 of 37 9/7/2015 9:05

  • read str1?"Enter a string: " print "\nYou said : $str1" typeset -u str1 # Convert to uppercase print "UPPERCASE: $str1" typeset -l str1 # Convert to lowercase print "lowercase: $str1" typeset +l str1 # turn off lowercase attribute read str2?"Enter another one: " str="$str1 and $str2" #concatenate 2 strings print "String concatenation : $str" # use '#' to delete from left # '##' to delete all # '%' to delete all # '%%' to delete from right print "\nRemove the first 2 chars -- ${str#??}" print "Remove up to (including) the first 'e' -- ${str#*e}" print "Remove the first 2 words -- ${str#* * }" print "\nRemove the last 2 chars -- ${str%??}" print "Remove from last 'e' -- ${str%e*}" print "Remove the last 2 tokens -- ${str% * *}" print "length of the string= ${#str}" ######################## # Parsing strings into words : typeset -l line # line will be stored in lowercase read finp?"Pathname of the file to analyze: " read fout?"Pathname of the file to store words: " # Set IFS equal to newline, space, tab and common punctuation marks IFS=" ,. ;!?" while read line # read one line of text do # then Parse it : if [[ "$line" != "" ]] # ignore blank lines then set $line # parse the line into words print "$*" # print each word on a separate line fi done < $finp > $fout # define the input & output paths sort $fout | uniq | wc -l # UNIX utilities

    List of Usual commands5.

    23 of 37 9/7/2015 9:05

  • Support this site, buy deep discounted Computer Books here!

    adb absolute debuggeradjust simple text formatteradmin create and administer SCCS filesar maintain portable archives and librariesas assemblerasa interpret ASA carriage control charactersastrn translate assembly languageat, batch execute commands at a later timeatime time an assembly language instruction sequenceatrans translate assembly languageawk pattern - directed scanning and processing languagebanner make posters in large lettersbasename, dirname extract portions of path namesbc arbitrary - precision arithmetic languagebdftosnf BDF to SNF font compiler for X11bdiff big diffbfs big file scannerbifchmod change mode of a BIF filebifchown, bifchgrp change file owner or groupbifcp copy to or from BIF filesbiffind find files in a BIF systembifls list contents of BIF directoriesbifmkdir make a BIF directorybifrm, bifrmdir remove BIF files or directoriesbitmap, bmtoa bitmap editor and converter utilitiesbs a compiler/interpreter for modest - sized programscal print calendarcalendar reminder servicecat concatenate, copy, and print filescb C program beautifier, formattercc, c89 C compilercd change working directorycdb, fdb, pdb C, C++, FORTRAN, Pascal symbolic debuggercdc change the delta commentary of an SCCS deltacflow generate C flow graphchacl add, modify, delete, copy, or summarize access conchatr change program's internal attributeschecknr check nroff/troff fileschfn change finger entrychmod change file modechown, chgrp change file owner or groupchsh change default login shellci check in RCS revisionsclear clear terminal screencmp compare two files

    24 of 37 9/7/2015 9:05

  • cnodes display information about specified cluster nodesco check out RCS revisionscol filter reverse line - feeds and backspacescomb combine SCCS deltascomm select or reject lines common to two sorted filescompact, uncompact compact and uncompact filescp copy files and directory subtreescpio copy file archives in and outcpp the C language preprocessorcrontab user crontab filecrypt encode/decode filescsh a shell (command interpreter) with C - like syntaxcsplit context splitct spawn getty to a remote terminal (call terminal)ctags create a tags filecu call another (UNIX) system; terminal emulatorcut cut out (extract) selected fields of each line of acxref generate C program cross - referencedate print or set the date and timedatebook calendar and reminder program for X11dbmonth datebook monthly calendar formatter for postscriptdbweek datebook weekly calendar formatter for postscriptdc desk calculatordd convert, reblock, translate, and copy a (tape) filedelta make a delta (change) to an SCCS filederoff remove nroff, tbl, and neqn constructsdiff differential file and directory comparatordiff3 3 - way differential file comparisondiffmk mark differences between filesdircmp directory comparisondomainname set or display name of Network Information Ser -dos2ux, ux2dos convert ASCII file formatdoschmod change attributes of a DOS filedoscp copy to or from DOS filesdosdf report number of free disk clustersdosls, dosll list contents of DOS directoriesdosmkdir make a DOS directorydosrm, dosrmdir remove DOS files or directoriesdu summarize disk usageecho echo (print) argumentsed, red text editorelm process mail through screen - oriented interfaceelmalias create and verify elm user and system aliasesenable, disable enable/disable LP printersenv set environment for command executionet Datebook weekly calendar formatter for laserjetex, edit extended line - oriented text editor

    25 of 37 9/7/2015 9:05

  • expand, unexpand expand tabs to spaces, and vice versaexpr evaluate arguments as an expressionexpreserve preserve editor bufferfactor, primes factor a number, generate large primesfile determine file typefind find filesfindmsg, dumpmsg create message catalog file for modificationfindstr find strings for inclusion in message catalogsfinger user information lookup programfixman fix manual pages for faster viewing withfold fold long lines for finite width output deviceforder convert file data orderfrom who is my mail from?ftio faster tape I/Oftp file transfer programgencat generate a formatted message catalog fileget get a version of an SCCS filegetaccess list access rights togetconf get system configuration valuesgetcontext display current contextgetopt parse command optionsgetprivgrp get special attributes for groupgprof display call graph profile datagrep, egrep, fgrep search a file for a patterngroups show group membershipsgwindstop terminate the window helper facilityhelp ask for helphostname set or print name of current host systemhp handle special functions of HP2640 and HP2621 - serieshpterm X window system Hewlett - Packard terminal emulator.hyphen find hyphenated wordsiconv code set conversionid print user and group IDs and namesident identify files in RCSied input editor and command history for interactive progsimageview display TIFF file images on an X11 displayintro introduction to command utilities and applicationiostat report I/O statisticsipcrm remove a message queue, semaphore set or sharedipcs report inter - process communication facilities statusjoin relational database operatorkermit kermit file transferkeysh context - sensitive softkey shellkill terminate a processksh, rksh shell, the standard/restricted command programlastcomm show last commands executed in reverse orderld link editor

    26 of 37 9/7/2015 9:05

  • leave remind you when you have to leavelex generate programs for lexical analysis of textlifcp copy to or from LIF fileslifinit write LIF volume header on filelifls list contents of a LIF directorylifrename rename LIF fileslifrm remove a LIF fileline read one line from user inputlint a C program checker/verifierln link files and directorieslock reserve a terminallogger make entries in the system loglogin sign onlogname get login namelorder find ordering relation for an object librarylp, cancel, lpalt send/cancel/alter requests to an LP linelpstat print LP status informationls, l, ll, lsf, lsr, lsxlist contents of directorieslsacl list access control lists (ACLs) of filesm4 macro processormail, rmail send mail to users or read mailmailfrom summarize mail folders by subject and sendermailstats print mail traffic statisticsmailx interactive message processing systemmake maintain, update, and regenerate groups of programsmakekey generate encryption keyman find manual information by keywords; print out amediainit initialize disk or cartridge tape mediamerge three - way file mergemesg permit or deny messages to terminalmkdir make a directorymkfifo make FIFO (named pipe) special filesmkfontdir create fonts.dir file from directory of fontmkmf make a makefilemkstr extract error messages from C source into a filemktemp make a name for a temporary filemm, osdd print documents formatted with the mm macrosmore, page file perusal filter for crt viewingmt magnetic tape manipulating programmv move or rename files and directoriesmwm The Motif Window Manager.neqn format mathematical text for nroffnetstat show network statusnewform change or reformat a text filenewgrp log in to a new groupnewmail notify users of new mail in mailboxesnews print news items

    27 of 37 9/7/2015 9:05

  • nice run a command at low prioritynl line numbering filternljust justify lines, left or right, for printingnlsinfo display native language support informationnm print name list of common object filenm print name list of common object file.nm print name list of object filenodename assign a network node name or determine currentnohup run a command immune to hangups, logouts, and quitsnroff format textnslookup query name servers interactivelyod, xd octal and hexadecimal dumpon execute command on remote host with environment similarpack, pcat, unpack compress and expand filespam Personal Applications Manager, a visual shellpasswd change login passwordpaste merge same lines of several files or subsequentpathalias electronic address routerpax portable archive exchangepcltrans translate a Starbase bitmap file into PCL rasterpg file perusal filter for soft - copy terminalsppl point-to - point serial networkingpplstat give status of each invocation ofpr print filespraliases print system - wide sendmail aliasesprealloc preallocate disk storageprintenv print out the environmentprintf format and print argumentsprmail print out mail in the incoming mailbox fileprof display profile dataprotogen ANSI C function prototype generatorprs print and summarize an SCCS fileps, cps report process statusptx permuted indexpwd working directory namepwget, grget get password and group informationquota display disk usage and limitsrcp remote file copyrcs change RCS file attributesrcsdiff compareRCS revisionsrcsmerge merge RCS revisionsreadmail read mail from specified mailboxremsh execute from a remote shellresize reset shell parameters to reflect the current sizerev reverse lines of a filergb X Window System color database creator.rlog print log messages and other information on RCS files

    28 of 37 9/7/2015 9:05

  • rlogin remote loginrm remove files or directoriesrmdel remove a delta from an SCCS filermdir remove directoriesrmnl remove extra new - line characters from filerpcgen an RPC protocol compilerrtprio execute process with real - time priorityrup show host status of local machines (RPC version)ruptime show status of local machinesrusers determine who is logged in on machines on localrwho show who is logged in on local machinessact print current SCCS file editing activitysar system activity reportersb2xwd translate Starbase bitmap to xwd bitmap formatsbvtrans translate a Starbase HPSBV archive to Personalsccsdiff compare two versions of an SCCS filescreenpr capture the screen raster information andscript make typescript of terminal sessionsdfchmod change mode of an SDF filesdfchown, sdfchgrp change owner or group of an SDF filesdfcp, sdfln, sdfmv copy, link, or move files to/from ansdffind find files in an SDF systemsdfls, sdfll list contents of SDF directoriessdfmkdir make an SDF directorysdfrm, sdfrmdir remove SDF files or directoriessdiff side-by - side difference programsed stream text editorsh shell partially based on preliminary POSIX draftsh, rsh shell, the standard/restricted command programmingshar make a shell archive packageshl shell layer managershowcdf show the actual path name matched for a CDFsize print section sizes of object filessleep suspend execution for an intervalslp set printing options for a non - serial printersoelim eliminate .so's from nroff inputsoftbench SoftBench Software Development Environmentsort sort and/or merge filesspell, hashmake spelling errorssplit split a file into piecesssp remove multiple line - feeds from outputstconv Utility to convert scalable type symbol set mapstlicense server access control program for Xstload Utility to load Scalable Type outlinesstmkdirs Utility to build Scalable Type ``.dir'' andstmkfont Scalable Typeface font compiler to create X andstrings find the printable strings in an object or other

    29 of 37 9/7/2015 9:05

  • strip strip symbol and line number information from anstty set the options for a terminal portsu become super - user or another usersum print checksum and block or byte count oftabs set tabs on a terminaltar tape file archivertbl format tables for nrofftcio Command Set 80 CS/80 Cartridge Tape Utilitytee pipe fittingtelnet user interface to the TELNET protocoltest condition evaluation commandtftp trivial file transfer programtime time a commandtimex time a command; report process data and systemtouch update access, modification, and/or change times oftput query terminfo databasetr translate characterstrue, false return zero or one exit status respectivelytset, reset terminal - dependent initializationtsort topological sortttytype terminal identification programul do underliningumask set file - creation mode maskumodem XMODEM - protocol file transfer programuname print name of current HP - UX versionunget undo a previous get of an SCCS fileunifdef remove preprocessor linesuniq report repeated lines in a fileunits conversion programuptime show how long system has been upusers compact list of users who are on the systemuucp, uulog, uuname UNIX system to UNIX system copyuuencode, uudecode encode/decode a binary file foruupath, mkuupath access and manage the pathalias databaseuustat uucp status inquiry and job controluuto, uupick public UNIX system to UNIX system file copyuux UNIX system to UNIX system command executionvacation return ``I am not here'' indicationval validate SCCS filevc version controlvi screen - oriented (visual) display editorvis, inv make unprintable characters in a file visible orvmstat report virtual memory statisticsvt log in on another system over lanwait await completion of processwc word, line, and character countwhat get SCCS identification information

    30 of 37 9/7/2015 9:05

  • which locate a program file including aliases and pathswho who is on the systemwhoami print effective current user idwrite interactively write (talk) to another userx11start start the X11 window systemxargs construct argumentxcal display calendar in an X11 windowxclock analog / digital clock for Xxdb C, FORTRAN, Pascal, and C++ Symbolic Debuggerxdialog display a message in an X11 Motif dialog windowxfd font displayer for Xxhost server access control program for Xxhpcalc Hewlett - Packard type calculator emulatorxinit X Window System initializerxinitcolormap initialize the X colormapxline an X11 based real - time system resource observationxload load average display for Xxlsfonts server font list displayer for Xxmodmap utility for modifying keymaps in Xxpr print an X window dumpxrdb X server resource database utilityxrefresh refresh all or part of an X screenxseethru opens a transparent window into the image planesxset user preference utility for Xxsetroot root window parameter setting utility for Xxstr extract strings from C programs to implement sharedxtbdftosnf BDF to SNF font compiler (HP 700/RX)xterm terminal emulator for Xxthost server access control program for Xxtmkfontdir create a fonts.dir file for a directory ofxtshowsnf print contents of an SNF file (HP 700/RX)xtsnftosnf convert SNF file from one format to another (HPxwcreate create a new X windowxwd dump an image of an X windowxwd2sb translate xwd bitmap to Starbase bitmap formatxwdestroy destroy one or more existing windowsxwininfo window information utility for Xxwud image displayer for Xyacc yet another compiler - compileryes be repetitively affirmativeypcat print all values in Network Information Service mapypmatch print values of selected keys in Network Informationyppasswd change login password in Network Information Systemypwhich list which host is Network Information System

    31 of 37 9/7/2015 9:05

  • List of Administrator commands

    accept, reject allow/prevent LP requestsacctcms command summary from per - process accountingacctcom search and print process accountingacctcon1, acctcon2 time accountingacctdisk, acctdusg overview of accountacctmerg merge or add total accounting filesacctprc1, acctprc2 process accountingarp address resolution display and controlaudevent change or display event or system call auditaudisp display the audit information as requested by theaudomon audit overflow monitor daemonaudsys start or halt the auditing system and set oraudusr select users to auditautomount automatically mount NFS file systemsbackup backup or archive file systembdf report number of free disk blocks (Berkeley version)bifdf report number of free disk blocksbiffsck Bell file system consistency check and interactivebiffsdb Bell file system debuggerbifmkfs construct a Bell file systemboot bootstrap processbootpd Internet Boot Protocol serverbootpquery send BOOTREQUEST to BOOTP serverbrc, bcheckrc, rc system initializabuildlang generate and display locale.def filecaptoinfo convert a termcap description into a terminfocatman create the cat files for the manualccck HP Cluster configuration file checkerchroot change root directory for a commandclri clear inodeclrsvc clear x25 switched virtual circuitcluster allocate resources for clustered operationconfig configure an HP - UX systemconvertfs convert a file system to allow long file namescpset install object files in binary directoriescron clock daemoncsp create cluster server processesdevnm device name

    6.

    32 of 37 9/7/2015 9:05

  • df report number of free disk blocksdiskinfo describe characteristics of a disk devicedisksecn calculate default disk section sizesdiskusg generate disk accounting data by user IDdmesg collect system diagnostic messages to form error logdrm admin Data Replication Manager administrative tooldump, rdump incremental file system dump, local or acrossdumpfs dump file system informationedquota edit user disk quotaseisa config EISA configuration toolenvd system physical environment daemonfbackup selectively backup filesfingerd remote user information serverfrecover selectively recover filesfreeze freeze sendmail configuration file on a clusterfsck file system consistency check and interactive repairfsclean determine shutdown status of specified file systemfsdb file system debuggerfsirand install random inode generation numbersftpd DARPA Internet File Transfer Protocol serverfuser, cfuser list process IDs of all processes that havefwtmp, wtmpfix manipulate connect accounting recordsgated gateway routing daemongetty set terminal type, modes, speed, and line discip.getx25 get x25 lineglbd Global Location Broker Daemongrmd graphics resource manager daemongwind graphics window daemonhosts to named Translate host table to name server fileifconfig configure network interface parametersinetd Internet services daemoninit, telinit process control initializationinsf install special filesinstall install commandsinstl adm maintain network install message and defaultintro introduction to system maintenance commands andioinit initialize I/O systemioscan scan I/O systemisl initial system loaderkillall kill all active processeslanconfig configure network interface parameterslanscan display LAN device configuration and statuslast, lastb indicate last logins of users and ttyslb admin Location Broker administrative toollb test test the Location Brokerlink, unlink exercise link and unlink system callsllbd Local Location Broker daemon

    33 of 37 9/7/2015 9:05

  • lockd network lock daemonlpadmin configure the LP spooling systemlpana print LP spooler performance analysis informationlpsched, lpshut start/stop the LP requestls admin Display and edit the license server databasels rpt Report on license server eventsls stat Display the status of the license server systemls targetid Prints information about the local NetLS tarls tv Verify that Network License Servers are workinglsdev list device drivers in the systemlssf list a special filemakecdf create context - dependent filesmakedbm make a Network Information System databasemkboot, rmboot install, update, or remove boot programsmkdev make device filesmkfs construct a file systemmklost+found make a lost+found directorymklp configure the LP spooler subsystemmknod create special filesmkpdf create a Product Description File from a prototypemkrs construct a recovery systemmksf make a special filemount, umount mount and unmount file systemmountd NFS mount request servermvdir move a directorynamed Internet domain name serverncheck generate path names from inode numbersnetdistd network file distribution (update) server daemonnetfmt format tracing and logging binary files.netlsd Starts the license servernettl control network tracing and loggingnettlconf configure network tracing and logging commandnettlgen generate network tracing and logging commandsnewfs construct a new file systemnfsd, biod NFS daemonsnfsstat Network File System statisticsnrglbd Non - Replicatable Global Location Broker daemonopx25 execute HALGOL programspcnfsd PC - NFS daemonpcserver Basic Serial and HP AdvanceLink serverpdc processor - dependent code (firmware)pdfck compare Product Description File to File Systempdfdiff compare two Product Description Filesperf test the NCS RPC runtime libraryping send ICMP ECHO REQUEST packets to network hostsportmap DARPA port to RPC program number mapperproxy manipulates the NS Probe proxy table

    34 of 37 9/7/2015 9:05

  • pwck, grpck password/group file checkersquot summarize file system ownershipquotacheck file system quota consistency checkerquotaon, quotaoff turn file system quotas on and offrbootd remote boot serverrcancel remove requests from a remote line printer spoolreboot reboot the systemrecoversl check and recover damaged or missing sharedregen regenerate (uxgen) an updated HP - UX systemremshd remote shell serverrepquota summarize quotas for a file systemrestore, rrestore restore file system incrementally, localrevck check internal revision numbers of HP - UX filesrexd RPC - based remote execution serverrexecd remote execution serverripquery query RIP gatewaysrlb remote loopback diagnosticrlbdaemon remote loopback diagnostic serverrlogind remote login serverrlp send LP line printer request to a remote systemrlpdaemon remote spooling line printer daemon, messagerlpstat print status of LP spooler requests on a remotermfn remove HP - UX functionality (partitions and filesets)rmsf remove a special filermt remote magnetic - tape protocol moduleroute manually manipulate the routing tablesrpcinfo report RPC informationrquotad remote quota serverrstatd kernel statistics serverrunacct run daily accountingrusersd network username serverrwall write to all users over a networkrwalld network rwall serverrwhod system status serversa1, sa2, sadc system activity report packagesam system administration managersavecore save a core dump of the operating systemsdfdf report number of free SDF disk blockssdffsck SDF file system consistency check, interactivesdffsdb examine/modify an SDF file systemsdsadmin create and administer Software Disk Stripingsendmail send mail over the internetsetmnt establish mount table /etc/mnttabsetprivgrp set special attributes for groupshowmount show all remote mountsshutdown terminate all processingsig named send signals to the domain name server

    35 of 37 9/7/2015 9:05

  • snmpd daemon that responds to SNMP requestsspray spray packetssprayd spray serverstatd network status monitorstcode translate hexadecimal status code value to textualsubnetconfig configure subnet behaviorswapinfo system swap space informationswapon enable additional device or file system for pagingsync synchronize file systemssyncer periodically sync for file system integritysysdiag online diagnostic system interfacesyslogd log systems messagessysrm remove optional HP - UX products (filesets)telnetd TELNET protocol servertftpd trivial file transfer protocol servertic terminfo compilertunefs tune up an existing file systemuntic terminfo de - compilerupdate, updist update or install HP - UX files (softwareuucheck check the uucp directories and permissions fileuucico transfer files for the uucp systemuuclean uucp spool directory clean - upuucleanup uucp spool directory clean - upuugetty set terminal type, modes, speed and line discip.uuid gen UUID generating programuuls list spooled uucp transactions grouped by transactionuusched schedule uucp transport filesuusnap show snapshot of the UUCP systemuusnaps sort and embellish uusnap outputuusub monitor uucp networkuuxqt execute remote uucp or uux command requestsuxgen generate an HP - UX systemvhe altlog login when Virtual Home Environment (VHE) homevhe mounter start the Virtual Home Environment (VHE)vhe u mnt perform Network File System (NFS) mount tovipw edit the password filevtdaemon respond to vt requestswall, cwall write to all userswhodo which users are doing whatxdm X Display Managerxtptyd X terminal pty daemon programypinit build and install Network Information Service dataypmake create or rebuild Network Information Service datayppasswdd daemon for modifying Network Information Serviceyppoll query NIS server for information about NIS mapyppush force propagation of Network Information Serviceypserv, ypbind Network Information Service server and

    36 of 37 9/7/2015 9:05

  • ypset bind to particular Network Information Service

    37 of 37 9/7/2015 9:05