LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 674|回复: 4

我来贴 : 的用法

[复制链接]
发表于 2004-4-13 22:11:58 | 显示全部楼层 |阅读模式
22.2.3 :
In the beginning, the magic number for Bourne shell scripts used to be a colon followed by a newline. Most Unices still support this, and will correctly pass a file with a single colon as its first line to `/bin/sh' for interpretation. Nobody uses this any more and I suspect some very new Unices may have forgotten about it entirely, so you should stick to the more usual `#! /bin/sh' syntax for your own scripts. You may occasionally come across a very old script that starts with a `:' though, and it is nice to know why!

In addition, all known Bourne compatible shells have a builtin command, `:' which always returns success. It is equivalent to the system command /bin/true, but can be used from a script without the overhead of starting another process. When setting a shell variable as a flag, it is good practice to use the commands, : and false as values, and choose the sense of the variable to be `:' in the common case: When you come to test the value of the variable, you will avoid the overhead of additional processes most of the time.

  

var=:
if $var; then
  foo
fi




The : command described above can take any number of arguments, which it will fastidiously ignore. This allows the `:' character to double up as a comment leader of sorts. Be aware that the characters that follow are not discarded, they are still interpreted by the shell, so metacharacters can have unexpected effects:

  

$ cat foo
:
: echo foo
: `echo bar`
: `echo baz >&2'
$ ./foo
baz




You may find very old shell scripts that are commented using `:', or new scripts that exploit this behavior in some esoteric fashion. My advice is, don't: It will bite you later.
发表于 2004-4-13 22:35:11 | 显示全部楼层
null命令是一个冒号:,它是一个shell的内制的命令,什么都不做的总是返回一个为零的状态,就是当你觉得没什么要说要做的时候,那么就用冒号吧~,常用于while结构

  1. while [color=red]:[/color];do #这里的: ,相当于true
  2.     ...;
  3. done
复制代码

例如:

  1. if grep root /etc/passwd;then
  2.     [color=red]:[/color]  #这里的: 以零状态退出,也可以用别的什么代替,如echo ....
  3. else
  4.     echo "root is not exists!"
  5. fi
复制代码
发表于 2004-4-14 10:13:29 | 显示全部楼层
如果:后面有带参数,则不一样了。试试看
发表于 2004-4-15 03:17:06 | 显示全部楼层
最初由 seablue 发表
如果:后面有带参数,则不一样了。试试看
man bash :
: [arguments]
              No  effect;  the command does nothing beyond expanding arguments
              and performing any specified redirections.  A zero exit code  is
              returned.
man ksh:
: [ ... ]
              The null command.  Exit status is set to zero.
home/javalee/myshell#
/home/javalee/myshell#echo $SHELL
/bin/ksh
/home/javalee/myshell#: ls date
/home/javalee/myshell#echo $?
0
/home/javalee/myshell#bash
/home/javalee/myshell#: ls date
/home/javalee/myshell#echo $?
0

还是什么多没作呀?:ask :ask
发表于 2004-4-15 18:31:06 | 显示全部楼层
:sorry是我搞错了

[linuxer@myes001 test]$ : echo ok;echo $#
0
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表