AIX笔记3

Unit 9.  Using Shell Variables

Shell variable conventions
All shell variable names are case-sensitive. For example, HOME and home are not the same.
As a convention, uppercase names are used for the standard variables set by the system and lowercase names are used for the variables set by the user.

Additional variables
In addition to the variables discussed above, there are other variables that the shell maintains which will be discussed later.

Setting variables
The set command displays the names and values of all shell variables. The set command is a built-in command of the shell, and therefore gives a different output depending on the shell being run, for instance a Bourne or a Korn shell.

Variable contents
Variables can hold any type of data, like integer numbers, single words, text strings or even complex numbers.
It is up to the application referencing the variable to decide what to do with the contents of that variable.
The contents of the system-defined variables is fairly static, for example, the HOME variable can only contain a path to a directory file and not, for instance, a file.

Listing variables
To set a variable, use the = with NO SPACES on either side. Once the variable has been set, to refer to the value of that variable precede the variable name with a $. There must be NO SPACE between the $ and the variable name.
The echo command displays the string of text to standard out (by default to the screen).

$ xy=day
$ echo  $xy
day
$ echo Tomorrow is Tues$xy
Tomorrow is Tuesday
$ echo There will be a $xylong meeting
There will be a meeting
$ echo There will be a ${xy}long meeting
There will be a daylong meeting
Examples
Notice there need not be a space BEFORE the $ of the variable in order for the shell to do variable substitution. Note, though, what happened when there was no space AFTER the variable name. The shell searched for a variable whose name was xylong, which did not exist. When a variable that has not been defined is referenced, the user does not get an error. Rather a null string is returned.
To eliminate the need for a space after the variable name, the curly braces { } are used. Note that the $ is OUTSIDE of the braces.

Variable = `Output from a Command`
$ date
Wed 11 Jul 11:38:39 2003
$ now=$(date) (or now=`date`)
$ echo $now
Wed 11 Jul 11:38:39 2003
$ HOST=$(hostname) (or HOST=`hostname`)
$ echo $HOST
sys1
$ echo "Today is `date` and `who | wc -l` users \
> are logged in"
Today is Wed 11 Jul 11:45:27 2003 and 4 users are logged in

Setting variables with command output
A variable can be set to the output of some command or group of commands by using the back quotes (also referred to as grave accents). They should not be mistaken for single quotes. In the examples the output of the date and who commands are stored in variables.
The back quotes are supported by the bourne shell, C shell and Korn shell. The use of $(command) is specific to the Korn shell.
When the shell sees a command substitution string on a command line, it will execute the enclosed command and will then substitute the entire command substitution string with the standard output of that command. After completing the substitution(s), the shell will then execute the resulting line.

The use of quotes
Quoting is used to override the shell's interpretation of special characters. Quotes allow a metacharacter to be interpreted literally instead of expanded.
You can use the backslash \ to stop the shell from interpreting one of the quoted characters.
For example:
$ echo "This is a double quote \""
This is a double quote "

''Single Quotes:Ignores the special meaning of the following character
$ echo '$HOME'
$HOME
""Double Quotes:Ignores all metacharacters except for dollar $, backquotes ` and backslash \
$ echo "$HOME"
/home/team01
\ Backslash:Ignores all metacharacters between the quotes
$ echo \$HOME
$HOME

Command line parsing options
When the shell parses a command line, it is breaking the line into a series of words.
One of these words determines which command will execute. Other words are information passed to the commands such as file names and options. Some of the words are instructions to the shell, like redirection.
Understand from this that the shell does a lot of “stuff” with a command line before the command ever gets to execute. The order in which the shell reads and processes a command is done from left to right. In logical order, the shell looks for redirection, command and variable substitution, wildcard expansion. The command is then executed.

Unit Summary
The shell has variables which define your environment and lets you define variables of your own.
Variables can be set to a value which can then be referenced and used within scripts.
The following quoting metacharacters have been discussed:
– Double quote (" ")
– Single quote   ('  ')
– Backslash ( \ )
Perform command substitution using either backquotes (``) or $(command).

---------------------------------------------------------------------------------------------

Unit 10.  Processes

The variable $$ shows the process ID of the current shell:
$ echo $$
4712
The ps command shows the running processes:
$ ps -u team01

AIX processes
A program or a command that is actually running on a system is referred to as a process. AIX can run a number of different processes at the same time as well as many occurrences of a program (such as vi) existing simultaneously in the system.
The process ID (PID) is extracted from a process table. In a shell environment, the process ID is stored in the variable $$.

Listing processes
To identify the running processes, execute the command ps, which will be covered later in this course. For example, ps -u team01 shows all running processes from user team01.

Login shell
When you log in to a system, AIX starts a new process (in the example with PID=202) and loads the program /usr/bin/ksh into this process. This shell is called the login shell.
The PID is randomly allocated by the kernel.

Process relationships
Processes exist in parent/child hierarchies. A process which starts or executes a program or a command is a parent process; a child process is the product of the parent process. A parent process may have several child processes, but a child process can only have one parent.
This process manifests itself when the user starts running commands after they are logged in to the system. The shell waits for instructions and having received them, executes them. The instructions usually involve starting up a process, like an editor. In this situation, the shell is the parent process and the editor becomes the child.
All child processes inherit an environment from their parent. This environment tells the child who invoked it, where to send output, and so forth.

Example
In the example, the user executes the command cat kfile. The shell uses the PATH variable to find the program cat. This program resides in directory /usr/bin. Afterwards, the shell starts a new process (PID=310) and loads the program /usr/bin/cat into this new process.

Parent versus child process
The PID is the process identification number used by the kernel to distinguish the different processes. PID 1 is always the init process which is the first AIX process that is started during the boot process.
The PPID is the parent process identification number, or in other words the PID of the process which started this one.
The special environment variable $$ is mostly used within shell scripts to distinguish between multiple instances of the same shell script (for instance when unique temporary file names need to be used).
There are some exceptions. The echo command is built into the shell, so it does not need to create a subshell in which to run echo.

Examples
In the example above, a second ksh was started as a way to illustrate the parent/child relationship with processes. As another example, a second different shell could be started (for example, the csh) to run specific shell scripts or programs.

Process environment
Variables are local to the shell or process from which they are set. Child processes will not automatically inherit the variables of the parent. The variable x is not known in the subshell that has been started.
To pass variables into a subshell the export command must be executed. That is shown in the next activity.

Activity with Hints
This activity introduces the export command.
__ 1. Log in to the system.
login: teamxx (at the login prompt)
Password: teamxx (default password same as user name)
__ 2. Write down the process ID of your current shell.
Process ID:
$ echo $$
__ 3. Define two shell variables vartest1 and vartest2 in the following way:
$ vartest1="moon"
$ vartest2="mars"
Execute the export command only for variable vartest2.
$ export vartest2
__ 4. Print the value of vartest1 and vartest2.
$ echo $vartest1
$ echo $vartest2
__ 5. Start a new shell:
$ ksh
__ 6. Write down the process ID of the subshell.
Process ID:
$ echo $$
__ 7. Check if the variables vartest1 and vartest2 are defined in your subshell.
$ echo $vartest1
$ echo $vartest2
__ 8. In your subshell change the value of variable vartest2:
$ vartest2="jupiter"
__ 9. Exit your subshell and print out the value of vartest2.
$ exit
$ echo $vartest2
Has the variable been changed in the parent shell?
No, the variable has not been changed.
__ 10. Please answer the following question to summarize this activity:
To pass variables into a subshell, which command must be executed?
You must use the export command.

A shell script is a collection of commands stored in a text file

Creating a shell script
A shell script is a simple text file that contains AIX commands.
When a shell script is executed, the shell reads the file one line at a time and processes the commands in sequence.
Any AIX command can be run from within a shell script. There are also a number of built-in shell facilities which allow more complicated functions to be performed. These will be illustrated later.
Any AIX editor can be used to create a shell script.

Additional information
More information on Korn shell features such as aliasing can be found in the AIX 6.1 online documentation using search arguments such as Korn shell, ksh, and programming.

Shell script example
A shell script is a collection of commands in a file. In the example a shell script hello is shown.
To execute this script, start the program ksh and pass the name of the shell script as argument:
$ ksh hello
This shell reads the commands from the script and executes all commands line by line.

Executing shell scripts
This visual shows another way of invoking a shell script. This method relies on the user first making the script an executable file with the chmod command. After this step, the script can be invoked by its name.
Note that the shell uses the PATH variable to find executable files. If you get an error message like the following,
$ hello
ksh: hello: not found
check your PATH variable. The directory in which the shell script is stored must be defined in the PATH variable.

Variables and shell scripts
Each shell script is executed in a subshell. Variables defined in a shell script cannot be passed back to the parent shell.
If you invoke a shell script with a . (dot), it runs in the current shell. Variables defined in this script (dir1, dir2) are therefore defined in the current shell.

Process exit codes
When a command executes, if it completes successfully, it returns to its parent shell the value of zero (0) which is stored in a variable $?. This value is referred to as the return code or the exit code. If, however, the command completes unsuccessfully, a positive number between the range of 1 to 255 is returned.
To obtain the return code use the following: $ echo $?
$ date
$ echo $?
0
This shows successful execution of the date command. The visual shows an example for an unsuccessful execution of a command.

Activity with Hints
This activity introduces the export command.
__ 1. Log in to the system.
login: teamxx (at the login prompt)
Password: teamxx (default password same as user name)
__ 2. Create a shell script count_files that prints the number of files in the current directory.
$ vi count_files
echo "Number of files:"
ls -l | wc -l
__ 3. Make the script executable.
$ chmod u+x count_files
__ 4. Invoke the script. If the shell cannot find your script, check the PATH variable, or provide a path to the script on the command line.
$ count_files
__ 5. Create another shell script called active that counts the number of active users.
$ vi active
echo "Active users:"
who
echo "Number of active users:"
who | wc -l
__ 6. Make the script executable and invoke it afterwards.
$ chmod u+x active
$ active

Unit Summary
Shell scripts can be invoked in three ways:
– $ ksh  scriptname (must have read permission)
– $ scriptname (must have read and execute permission)
– $ . scriptname (must have read permission)
Each program runs in an AIX process.
Every process has an environment in which it runs much of which is inherited from its initiating process, the parent process.

---------------------------------------------------------------------------------------------

Unit 11.  Controlling Processes

Displaying process status information
The ps command lists processes in the same manner as ls lists files. By default, it prints information only about processes started from your current terminal. Only the Process ID, Terminal, Elapsed Time and Command with options and arguments are displayed.
The -e option displays information about EVERY process running in the system.
The -f option in addition to the default information provided by ps, displays the User Name, PPID, start time for each process (that is, a FULL listing).
The -l option displays the user ID, PPID and priorities for each process in addition to the information provided by ps (that is, a LONG listing). It provides only the process name instead of the original command line.
In addition to these options, AIX has support for all of the System V options.

Starting processes
Processes can be invoked in different ways. If the command will finish in a short period of time, then we don't mind waiting for it to finish. On the other hand, if it is going to take minutes or hours to run, then we may wish to invoke it in such a way that we can continue to use the terminal.
Processes run in two states:
  - Foreground: where they take full control over the terminal while they are running
  - Background: where they run with no further interaction with the shell

Foreground processes
Processes that are started from and require interaction with the terminal are called foreground processes. Most important, the parent shell can not give you a new prompt until the foreground process completes.

Background processes
Processes that are run independently of the initiating terminal are referred to as background processes. A background process is launched as a sub-process, but the foreground (parent) shell immediately gets control back and issues a new prompt. This allows the user to continue to interact with the shell while the sub-process is executing.
Background processes are most useful with commands that take a long time to run.
A process can only be run in the background if:
i. It does not require keyboard input.
ii. It is invoked with an ampersand (&) as the last character in the command line

Stopping a foreground process
Foreground processes interact with the terminal. These can be stopped by a quit signal by pressing <Ctrl-c>. Sometimes, the <Ctrl-c> may not work. A shell script or program can trap the signal a <Ctrl-c> generates and ignore its meaning. In this case, you must use the kill command to terminate the process.

Stopping a background process
Background processes are not interacting with the terminal and must be stopped by using the kill command to terminate the process.

The kill command sends a signal to a running process, which normally stops the process.

$ ps -f
UID    PID  PPID  ... TTY   ...    COMMAND
john   202     1  ...   tty0  ...    -ksh
john 204 202  ...   tty0 ...    db2_start
john 206 202  ...   tty0  ...    find /
$ kill 204 (Termination Signal)
$ kill -9 206  (Kill Signal)

Termination:   Notification to the program to terminate
Kill: Kill the application without notification (Use with care!)

The kill command is used to communicate a change of state to a command. The name of the kill command is misleading because many signals do not stop processes. The command can be used to tell the command or process to stop running but can also be used to convey other state changes to processes.
kill uses signals to communicate with the process. If no signal is specified, then the kill command issues a default signal, 15, to tell the process to terminate itself.
The example on the visual shows a find command running in the background. To end this process (as it may take a very long time to run), the command kill is used.

Who can stop processes?
A root user can stop any process with the kill command. If you are not a root user, you must have initiated the process in order for you to kill it.

Freeing up a hung terminal
If your terminal hangs, to clear the problem, try the interrupt key, <Ctrl-c>, or try using <Ctrl-q> (in case the terminal output is suspended), or try using <Ctrl-d> (in case it is just a foreground program waiting for more STDIN input).
If these actions still do not free the terminal, you can usually free up the terminal by logging in at a different terminal and using the kill command to kill the login shell of the hung terminal.

kill -9
A kill signal (-9) kills an application “with extreme prejudice.” This means that rather than the process terminating itself, the operating system terminates the process. When a process is killed in this manner, it does not have an opportunity to close any open files, or save any data, and can lead to corruption. For example, if you kill a database server process, you might end up with a corrupt database. Always try to stop processes by sending a normal termination signal (no flag, or -15), and use the (-9) signal as a last resort.

Signals
Signal Meaning
1 hangup - you logged out while the process was still running
2 interrupt - you pressed the interrupt (break) key sequence <Ctrl+c>
3 quit - you pressed the quit key sequence <Ctrl+\>
9 Kill signal: The most powerful (and risky) signal that can be sent: Signal cannot be avoided or ignored!
15 Termination signal (Default): Stop a process Signal can be handled by programs

Signals are used to communicate a change of state to a command. This may mean that the command or process should stop running or it may even mean that this process should re-read its parameter files.

Signals
Signals are used to tell the kill command what to do with the PID specified in the command. By default, the kill command sends a signal of 15 to a process.
To send a different signal to a process use kill -num PID where num is the signal that you want to send.
The HANGUP signal (1) is sent to a process if its parent dies, for example if you log off when a background process is running.
The INTerrupt signal (2) is generated when the user presses the interrupt key (Ctrl-c) on the keyboard.
The QUIT signal (3) is generated by the user pressing the quit key <Ctrl-\>.
The most powerful signal you can send to a process is the KILL signal (9), which is sent to all processes when the system is shutting down. Processes which refuse to be killed by other signals will usually be killed by kill -9 PID.

Listing signals
To list all the signals supported use the kill -l command. From this list you can also specify the kill command with the name of the signal rather than the number. For example, signal 3 refers to the Quit signal, so you could enter $ kill -QUIT rather than $ kill -3.
Note that the number of the signal bears no resemblance to its strength or priority.

Running Long Processes
nohup ls -R / > out 2> err.file &
The nohup, or “no hangup” command, will take over control of a background process once the process has been invoked. It tells the process to ignore signals 1 and 3 (hangup and quit). This will allow the process to continue if you log off the system.
nohup is designed to be used for background processes as it has little meaning when used with a foreground process.

Command output
A process started by nohup cannot send its output to your terminal. If you do not redirect its output, nohup will redirect the output of the command to a file called nohup.out.
located in the current working directory.
If more than one background process is started with nohup with the same current directory and the output has not been redirected, the nohup.out file will contain the output from all those processes (either mixed or appended). For this reason, it is a good idea to redirect output when using nohup.
The output from a command may be redirected to a log file or even to the null device (/dev/null) if no output is required.

STDERR
If the standard error is a terminal, all output written by the named command to its standard error is redirected to the same file descriptor as the standard output.

Who owns the process after you log out?
Since all processes need to have a parent process associated with it, commands started with nohup will be connected to the init process as the parent when you log off the system.

Job Control in the Korn Shell
jobs:Lists all jobs running in the background and stopped processes
<Ctrl-z>:Suspends foreground task
fg %<jobnumber>:Executes job in foreground
bg %jobnumber:Executes job in background

Finding background processes
When running multiple processes, the trick is to identify which processes are running in the background. By using the ps command, it is not normally possible to identify these background processes. There is a tool specifically designed for locating these processes called jobs. This example shows that two processes are running in the background.
$ jobs
[2] +Running ls -R / > outfile &
[1] - Running ls -R / > outfile1 &

Stopping background processes
The number between the brackets is used when controlling the background process by referring to it by %jobno, for example, kill %1 would stop the process labeled as job number one.

Moving a foreground process to the background
You can suspend a foreground process by pressing <Ctrl-z>. The running process is paused, and the parent shell is re-activated. The kernel is maintaining the environment of the process and able to resume the execution at the point where it was suspended.
To resume a suspended processes in the background, use the bg command. To bring a suspended or background process into the foreground, use the fg command.
The bg, fg, and kill commands can be used with a job number. For instance, to bring job number 3 from the background into the foreground, you can issue the command:
$ fg %3

nohup command
The jobs command does not list jobs that were started with the nohup command if the user has logged off and then logged back in to the system. On the other hand, if a user invokes a job with the nohup command and then issues the jobs command without logging off, the job will be listed.
If you started a job that is taking longer than you expected and need to log off, you can apply the nohup command to an existing process. For example, the user started a job in the background but forgot to add the nohup command:
$ start_app >/home/team01/app.out &
If the user logs off, the application will terminate. To allow it to continue to execute, add the nohup command to that process by finding its PID and then issuing the nohup command:
$ jobs
$ ps
   PID    TTY  TIME CMD
  5314  pts/0  0:00 -ksh
 11522  pts/0  0:00 ps
 19208  pts/0  0:01 start_app
$ nohup -p 19208
The user can now log off and the job will continue to execute until completion.

Job Control Example
Start job:
$ ls -R / > out 2> errfile &
[1] 273
Lists jobs:
$ jobs
[1]  + Running         ls -R / > out 2> errfile &
$
Foreground:
$ fg %1
ls -R / > out 2> errfile
Suspend:
<ctrl-z>
[1] + Stopped (SIGTSTP) ls -R / > out 2> errfile &
$
Background:
$ bg %1
$ jobs
[1] + Running        ls -R / > out 2> errfile &
$
Terminate:
$ kill %1
[1] + Terminate       ls -R / > out 2> errfile &
$

This visual shows how you can work with job control commands in a Korn shell.

Daemons
A daemon is a never-ending process, that controls a system resource such as the printer queue.
A daemon (pronounced “day-mon”) is a process that usually starts when you start your system and runs until you shut it down. Daemons are processes that wait for an event to take place. Once an event is detected, then the daemon will take responsibility for the task and process it.

Daemon example
qdaemon is one example of a daemon. qdaemon tracks print job requests and the printers available to handle them. The qdaemon maintains queues of outstanding requests and sends them to the proper device at the proper time.
The common daemons are cron, qdaemon, and errdemon. There are others daemons as well, many of them providing network services.

Unit Summary
To monitor processes use the ps command.
Background processes are invoked by including an ampersand & at the end of the command.
Use the kill command to terminate processes.
Some useful signals that terminate processes are kill -2,kill -3, and kill -9.
Jobs can be controlled in the Korn shell by suspending a job with <ctrl z> and restarted using the bg or fg commands.
The nohup command allows you to start a job in the background and complete processing after you log off.
System processes are called daemons and are often used to control system resources like the printer queueing mechanism.

-------------------------------------------------------------------------------------------------------------------

Unit 12.  Customizing the User Environment

Login Files
When you first log in to an AIX system, you have an opportunity to configure various settings that will control the way your shell session will work. Your environment is configured through several files that are read during the login process.

/etc/environment
The first file that the operating system uses at login is the /etc/environment file. This file contains variables specifying the basic environment for all processes and can only be changed by the system administrator.

/etc/profile
The second file that the operating system uses at login time is the /etc/profile file. This script controls system-wide default variables such as the mail messages and terminal types. It can only be changed by the administrator.

.profile
The .profile file is the third file read at login time. It resides in a user's login directory and enables a user to customize their individual working environment. The .profile file overrides commands run and variables set and exported by the /etc/profile file.
The contents of the .profile file can be any commands or settings that you would otherwise have to enter manually each time you log in to the system.
When setting variables in your .profile file, ensure that newly created variables do not conflict with standard variables such as MAIL, PS1, PS2, and so forth.

Establishing a standard environment
The /etc/environment file contains default variables set for each process. Only the system administrator can change this file.

Sample /etc/environment:
$ cat /etc/environment
# WARNING:   This file is only for establishing environment
# variables.  Execution of commands from this file or any
# lines other than specified above may cause failure of the
# initialization process.
PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb:/usr/bin/X11:/sbin:
/usr/java131/jre/bin:/usr/java131/bin     
TZ=EST5EDT
LANG=en_US
LOCPATH=/usr/lib/nls/loc
NLSPATH=/usr/lib/nls/msg/%L/%N:/usr/lib/nls/msg/%L/%N.cat

/etc/environment variables
PATH is the sequence of directories that is searched when looking for a command whose path name is incomplete.
TZ is the time zone information.
LANG is the locale name currently in effect.
LOCPATH is the full path name of the location of National Language Support information, part of this being the National Language Support Table.
NLSPATH is the full path name for messages.

Sample /etc/profile:
$ cat /etc/profile
.
# System-wide profile.  All variables set here may be overridden by
# a user's personal .profile file in their $HOME directory. However
# all commands here will be executed at login regardless.
trap "" 1 2 3
readonly LOGNAME
# Automatic logout (after 120 seconds inactive)
TMOUT=120
# The MAILMSG will be printed by the shell every MAILCHECK seconds
# (default 600) if there is mail in the MAIL system mailbox.
MAIL=/usr/spool/mail/$LOGNAME
MAILMSG="[YOU HAVE NEW MAIL]"
# If termdef command returns terminal type (i.e. a non NULL value),
# set TERM to the returned value, else set TERM to default lft.
TERM_DEFAULT=lft
TERM=`termdef`
TERM=${TERM:-$TERM_DEFAULT}
.
export LOGNAME MAIL MAILMSG TERM TMOUT
trap 1 2 3

/etc/profile
The /etc/profile file contains the set of environment variables and commands that will be invoked when a user logs in to the system. These are settings that all users will have applied to their shell as they log in.
Any settings here can be overridden by a user's .profile.

Environment Variables (1 of 2)
LOGNAME
This holds your login name. It is read by many commands. Value cannot be changed (readonly variable).
TMOUT
Holds the value for how long a terminal can be inactive before the terminal is logged off by the system.
MAIL
Holds the name of the file where your mail is sent.
TERM
The terminal type you are using. Used by screen-oriented applications like vi or smit.

Typical /etc/profile file variables
These are some of the variables that can be found in the /etc/profile file:
  - MAIL is the name of the file used by the mail system to detect the arrival of new mail.
  - You can force a terminal to log off after a period of inactivity by setting the TMOUT variable in the /etc/profile file.
  - The MAILCHECK variable specifies how often (in seconds) the shell will check for changes in the modification time of any of the files specified by the MAILPATH or MAIL parameters. The default value is 600 seconds.
  - MAILMSG is the variable which holds the message you receive to tell you new mail has arrived.
  - LOGNAME is the variable that the user logs in with.
  - TERM is the variable that stores the terminal type.

Sample .profile:
$ cat .profile
PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb:$HOME/bin:/usr/bin/X11:/sbin:.
PS1=' $PWD => '
ENV="$HOME/.kshrc"   ###Execute this file every time a new Korn shell is started.
export PATH PS1 ENV
if [ -s  "$MAIL" ]
then
echo "$MAILMSG"
fi

Controlling your shell with .profile
The .profile is a user-specific profile. It contains settings for individual users of AIX. The settings in this file will be acted on as the user logs in. These settings override any prior settings made in the /etc/profile. The .profile file is read only when the user logs in.
At startup time, the shell checks to see if there is any new mail in /usr/spool/mail/$LOGNAME. If there is then MAILMSG is echoed back. In normal operation, the shell checks periodically.
The ENV="$HOME/.kshrc" variable will cause the file $HOME/.kshrc to be run every time a new Korn shell is explicitly started. This file will usually contain Korn shell commands.

Environment Variables (2 of 2)
PATH
A list of colon-separated directories that the shell searches for commands:
PATH=/usr/bin:/etc:/usr/sbin:/usr/ucb:$HOME/bin:/us
r/bin/X11:/sbin:.
PS1
Primary system prompt (default= $). To show the hostname and the current
directory in the prompt:
PS1="$(hostname), "'$PWD: '
ENV
Pointer to a file containing Korn shell settings:
ENV="$HOME/.kshrc"

More environment variables
The PATH variable defines the search path for the directory containing commands and executable programs such as ls. Alternative directory names are separated with a : (colon). The current directory can be specified by two or more adjacent colons, or by a :. (colon period) as shown in the example above.
The current directory can also be specified by placing a . within two colons in the PATH variable:
/usr/bin:/etc:.:/home/nick
PS1 is the shell prompt and is normally set to $ for a user and # for root. It can be set to any string of text or to a variable.
PWD is a variable containing the current working directory.
MAIL is a pointer to the location of the user's mail directory.
MAILMSG is a string of text, normally set to You have new mail, that is displayed if the user has new mail in their mailbox.
ENV is a pointer to a file containing Korn shell settings. These cannot be exported like variables, so a variable is set up to reference a file containing these settings. In this way, each time a subshell is started, it will contain those settings automatically. This is covered in more detail in the next visual.

Sample .kshrc
$ cat .kshrc
# set up the command recall facility
set -o vi
# set up a few aliases
alias ll='ls -l'
alias p='ps -f'
alias up='cd ..'

Example of the .kshrc file
The ENV variable specifies a Korn shell script to be invoked every time a new shell is created. The shell script in this example is .kshrc (which is the standard name used), but any other filename can also be used.
The difference between .profile and .kshrc is that .kshrc is read each time a subshell is spawned, whereas .profile is read once at login.
You can also set the following variable in $HOME/.profile:
EDITOR=/usr/bin/vi
export EDITOR
It will do the same thing that the set -o vi command does as shown in the example.

ksh Features - Aliases
$ alias p='ps -ef'
$ alias ll='ls -l'
$ alias
history='fc -l'
ll='ls -l'
p= 'ps -ef'
r= 'fc -e -'

Aliases are settings that contain complex commands that are commonly used. The alias name will normally be a mnemonic or a shorthand for the command that it symbolizes.
The command or commands, are then assigned to the alias. From this point on, the alias contains the commands.

Assigning aliases
As shown in the visual, an alias can be set by simply typing the alias command followed by the mnemonic and a command or set of commands that are to be assigned to that muonic. The command or set of commands are in single quotes.

Predefined aliases
The alias command invoked with no arguments prints the list of aliases in the form name=value on standard output.
The Korn shell sets up a number of aliases by default. Notice that the history and r commands are in fact aliases of the fc command. Once this alias is established, typing an r will re-execute the previously entered command.

Passing aliases to subshells
Aliases can not be exported to subshells in the same manner as shell variables. To allow aliases to be set in subshells, the ENV variable has to be modified. The ENV variable is normally set to $HOME/.kshrc in the .profile file (although you can set ENV to any shell script). By adding the alias definition to the .kshrc file (by using one of the editors) and invoking the .profile file, the value of the alias will be carried down to all subshells, because the .kshrc file is run every time a Korn shell is explicitly invoked.
The file pointed to by the ENV variable should contain Korn shell commands.

ksh Features - Using Aliases
$ ll
-rw-r--r-- 1 joe staff 524 Sep 19
11:31 fleas
-rw-r--r-- 1 joe staff 1455 Jan 23
17:18 walrus
$ unalias ll
$ ll
ksh: ll: not found

Using aliases
To use an alias, simply invoke the alias name as if it where a command.
It is possible to invoke an alias with parameters, as long as these are significant to the LAST command in the alias. For example:
alias dir='ls'
dir -l
The -l will be added to the original command ls in the alias dir.

Removing aliases
To remove an alias, use the unalias command. This causes the current shell to “forget” about the alias. The names of the aliases specified with the unalias command will be removed from the alias list.

Shell command history
The text of the previous commands entered from a terminal device is stored in a history file, which by default is called .sh_history and is stored in the user's $HOME directory.
The fc -l command reads this file and allows you to list the last 16 commands entered. Instead of fc -l you can use the command history.
The r command allows you to recall previously entered commands. You can specify the command number (as given by the history command) or a text pattern to match against the command name.
The fc command allows the last 128 commands in the .sh_history file to be examined/modified. The portion of the file to be edited or listed can be selected by number or by giving the first character or characters of the command. If you do not specify an editor program as an argument to the fc command the value of the FCEDIT variable is used. If the FCEDIT variable is not defined, then the /usr/bin/ed file is used.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值