Chinaunix首页 | 论坛 | 博客
  • 博客访问: 892331
  • 博文数量: 113
  • 博客积分: 3160
  • 博客等级: 少校
  • 技术积分: 1801
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-19 10:09
文章分类

全部博文(113)

分类: Python/Ruby

2012-06-08 21:26:19

 
1:$$:PID号
 
shell把执行shell的进程的PID号存储在特殊参数$$中。
 
 
实例:
 
#!/bin/sh
 
echo "The cunrrent PID is $(ps)"
 
echo "Ihe PID of a is  $$"
 
exit 0
 
 
测试结果:
 
./a
 
The cunrrent PID is   PID TTY          TIME CMD
 2567 pts/3    00:00:00 bash
 2842 pts/3    00:00:00 a
 2843 pts/3    00:00:00 ps
Ihe PID of a is  2842
 
 
2:$!:后台运行的PID号存储在$!中
 
 
实例:
 
#!/bin/sh
 
echo &
 
echo "$!"
echo "$(ps)"
 
exit 0
 
 
测试结果:
 
 
./a
 
 2908
 
  PID TTY          TIME CMD
 2567 pts/3    00:00:00 bash
 2907 pts/3    00:00:00 a
 2908 pts/3    00:00:00 a
 2909 pts/3    00:00:00 ps
 
ps
  PID TTY          TIME CMD
 2567 pts/3    00:00:00 bash
 2939 pts/3    00:00:00 ps
 
 
3:$?:退出状态
 
 
一个进程结束的时候,会向父进程返回一个状态,$?就存放这个返回状态码(类似与C语言函数结束的时候,返回值保存在寄存器eax中一样)。通常情况下返回状态码0表示执行成功,否则就是失败。
 
 
 
4:$#:命令行参数的个数
 
 
$#保存了命令行上除了命令自身的参数个数。
 
 
例如,C语言的main函数原型,
 
int main(int argc, char *argv[]);
 
其中的argc(argument counts)表示命令行参数个数,就是那个$#;
 
 
而argv(argument variables)表示命令参数,其中的*argv[0]表示程序名,跟$0一个意思;*argv[1]表示命令参数,类似与$1,$2....(很多东西都是相同的,要富于联想。。)
 
 
实例:
 
 
#!/bin/sh
 
echo "this program has $# argument variables !"
 
exit 0
 
 
测试结果:
 
 
./a
this program has 0 argument variables !
 
./a li chen wang han
this program has 4 argument variables !
 
 
5:$0,$1,$2....
 
 
其中$0存储程序名,剩下$1$2..存储命令行参数
 
 
实例:
 
 
#!/bin/sh
 
echo "this program is $0"
 
echo "the first argument variable is $1"
 
echo "the second is $2"
 
exit 0
 
 
测试结果:
 
./a li chen
this program is ./a
the first argument variable is li
the second is chen
 
 
 
6:$*,$@:所有的命令行参数
 
 
它们两者的不同在于,$*把位置参数看成是一个整体,当作一个参数处理;$@则把每个参数当作单独的参数看待。
 
 
实例:
 
#!/bin/sh
 
echo "this program is $0"
 
echo "All of the argv are $* "
 
exit 0
 
 
测试结果:
 
 
#!/bin/sh
 
echo "this program is $0"
 
echo "All of the argv are $* "
 
exit 0
 
 
 
7:$(()):对双括号内的变量做算术运算
 
 
实例:
 
#!/bin/sh
 
foo=1
 
while [ "$foo" -le "5" ] ; do
    echo "Foo is $foo now !"
    foo=$(($foo + 1))
done
 
exit 0
 
 
测试结果:
 
./a
Foo is 1 now !
Foo is 2 now !
Foo is 3 now !
Foo is 4 now !
Foo is 5 now !
 
 
 
8:${name}:变量name的值,等价于$name
 
 
实例:
 
#!/bin/sh
 
foo=1
 
echo "$foo"
echo "${foo}"
 
exit 0
 
 
测试结果:
 
 
./a
1
1
 
 
9:其它
 
 
${name:-default}:如果name为空或者未赋值,那么使用default;
 
${name:=default}:如果name为空或者未赋值,那么使用default,同时将name设置为default.
 
${name:?message}:如果name为空或者未赋值,那么显示出错信息mesage.
 
${#name} : name字符个数
 
${name#pattern}:去除最小匹配前缀
 
${name##pattern}:去除最大匹配前缀
 
${name%pattern}:去除最小匹配后缀
 
${name%%pattern}:去除最大匹配后缀
 
 
实例:
 
 
#!/bin/sh
 
var="li.chen.wang.he.bei"
echo "$var"
 
echo "${name:-$var}"
echo "${name}"
echo "${name:=$var}"
echo "${name}"
echo "${name:?$var}"
 
exit 0
 
 
测试实例:
 
 
./a
li.chen.wang.he.bei
li.chen.wang.he.bei
(空,说明name为空)
li.chen.wang.he.bei
li.chen.wang.he.bei(说明name已经被设置)
li.chen.wang.he.bei
 
 
阅读(1890) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~