| 
                         当我们调用这个脚本时,我们会看到如下内容: 
$ tryme one two three/home/shs/bin/tryme     <== 脚本名称one                     <== 第一个参数two                     <== 第二个参数3                       <== 参数的个数one two three           <== 所有的参数0                       <== 上一条 echo 命令的返回码10410                   <== 脚本的进程 ID10109                   <== 父进程 ID
  
如果我们在脚本运行完毕后检查 shell 的进程 ID,我们可以看到它与脚本中显示的 PPID 相匹配: 
$ echo $$10109                   <== shell 的进程 ID
  
当然,比起简单地显示它们的值,更有用的方式是使用它们。我们来看一看它们可能的用处。 
检查是否已提供参数: 
if [ $# == 0 ]; then    echo "$0 filename"    exit 1fi
  
检查特定进程是否正在运行: 
ps -ef | grep apache2 > /dev/nullif [ $? != 0 ]; then    echo Apache is not running    exitfi
  
在尝试访问文件之前验证文件是否存在: 
if [ $# -lt 2 ]; then    echo "Usage: $0 lines filename"    exit 1fi-  
 if [ ! -f $2 ]; then    echo "Error: File $2 not found"    exit 2else    head -$1 $2fi
  
在下面的小脚本中,我们检查是否提供了正确数量的参数、第一个参数是否为数字,以及第二个参数代表的文件是否存在。 
#!/bin/bash-  
 if [ $# -lt 2 ]; then    echo "Usage: $0 lines filename"    exit 1fi-  
 if [[ $1 != [0-9]* ]]; then    echo "Error: $1 is not numeric"    exit 2fi-  
 if [ ! -f $2 ]; then    echo "Error: File $2 not found"    exit 3else    echo top of file    head -$1 $2fi
  
重命名变量
在编写复杂的脚本时,为脚本的参数指定名称通常很有用,而不是继续将它们称为 $1、$2 等。等到第 35 行,阅读你脚本的人可能已经忘了 $2 表示什么。如果你将一个重要参数的值赋给 $filename 或 $numlines,那么他就不容易忘记。 
#!/bin/bash-  
 if [ $# -lt 2 ]; then    echo "Usage: $0 lines filename"    exit 1else    numlines=$1    filename=$2fi-  
 if [[ $numlines != [0-9]* ]]; then    echo "Error: $numlines is not numeric"    exit 2fi-  
 if [ ! -f $ filename]; then    echo "Error: File $filename not found"    exit 3else    echo top of file    head -$numlines $filenamefi
  
当然,这个示例脚本只是运行 head 命令来显示文件中的前 x 行,但它的目的是显示如何在脚本中使用内部参数来帮助确保脚本运行良好,或在失败时清晰地知道失败原因。                         (编辑:泰州站长网) 
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! 
                     |