⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 333.html

📁 著名的linux英雄站点的文档打包
💻 HTML
📖 第 1 页 / 共 3 页
字号:
                            <TD background="images/bgi.gif" tppabs="http://www.linuxhero.com/docs/images/bgi.gif" 
                          height=30></TD></TR></TBODY></TABLE>
                        <TABLE cellSpacing=0 cellPadding=3 width="95%" 
                        align=center border=0>
                          <TBODY>
                          <TR>
                            <TD>
                              <TABLE cellSpacing=0 cellPadding=3 width="100%" 
                              border=0>
                                <TBODY>
                                <TR>
                                      <TD vAlign=top> 
<p><FONT class=normalfont><B><font color=blue>SHELL Warming up</font></B></FONT><BR><FONT class=smallfont color=#ff9900>2004-04-23 15:18 pm</FONT><BR><FONT class=normalfont>作者:作者<br>来自:Linux知识宝库<br>联系方式:无名<br><br>Comments<br>
Comments in shell programming start with # and go until the end of the line. We really recommend you to use comments. If you have comments and you don't use a certain script for some time you will still know immediately what it is doing and how it works.<br>
 <br>
Variables<br>
As in other programming languages you can't live without variables. In shell programming all variables have the datatype string and you do not need to declare them. To assign a value to a variable you write:<br>
varname=value<br>
<br>
To get the value back you just put a dollar sign in front of the variable:<br>
#!/bin/sh<br>
# assign a value:<br>
a="hello world"<br>
# now print the content of "a":<br>
echo "A is:"<br>
echo $a<br>
<br>
Type this lines into your text editor and save it e.g. as first. Then make the script executable by typing chmod +x first in the shell and then start it by typing ./first<br>
The script will just print:<br>
A is:<br>
hello world<br>
<br>
Sometimes it is possible to confuse variable names with the rest of the text:<br>
num=2<br>
echo "this is the $numnd"<br>
<br>
This will not print "this is the 2nd" but "this is the " because the shell searches for a variable called numnd which has no value. To tell the shell that we mean the variable num we have to use curly braces:<br>
num=2<br>
echo "this is the ${num}nd"<br>
<br>
This prints what you want: this is the 2nd<br>
<br>
There are a number of variables that are always automatically set. We will discuss them further down when we use them the first time.<br>
<br>
If you need to handle mathematical expressions then you need to use programs such as expr (see table below).<br>
Besides the normal shell variables that are only valid within the shell program there are also environment variables. A variable preceeded by the keyword export is an environment variable. We will not talk about them here any further since they are normally only used in login scripts.  <br>
Shell commands and control structures<br>
There are three categories of commands which can be used in shell scripts:<br>
<br>
1)Unix commands:<br>
Although a shell script can make use of any unix commands here are a number of commands which are more often used than others. These commands can generally be described as commands for file and text manipulation.<br>
Command syntax Purpose<br>
echo "some text" write some text on your screen<br>
ls list files<br>
wc -l file<br>
wc -w file<br>
wc -c file count lines in file or<br>
count words in file or<br>
count number of characters<br>
cp sourcefile destfile copy sourcefile to destfile<br>
mv oldname newname rename or move file<br>
rm file delete a file<br>
grep 'pattern' file search for strings in a file<br>
Example: grep 'searchstring' file.txt<br>
cut -b colnum file get data out of fixed width columns of text<br>
Example: get character positions 5 to 9<br>
cut -b5-9 file.txt<br>
Do not confuse this command with "cat" which is something totally different<br>
cat file.txt write file.txt to stdout (your screen)<br>
file somefile describe what type of file somefile is<br>
read var prompt the user for input and write it into a variable (var)<br>
sort file.txt sort lines in file.txt<br>
uniq remove duplicate lines, used in combination with sort since uniq removes only duplicated consecutive lines<br>
Example: sort file.txt | uniq<br>
<br>
expr do math in the shell<br>
Example: add 2 and 3<br>
expr 2 "+" 3<br>
find search for files<br>
Example: search by name:<br>
find . -name filename -print<br>
This command has many different possibilities and options. It is unfortunately too much to explain it all in this article.<br>
tee write data to stdout (your screen) and to a file<br>
Normally used like this:<br>
somecommand | tee outfile<br>
It writes the output of somecommand to the screen and to the file outfile<br>
basename file return just the file name of a given name and strip the directory path<br>
Example: basename /bin/tux<br>
returns just tux<br>
dirname file return just the directory name of a given name and strip the actual file name<br>
Example: dirname /bin/tux<br>
returns just /bin<br>
head file print some lines from the beginning of a file<br>
tail file print some lines from the end of a file<br>
sed sed is basically a find and replace program. It reads text from standard input (e.g from a pipe) and writes the result to stdout (normally the screen). The search pattern is a regular expression (see references). This search pattern should not be confused with shell wildcard syntax. To replace the string linuxfocus with linuxFocus in a text file use:<br>
cat text.file | sed 's/linuxfocus/linuxFocus/' &gt; newtext.file<br>
This replaces the first occurance of the string linuxfocus in each line with linuxFocus. If there are lines where linuxfocus appears several times and you want to replace all use:<br>
cat text.file | sed 's/linuxfocus/linuxFocus/g' &gt; newtext.file<br>
<br>
awk Most of the time awk is used to extract fields from a text line. The default field separator is space. To specify a different one use the option -F.<br>
cat file.txt | awk -F, '{print $1 "," $3 }'<br>
<br>
<br>
Here we use the comma (,) as field separator and print the first and third ($1 $3) columns. If file.txt has lines like:<br>
Adam Bor, 34, India<br>
Kerry Miller, 22, USA<br>
<br>
<br>
then this will produce:<br>
Adam Bor, India<br>
Kerry Miller, USA<br>
<br>
<br>
There is much more you can do with awk but this is a very common use.  <br>
<br>
<br>
2) Concepts: Pipes, redirection and backtick<br>
They are not really commands but they are very important concepts.<br>
<br>
pipes (|) send the output (stdout) of one program to the input (stdin) of another program.<br>
<br>
   grep "hello" file.txt | wc -l<br>
<br>
finds the lines with the string hello in file.txt and then counts the lines.<br>
The output of the grep command is used as input for the wc command. You can concatinate as many commands as you like in that way (within reasonable limits).<br>
<br>
redirection: writes the output of a command to a file or appends data to a file<br>
&gt; writes output to a file and overwrites the old file in case it exists<br>
&gt;&gt; appends data to a file (or creates a new one if it doesn't exist already but it never overwrites anything).<br>
<br>
Backtick<br>
The output of a command can be used as command line arguments (not stdin as above, command line arguments are any strings that you specify behind the command such as file names and options) for another command. You can as well use it to assign the output of a command to a variable.<br>
The command<br>
find . -mtime -1 -type f -print<br>
<br>
finds all files that have been modified within the last 24 hours (-mtime -2 would be 48 hours). If you want to pack all these files into a tar archive (file.tar) the syntax for tar would be:<br>
tar xvf file.tar infile1 infile2 ...<br>
<br>
Instead of typing it all in you can combine the two commands (find and tar) using backticks. Tar will then pack all the files that find has printed:<br>
#!/bin/sh<br>
# The ticks are backticks (`)  not normal quotes ('):<br>
tar -zcvf lastmod.tar.gz `find . -mtime -1 -type f -print`<br>
<br>
<br>
3) Control structures<br>
The "if" statement tests if the condition is true (exit status is 0, success). If it is the "then" part gets executed:<br>
if ....; then<br>
  ....<br>
elif ....; then<br>
  ....<br>
else<br>
  ....<br>
fi<br>
<br>
Most of the time a very special command called test is used inside if-statements. It can be used to compare strings or test if a file exists, is readable etc...<br>
The "test" command is written as square brackets " [ ] ". Note that space is significant here: Make sure that you always have space around the brackets. Examples:<br>
[ -f "somefile" ]  : Test if somefile is a file.<br>
[ -x "/bin/ls" ]   : Test if /bin/ls exists and is executable.<br>
[ -n "$var" ]      : Test if the variable $var contains something<br>
[ "$a" = "$b" ]    : Test if the variables "$a" and  "$b" are equal<br>
<br>
Run the command "man test" and you get a long list of all kinds of test operators for comparisons and files.<br>
Using this in a shell script is straight forward:<br>
#!/bin/sh<br>
if [ "$SHELL" = "/bin/bash" ]; then<br>
 echo "your login shell is the bash (bourne again shell)"<br>
else<br>
 echo "your login shell is not bash but $SHELL"<br>
fi<br>
<br>
The variable $SHELL contains the name of the login shell and this is what we are testing here by comparing it against the string "/bin/bash"<br>
<br>
Shortcut operators<br>
People familiar with C will welcome the following expression:<br>
<br>
[ -f "/etc/shadow" ] && echo "This computer uses shadow passwors"<br>
<br>
The && can be used as a short if-statement. The right side gets executed if the left is true. You can read this as AND. Thus the example is: "The file /etc/shadow exists AND the command echo is executed". The OR operator (||) is available as well. Here is an example:<br>
#!/bin/sh<br>
mailfolder=/var/spool/mail/james<br>
[ -r "$mailfolder" ] || { echo "Can not read $mailfolder" ; exit 1; }<br>
echo "$mailfolder has mail from:"<br>
grep "^From " $mailfolder<br>
<br>
The script tests first if it can read a given mailfolder. If yes then it prints the "From" lines in the folder. If it cannot read the file $mailfolder then the OR operator takes effect. In plain English you read this code as "Mailfolder readable or exit program". The problem here is that you must have exactly one command behind the OR but we need two:<br>
-print an error message<br>
-exit the program<br>
To handle them as one command we can group them together in an anonymous function using curly braces. Functions in general are explained further down.<br>
You can do everything without the ANDs and ORs using just if-statements but sometimes the shortcuts AND and OR are just more convenient.<br>
<br>
The case statement can be used to match (using shell wildcards such as * and ?) a given string against a number of possibilities.<br>
case ... in<br>
...) do something here;;<br>
esac<br>
<br>
Let's look at an example. The command file can test what kind of filetype a given file is:<br>
file lf.gz<br>
<br>
returns:<br>
<br>
lf.gz: gzip compressed data, deflated, original filename,<br>
last modified: Mon Aug 27 23:09:18 2001, os: Unix<br>
<br>
We use this now to write a script called smartzip that can uncompress bzip2, gzip and zip compressed files automatically :<br>
#!/bin/sh<br>
ftype=`file "$1"`<br>
case "$ftype" in<br>
"$1: Zip archive"*)<br>
   unzip "$1" ;;<br>
"$1: gzip compressed"*)<br>
   gunzip "$1" ;;<br>
"$1: bzip2 compressed"*)<br>
   bunzip2 "$1" ;;<br>
*) error "File $1 can not be uncompressed with smartzip";;<br>
esac<br>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -