Chinaunix首页 | 论坛 | 博客
  • 博客访问: 187185
  • 博文数量: 76
  • 博客积分: 2510
  • 博客等级: 少校
  • 技术积分: 831
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-31 00:52
文章分类

全部博文(76)

文章存档

2010年(58)

2009年(18)

我的朋友

分类:

2010-03-05 10:45:21


Bash programming


#!/bin/bash

#Test $()---use for embedded bash command
for i in $(ls);do
    echo item: $i
done


 item: bin
 item: code
 item: Desktop
 item: doc




#!/bin/bash
# Test seq

# Test ${} -- use for variable
for i in `seq 1 5`;do
    echo item: ${i}s
    sleep 1
done


item: 1s
item: 2s
item: 3s
item: 4s
item: 5s






IO redirection
1. stderr 2 file

jili@jili-desktop:~$ ls non_exit_file 2>log
jili@jili-desktop:~$ cat log
ls: cannot access non_exit_file: No such file or directory

2. stderr 2 stdout

jili@jili-desktop:~$ ls non_exit_file 2>&1
ls: cannot access non_exit_file: No such file or directory

 3. stdout 2 stderr
jili@jili-desktop:~$ ls non_exit_file 1>&2
ls: cannot access non_exit_file: No such file or directory

 4. stdout and stderr 2 file
jili@jili-desktop:~$ ls non_exit_file &> /dev/null
jili@jili-desktop:~$







#!/bin/bash
#Test local variable
#Local variable can be declared with "local" identifier
whom=Mom
function hello {
    local whom=Dad
    echo Hello $whom at $(date +%Y%m%d).
}

echo Hello $whom
hello
echo Hello $whom


--------test result--------------------------

 Hello Mom
 Hello Dad at 20100305.
 Hello Mom





#!/bin/bash
#Test if and else

var1="hi"
var2="hello"

if [ "$var1" = "$var2" ];then
    echo Matched
else
    echo Different
fi


--------test result--------------------------

 Different






#!/bin/sh
#test while

CNT=1
while [ $CNT -lt 5 ];
do
    echo The counter value is $CNT
    CNT=`expr $CNT + 1`
done


------------------------

The counter value is 1
The counter value is 2
The counter value is 3
The counter value is 4


#!/bin/bash
#Test until

CNT=5

until [ $CNT -lt 1 ]; do
    echo The counter value is $CNT
    let CNT-=1
done


--------------------------------------------

The counter value is 5
The counter value is 4
The counter value is 3
The counter value is 2
The counter value is 1







#!/bin/bash
#test select

OPTIONS="Apple Pair"

#OPTIONS="Apple, Pair" //not work
select opt in $OPTIONS; do
    if [ "$opt" = "Apple" ]; then
        echo "I want an apple."
    elif [ "$opt" = "Pair" ]; then
        echo "I want a pair."
    else
        echo "Thanks."
    fi
    exit 0
done

---------------------------

1) Apple
2) Pair
#? 1
I want an apple.


1) Apple
2) Pair
#? 2
I want a pair.

1) Apple
2) Pair
#? 3
Thanks.


#!/bin/bash
#test return value, assuming directory is not exits.

cd /data &> /dev/null
echo return_val: $?
cd $(pwd) &> /dev/null
echo return_val: $?

-----------------------------------

return_val: 1
return_val: 0

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