@sangyy
2015-09-04T16:14:55.000000Z
字数 1908
阅读 1497
compiler2015
Linux/Unix的用户通常使用shell来工作。shell有两种执行方式:Interactive(交互式:在终端下用户每输入一条指令,shell就执行一条)和Batch(批处理:将多条指令写入脚本文件中,调用shell一次执行所有指令)。
在课程实验中有多处要用到shell script,建议同学们使用它来调试,提交程序时将测试步骤写入脚本中。
新建一个文件hello.sh,输入以下内容:
#!/bin/bashecho "Hello World!"# I will print Hello World!
其中第一行指明该文件该使用/bin/bash执行,第二行输出一个字符串。第三行是注释,所有的注释均以#开头。
我们可用两种方法执行它:
bash hello.sh
或者
chmod +x hello.sh./hello.sh
chmod赋予文件可执行权限,./hello.sh执行该文件,系统会根据文件第一行指明的/bin/bash来执行它。
var.sh
var=1str=waterecho $varecho "I like ${str}melon"
给变量赋值时注意等号两边不能有空格。使用变量时要在前面加$符。
$str和${str}效果是一样的,花括号的作用是标注变量名的边界。
在shell中,'$str'是强引用,引号中的变量名不会替换。而使用"$str"则会替换变量名。
arg.sh
echo "I received $# parameters"echo "They are: $@"echo "The file name is: $0"echo "The first parameter is: $1"
执行bash arg.sh abc 123 hello
其中$#为参数个数,$@为所有参数($*有类似功能,但稍有区别),$0为文件名,$1为第一个参数,依次类推。参数超过10个时要用${10}而不是$10
if.sh
a=hellob=helloc=hi# ifif [ $a = $b ]thenecho "a==b"fi# if elseif [ $a != $b ]thenecho "a!=b"elseecho "a==b"fi# if elifif [ $a != $b ]thenecho "a!=b"elif [ $a != $c ]thenecho "a!=c"fi
使用了一些逻辑表达式,总结如下:
| Operator | Description |
|---|---|
| 1 -eq 2 | equal |
| 1 -ne 2 | not equal |
| 1 -lt 2 | less than |
| 1 -le 2 | less or equal |
| 1 -gt 2 | greater than |
| 1 -ge 2 | greater or equal |
| ! false | negation |
| true -o false | or |
| true -a false | and |
| ab = ac | string equal |
| ab != ac | string not equal |
| -z ab | string length is 0 |
| -n ab | string length is not 0 |
| -e file | file exist |
| -d file | file is directory |
| -s file | file is not empty |
| -r file | file is readable |
| -w file | file is writable |
| -x file | file is executable |
for.sh
for i in 1 2 3 4 5doecho $idone# or we can use seqfor i in `seq 5`doecho $idone# loop over all files within a directoryfor file in /bindoecho $filedone
注:shell会先执行撇号中的指令,然后将执行结果替换到原来位置再继续执行。
while.sh
i=1while [ $i -lt 100 ]doi=`expr $i + $i`done
注:expr会计算参数列表对应的表达式。
print.sh
#printf (C style)printf "%d is %s\n%d is %s" 10 "ten" 20 "twenty\n"#echo -e (with color)echo -e "\033[0;31m"echo "[==start==]"echo -e "\033[0m"ls ~echo -e "\033[0;31m"echo "[===end===]"echo -e "\033[0m"
Unix Shell Tutorial
Linux Shell Scripting Tutorial A Beginner's handbook
Shell教程