在当前shell中而不是子Shell中执行cmd.sh程序:
$ source cmd.sh
或者
$ . cmd.sh
test 用于测试一个表达式的返回值:
if test "$1" = "abc" then cmd fi
可以用[]代替'test'关键字:
if [ "$1" = "abc" ] then cmd fi
但[后和]前必须留有空格,等号两边也要留空格。
一些比较运算符:前面一列用于整形数据,后面一列用于字符串数据
-lt < -gt > -lq >= -gq <= -ne != -eq =
其他参数:
-n "str" 串是否不为空 -e "filename" 文件是否存在 -f "filename" 文件是否是普通文件 -d "filename" 是否是目录
shell后面的参数:
$# 参数的个数,不包括命令本身 $? 最后一个进程返回值 $0 命令本身 $1 第一个参数,依次类推:$2,$3... $@ 所有的参数,形如:"$1" "$2" "$3" ... $$ 包含当前进程ID $! 最后一个后台进程的ID
可以用如下shell取出传入参数:
#!/bin/bash if [ $# -lt 6 ] then echo usage: -a para1 echo [-b para2] [-c para3] exit 0 fi for element in #@ do if [ "$1" = "-a" ] then var1="$2" elif [ "$1" = "-b" ] then var2="$2" elif [ "$1" = "-c" ] then var3="$2" fi shift # 改变参数的引用,$2变成$1, $3变成$2 ... done
注意:shift命令将会改变'$@'的值,循环结束后,'$@'值变为null。
有关awk的使用:
### m.tmp ### table1 table2 ... #############
把m.tmp文件中的每一行前后插入字符串,并写回文件:
cat m.tmp | awk '{ print "delete from " $1 ";" }' > m.tmp
避免交互过程,一次性设定新密码:
echo "newpasswd" | passwd --stdin username
从命令行读入:
#!/bin/sh while true do echo "are you sure to do this? [y/n]" read str if [ "$str" = "y" -o "$str" = "Y" ] then break if [ "$str" = "n" -o "$str" = "N" ] then exit 0 else continue fi done
read 后面可以不声明变量,则用户输入会写入默认变量$REPLY.


