Chinaunix首页 | 论坛 | 博客
  • 博客访问: 254529
  • 博文数量: 54
  • 博客积分: 1761
  • 博客等级: 上尉
  • 技术积分: 585
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-17 23:30
文章分类

全部博文(54)

文章存档

2013年(4)

2012年(7)

2011年(15)

2010年(28)

分类: LINUX

2013-05-22 02:25:07

advanced topic in shell programming

1. array

modern shell supports types in array.

there are 3 majors ways to create array

declare:
declare -a myarray

initialize value:
area3=([17]=seventeen [24]=twenty-four)
array=( element1 element2 elementN )

#you can use command output to initialize an array
#remember to declare it as array
array1=( `cat "$filename"`)


operations on array

echo ${string[@]}
echo ${#string[@]}
echo ${string[1]} #index can be literal or variable(without $)


2. indirect reference



there are some cases, you need variable name from a variable.

a=b
b=c

you intend to get c with $$a, first $a is transformed to b, then $b get the result of c

there are two ways to handle this.

1. traditional way:


eval f=\$$a

2. bash way

shell use ${!indirect} to get pointer
to solve above issues, you may use
${!a}

3. list operation


there are cases when you often use if and else to run a sequence of commands check previous steps return code
before you proceed.

a good habit to avoid complex if/then/else is using && and || glue.



or operation


command-1 || command-2 || command-3 || ... command-n
Each command executes in turn for as long as the previous command returns false.

and operation

command-1 && command-2 && command-3 && ... command-n
Each command executes in turn, provided that the previous command has given a return value of
true (zero).


4. process substitution


we have some concepts about input redirect and output redirect
but sometimes, it's not enough, we need multiple input from different files.

<(list)
>(list)

to command, above process substitution looks like they are two files. and command acting on the files

for example:

uniq <(sort a)

underlying the scene, shell sort file a and store it into some temp file /proc/pid/n, then
uniq acts on /proc/pid/n

5. options


set

-o verbose or -v

will echo commands

-x

debug mode

-o posix

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