总是写了忘,忘了查,查了写,写了忘。。。无限循环。故博客记录一下。。。
1.传递参数
$1,$2,... 依次为运行脚本时传入的参数
thua@thua-lnxl:~$ cat printArg.sh
#!/bin/sh
echo "$1,$2"
thua@thua-lnxl:~$ ./printArg.sh hello world
hello,world
2.for循环
for ... in ...
do
...
done
thua@thua-lnxl:~$ cat animals.txt
dog
cat
fish
monkey
thua@thua-lnxl:~$ cat printAnimal.sh
#!/bin/sh
file=$1
for animal in $(cat $file)
do
echo $animal
done
thua@thua-lnxl:~$ ./printAnimal.sh animals.txt
dog
cat
fish
monkey
3.if判断
if [...]; then
...
else
...
fi
thua@thua-lnxl:~$ cat animals.txt
dog
cat
fish
monkey
thua@thua-lnxl:~$ cat printAnimal.sh
#!/bin/sh
file=$1
if [ -e $file ]; then
for animal in $(cat $file)
do
echo $animal
done
else
echo "file not exist"
fi
thua@thua-lnxl:~$ ./printAnimal.sh nofile.txt
file not exist
thua@thua-lnxl:~$ ./printAnimal.sh animals.txt
dog
cat
fish
monkey
4.case语句
case ... in
"...")
...
;;
"...")
...
;;
esac
thua@thua-lnxl:~$ cat printAnimal.sh
#!/bin/sh
file=$1
case $file in
"animals.txt")
for animal in $(cat $file)
do
echo $animal
done
;;
"animals_1.txt")
echo "this animals cannot be printed..."
;;
esac
thua@thua-lnxl:~$ ./printAnimal.sh animals.txt
dog
cat
fish
monkey
thua@thua-lnxl:~$ ./printAnimal.sh animals_1.txt
this animals cannot be printed...
5.function
function ...
{
...
}
thua@thua-lnxl:~$ cat animals.txt
dog
cat
fish
monkey
thua@thua-lnxl:~$ cat printAnimal.sh
#!/bin/bash
function is_success {
if [[ $? -ne 0 ]]; then
echo $1
else
echo $2
fi
}
cat $1
is_success "print failed" "print success"
thua@thua-lnxl:~$ ./printAnimal.sh animals.txt
dog
cat
fish
monkey
print success
thua@thua-lnxl:~$ ./printAnimal.sh animals_1.txt
cat: animals_1.txt: No such file or directory
print failed