Chinaunix首页 | 论坛 | 博客
  • 博客访问: 40196
  • 博文数量: 37
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 372
  • 用 户 组: 普通用户
  • 注册时间: 2013-10-12 23:27
文章分类

全部博文(37)

文章存档

2014年(5)

2013年(32)

我的朋友

分类: LINUX

2013-11-20 11:39:58

总是写了忘,忘了查,查了写,写了忘。。。无限循环。故博客记录一下。。。




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


阅读(81) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~