您的位置:首页 > 运维架构 > Shell

关于shell脚本的一些容易混淆的概念

2016-06-26 12:42 489 查看
$@和$*的区别

[lf@x201t~]$vim my_fun.sh
#!/bin/bash
# $@ and $*
my_fun (){
echo "$#"
}

echo 'the number of parameter in "$@" is' $(my_fun "$@")
echo 'the number of parameter in $@ is' $(my_fun $@)
echo 'the number of parameter in "$*" is' $(my_fun "$*")
echo 'the number of parameter in $* is' $(my_fun $*)
~

[lf@x201t ~]$ sh a.sh p1 "p2 p3" p4
the number of parameter in "$@" is 3
the number of parameter in $@ is 4
the number of parameter in "$*" is 1
the number of parameter in $* is 4
看出区别了吗?关键 $@ 靠谱一点

2. 关于 > 和 <
[lf@x201t ~]$ cat <file >file.bak
[lf@x201t ~]$ cat file;cat file.bak
this is a test
this is a test
[lf@x201t ~]$ cat <file >file
[lf@x201t ~]$ cat file
[lf@x201t ~]$ =====> 这行输出是空的,文件 file 已经没内容了
为什么在最后 cat 看不到 file 文件的内容了呢?
这是因为文件 file 这时真的是个空文件。 why???
因为 IO重定向中,标准输出是要先准备好,才会从标准输入读入到标准输出。是不是有点绕。
就像接力赛中,传递接力棒一样的道理;你没看到接棒的人,你肯定不会把接力棒送出去一样。
所以, cat <file >file 命令中, > 会先把文件 file 清空,之后 才会执行 > file;结果就是空空。

3. for 循环中 变量的取值方式
a. 从一组字符串中取值
for var in one two three four five
do

echo ****************************

echo '$var is ' $var

done

b. 从位置变量中取值
for var;do
do
echo '-----------------------------'
echo '$var is ' $var
done
c. 从累计变化的格式中取值

#!/bin/bash
for ((var=1;var<=10;var++))
do
echo ------------------------
echo '$var is ' $var
done

d. 从命令替换中取值
#!/bin/bash
for var in $(cat file.txt)
do
echo ------------------------
echo '$var is ' $var
done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  脚本 shell 小心得