对话 UNIX: !$#@*%( 四 )


# cat << EOF
> Line 1
> Line 2
> Line 3
> Line 4
> Line 5
> EOF
Line 1
Line 2
Line 3
Line 4
Line 5
还可以使用制表符让 shell 脚本中的内容更整洁一点,这只需要在 << 和终止标识符之间放上一个连字符(-):
# cat <<- ATC
>Line 1
>Line 2
>Line 3
>Line 4
>Line 5
> ATC
Line 1
Line 2
Line 3
Line 4
Line 5
清单 7 给出的示例演示如何结合使用本文到目前为止讨论的东西 。
清单 7. 组合 CLI
# cat redirect_example
#!/usr/bin/ksh
cat <<- ATC | sed "s/^/Redirect Example => /g" >> atc.out
This is an example of how to redirect
stdout to a file as well as pipe stdout into stdin
of another command (i.e. sed), all done inside
a here-document.
Cool eh?
ATC
现在,看看关于重定向和管道的脚本 。
# ./redirect_example
# cat atc.out
Redirect Example => This is an example of how to redirect
Redirect Example => stdout to a file as well as pipe stdout into stdin
Redirect Example => of another command (i.e. sed), all done inside
Redirect Example => a here-document.
Redirect Example =>
Redirect Example => Cool eh?
子 shell
有时候,需要一起执行几个命令 。例如,如果希望在另一个目录中执行某一操作,可以使用 清单 8 中的代码 。
清单 8. 同时执行几个命令
# pwd
/home/cormany
# cd testdir
# tar –cf ls_output.tar ls.out?
# pwd
/home/cormany/testdir
这是有效的,但是要注意,在执行这些步骤之后,您就不再位于原来的目录中了 。通过把这些命令放在它们自己的子 shell 中,它们会作为子 shell 的实例执行 。清单 9 演示如何使用子 shell 执行相同的代码 。
清单 9. 使用子 shell 同时执行几个命令
# pwd
/home/cormany
# (cd testdir ; tar -cf ls_output.tar ls.out?)
# pwd
/home/cormany
test 命令、[ ] 和 [[ ]]
在编写 shell 脚本或用任何现代语言编写程序时,运算表达式或值的能力都很重要 。Unix 一直通过 test 命令提供这一功能 。正如 test 的手册页指出的,test 命令运算表达式参数的值,如果表达式的值是 True,就返回零(True)退出值 。关于 test 的定义和所有可用条件的更多信息,请参见 test 手册页 。
要想使用 test 命令,只需给这个命令提供适当的标志和文件名 。当 test 运算完表达式时,返回到命令提示,可以在这里检查返回码,见 清单 10 。
清单 10. 检查返回码
# ls –l
-rwxr-xr-x1 cormany atc 786 Feb 22 16:11 check_file
-rw-r--r--1 cormany atc0 Aug 04 20:57 emptyfile
# test -f emptyfile
# echo $?
0
# test -f badfilename
# echo $?
1
根据定义,如果表达式值是 True,那么 test 返回零退出值,否则返回非零退出值(即 1) 。在 清单 10 中,找到了文件 emptyfile,所以 test 返回 0;但是没有找到文件 badfilename,所以返回 1 。
使用 test 的另一种方法是把要运算的表达式放在单层方括号([ ])中 。使用 test 命令或把它替换为 [ ] 会返回相同的值:
# [ -f emptyfile ]
# echo $?
0
# [ -f badfilename ]
# echo $?
1
使用单层方括号([ ])还是双层方括号([[ ]])是个人习惯问题,实际上取决于您如何学习命令和 shell 脚本编程 。但是请记住,这两者之间有一些差异 。尽管 [ ] 和 [[ ]] 在运算期间使用相同的测试操作符,但是它们使用不同的逻辑操作符 。
操作符
在 ksh(AIX 中使用的默认 shell)中,以及 Unix 和 Linux 使用的其他 shell 中,一定要知道如何使用测试、逻辑和替换操作符 。

推荐阅读