---
title: "Linux shell脚本全面学习4"
author: "sdustyongz"
date: "2010-12-07T13:30:09Z"
tags: []
categories: ["操作系统"]
slug: "linux-shell-4"
draft: false
lastmod: "2010-12-07T13:30:09Z"
id: 835540
url: "https://uvbook.iteye.com/blog/835540"
---

5. 引号
　　在向程序传递任何参数之前，程序会扩展通配符和变量。这里所谓扩展的意思是程序会把通配符
　　（比如*）替换成合适的文件名，它变量替换成变量值。为了防 止程序作这种替换，您可以使用
　　引号：让我们来看一个例子，假设在当前目录下有一些文件，两个jpg文件， mail.jpg 和tux.jpg。
　　1.2 编译SHELL脚本
　　#ch#!/bin/sh mod +x filename
　　cho *.jpg ∪缓螅梢酝ü淙耄?./filename 来执行您的脚本。
　　这将打印出"mail.jpg tux.jpg"的结果。
　　引号 (单引号和双引号) 将防止这种通配符扩展：
　　#!/bin/sh
　　echo "*.jpg"
　　echo '*.jpg'
　　这将打印"*.jpg" 两次。
　　单引号更严格一些。它可以防止任何变量扩展。双引号可以防止通配符扩展但允许变量扩展。
　　#!/bin/sh
　　echo $SHELL
　　echo "$SHELL"
　　echo '$SHELL'
　　运行结果为：
　　/bin/bash
　　/bin/bash
　　$SHELL
　　最后，还有一种防止这种扩展的方法，那就是使用转义字符——反斜杆：
　　echo *.jpg
　　echo $SHELL
　　这将输出：
　　*.jpg
　　$SHELL
　　6. Here documents
　　当要将几行文字传递给一个命令时，here documents（译者注：目前还没有见到过对该词适合的翻译）
　　一种不错的方法。对每个脚本写一段帮助性的文字是很有用的，此时如果我们四有那个 here documents
　　就不必用echo函数一行行输出。 一个 "Here document" 以  shift by 2
　　--) shift;break;; # end of options
　　-*) echo "error: no such option $1. -h for help";exit 1;;
　　*) break;;
　　esac
　　done
　　echo "opt_f is $opt_f"
　　echo "opt_l is $opt_l"
　　echo "first arg is $1"
　　echo "2nd arg is $2"
　　您可以这样运行该脚本：
　　cmdparser -l hello -f -- -somefile1 somefile2
　　返回的结果是：
　　opt_f is 1
　　opt_l is hello
　　first arg is -somefile1
　　2nd arg is somefile2
　　这个脚本是如何工作的呢？脚本首先在所有输入命令行参数中进行循环，将输入参数
　　与case表达式进行比较，如果匹配则设置一个变量并且移除该参数。根据unix系统的惯例，
　　首先输入的应该是包含减号的参数.
　　第2部分 实例
　　现在我们来讨论编写一个脚本的一般步骤。任何优秀的脚本都应该具有帮助和输入参数。并且写一个伪脚本（framework.sh），该脚本包含了大多数脚本都需要的框架结构，是一个非常不错的主意。这时候，在写一个新的脚本时我们只需要执行一下copy命令：
　　cp framework.sh myscript
　　然后再插入自己的函数。