Bash Command-line Editing
Early shell environments did not provide any form of line editing capabilities. This meant that if you spotted an error at the beginning of a long command line you were typing, you had to delete all the following characters, correct the error and then re-enter the remainder of the command. Fortunately Bash provides a wide range of command line editing options as outlined in the following table:
Key Sequence | Action |
---|---|
Ctrl-b or Left Arrow | Move cursor back one position |
Ctrl-f or Right Arrow | Move cursor forward on position |
Ctrl-p or Up Arrow | Scroll back through previously entered command |
Ctrl-n or down Arrow | Forth through previously entered command |
!1030(command's history number) | Execute the history command |
Delete | Delete character currently beneath the cursor |
Backspace | Delete character to the left of the cursor |
Ctrl-_ | Undo previous change (can be repeated to undo all previous changes) |
Ctrl-a | Move cursor to the start of the line |
Ctrl-e | Move cursor to the end of the line |
Meta-f or Esc then f | Move cursor forward one word |
Meta-b or Esc then b | Move cursor back on word |
Ctrl-l | Clear the screen of everything except current command |
Ctrl-k | Delete to end of line from current cursor position |
Meta-d or Esc then d | Delete to end of current word |
Meta-DEL or Esc then DEL | Delete beginning to current word |
Ctrl-w | Delete from current cursor position to previous white space |
Filename Shorthand
# To display the content of a text file named list.txt
cat list.txt
# The content of multiple text files could be displayed by specifying all the file names as arguments:
cat list.txt list2.txt list3.txt list4.txt
# Pattern matching can be used to specify all file with names matching certain criteria. For example, the "*" wildcard character to can be used to simplify the above example:
cat *.txt
# This could be further restricted to any file names beginning with list and ending in .txt:
cat list*.txt
# Single character matches may be specified using the '?' character:
cat list?.txt
File Name and Path Completion
In order to use filename completion, simply enter the first few characters of the file or path name and the press the ESC key twice. The Shell will then complete the filename for you with the first file or path name in the directory that matches the characters you entered.
To obtain a list of possible matches, press "ESC + =" after entering the first few characters.
Input and Output Redirection
Many shell commands output information when executed. By default this output goes to a device file called stdout which is essentially the terminal window or console in which the shell is running. Conversely, the shell takes input from a device file named stdin, which by default is the keyboard.
Output from a command can be redirected from stdout to a physical file on the file system using the '>' character. For example, to redirect output from an 'ls' command to a file named files.txt, the following command would be required:
ls *.txt > files.txt
To redirect the contents of a file as input to a command:
wc -l < files.txt
The above command will display the number of lines contained in files.txt file.
It is important to note that > redirection operator creates a new file, or truncates an existing file when used. In order to append to an existing file, use the >> operator:
ls *.dat >> files.txt
Whilst output from a command is directed to stdout, any error messages generated by the command are directed to stderr. This means that if stdout is directed to a file, error messages will still appear in the terminal. This is generally the desired behavior, though stderr may also redirected if desired using the 2> operator:
ls ddfrdfdfxcsfg 2> errormsg
On completion of the command, an error reporting the fact that the file named ddfrdfdfxcsfg could not be found will be contained in the errormsg file.
Both stderr and stdout may be redirected to the same file using the &> operator:
ls /etc ddfrdfdfxcsfg &> alloutput
On completion of execution, the alloutput file will contain both a listing of the contents of the /etc directory, and the error message associated with the attempt to list a non-existment file.
Working with Pipes in the Bash Shell
In addition to I/O redirection, the shell allows output from one command to be piped directly as input to another command. A pipe operation is achieved by placing the '|' character between two or more commands on a command line. Foe example, to count the number of process running on a system the output from the ps command can be piped through to the wc command:
ps -ef | wc -l
There is no limit to the number of pipe operations that can be performed on a command line. For example, to find the number of lines in a file which contain the name Smith:
cat namesfile | grep Smith | wc -l
Configuring Aliases
As you gain proficiency with the shell environment, it is likely that you will find yourself frequently issuing commands with the same arguments. For example, you may often use the ls command with l and t option:
ls -lt
To reduce the amount of typing involved in issuing a command, it is possible to create an alias that maps to the command and the arguments. For example, to create an alias such taht entering the letter l will cause the ls -lt command to be execute, the following statement would be used:
alias l ='ls -lt'
Environment Variables
Shell environment variables provide temporary storage of data and configuration setting. The shell itself sets up a number of environment variables that may be changed by the user to modify the behavior of the shell. A list of currently defined variables may be obtained using the 'env' command:
$ env
Perhaps the most useful environment variable is PATH. This defines the directories in which the shell will search for commands entered at the command prompt, and the order in which it will do so.
Another useful variable is HOME which specifies the home directory of the current user. If, for example, you wanted the shell to also look for commands in the scripts directory located in your home directory, you would modify the PATH variable as follows:
export PATH=$PATH:$HOME/scripts
Display en existing environment variable using the echo command:
echo $PATH
Create your own enviroment variables using the export command. For example:
export DATAPATH=/data/file
A useful trick to assign the output from a command to an enviroment variable involves the use of back quotes(`) around the command. For example, to assign the current date and time to an environment variable called NOW:
export NOW=date
echo $NOW
If there are environment variable or alias setting that you need to be configured each time you enter the shell environment, they may be added to a file in your home directory name .bashrc. For example, the following example .bashrc file is configured to set up the DATAPATH environment variable and an alias:
# .bashrc
# Source global definitions
if [-f /etc/bashrc]; then
. /etc/bashrc
fi
# User specific aliases and functions
export DATAPATH=/data/files
alias l='ls -lt'
Writing Shell Scripts
So far we have focused exclusively on the interactive nature of the Bash shell. By interactive we mean manually entering commands at the prompt one by one and executing them. In fact, this is only a smell part of what the shell is capable of. Arguably one of the most powerful aspects of the shell involves the ability to create shell scripts. Shell scripts are essentially text files containing sequences of statements that can be executed within the shell environment to perform tasks. In addition to the ability to execute commands, the shell provides many of the programming constructs such as for and do loops and if statements that you might reasonable expect to find in scripting language.
Unfortunately a detailed overview of shell scripting is beyond the scope of this chapter. There are, however, many books and web resources dedicated shell scripting that do the subject much more justice than we could ever hope to achieve here. In this section, therefore, we will only be providing a very small taste of shell scripting.
The first step in creating a shell script is to create a file (for the purpose of this example we name it simple.sh) and add the following as the first line:
#!/bin/sh
The #! is called the shebang and is a special sequence of characters indicating that the path to the interpreter needed to execute the script is the next item on the line (in this case the sh executable located in /bin). This could equally be, for example, /bin/csh or /bin/ksh if either were the interpreter you wanted to use.
The next step is to write a simple script:
#!/bin/sh
for i in *
do
echo $i
done
All this script does is iterate through all the files in the current directory and display the name of each file. This may be executed by passing the name of the script through as an argument to sh:
sh simple.sh
In order to make file executable (thereby negating the need to pass through to the sh command) the chomd command can be used:
chmod +x simple.sh
Once the execute bit has been set on the file's permissions, it may be executed directly. For example:
./simple.sh
邓福如:你好吗 天气好吗
网友评论