Requirement-Driven Linux Shell Programming

*/-->

Requirement-Driven Linux Shell Programming

Table of Contents

  • 1. Where can I find the basic Material about Linux Shell
    Programming?

  • 2. How to time a function/program(Get the execution time
    of a program)?

  • 3. How to pass parameters to a function?

  • 4. How to calculate float point in Shell?

  • 5. How to output nicer to the console, like a
    table?

  • 6. How to print the destined(specific) line of a
    file?

  • 7. How to covert column to row?

  • 8. How to output a certain lines of a file?(Say, all but
    the first line)

  • 9. How to list(copy) all the executable files in a
    directory?

  • 10. The short key for adding source block in org
    mode:

  • 11. How to remove the duplicated newlines in a
    file?

  • 12. How to transpose a file(to convert all the colums to
    rows)?

Recently, I am doing a little project on linux filesystem, and some testing
work must be done by high-level applications written in C or other script
languages. When I am running the test cases, I find it annoying to do all these
works by hand, so I start to learn the linux shell programming, and I decide to
write the most important concept and skills down to remind myself or to provide
those who are interested in shell programming with the starting material…

I will record my progress and the useful skills I learned when the project is
carrying on in the Q&A form, which I think is a clean and simple way to
organize my thoughts and that, I hope, won‘t take me too much time…

Note:What I will cover in this post is not the step-by-step tutorial for
shell programming, but rather the kind of problems one will meet in a real
project, and I make the assumption that the readers are already equipped with
basic knowledge about the shell script.

1 Where can I find the
basic Material about Linux Shell Programming?

I found this tutorial useful,A Beginner‘s Handbook for Linux Shell
Scripting
. There are many places you can find such materials, and you can
take a quick look at it whenever you are in need.

2 How to time a
function/program(Get the execution time of a program)?

Command Format: time the_program_to_be_tested
Note:the output of "time"
command will be the STDERR_FILENO,in my case, I want to redirect the output to a
file, so the following command is used:



time ./the_program_to_be_tested > result
2>&1

3 How to pass parameters to
a function?

Suppose the following code section:

1: time_xtar_load()
2: {
3: time ./xtar_load $1
4: }
5:
6: for ((i = 0;i < $num_process;i++))
7: do
8: time_xtar_load $i &
9: done

In this example, a function named time_xtar_load is defined, and the "for"
statement will evoke the function many times each with a different parameter,
that is, the running value of i.

4 How to calculate float
point in Shell?

The default behavior of the shell to the calculation works is limited to
integers, the tool "bc" is needed to do more advanced calculations.for example:

1: while read MINUTE SECOND
2: do
3: total=`echo "$MINUTE * 60 + $SECOND" | bc`
4: sum=`echo "$total + $sum" | bc`
5: done < ctar_load_sys
6:
7: avg=`echo "scale=10;$sum / $n" | bc`

In the above code segment, two self-defined variables(MINUTE, SECOND) are
read from a file named "ctar_load_sys", they are used to get the total number in
seconds, and after the while terminates, the average time is calculated with the
last line of code.Note that the "scale=10" is necessary to do the decimal
computation.

5 How to output nicer to
the console, like a table?

The "printf" command can do exactly what we can do in C/C++, it has rich
formats to choose from. For example:

1: header="\n %-10s %10s %10s\n"
2: format=" %-10s %10.3f %10.3f\n"
3: printf "$header" " " "sum" "avg"
4: printf "$format" 5: real $sum $avg 6: sys $sum $avg

The above code prints a table on the console as follows:









  sum avg
real 2.36 2.35

6 How to print the
destined(specific) line of a file?

Use the following command:



sed -n 1p

7 How to covert column to
row?

Say, I have a file(nofs) which has the following contents:

nofs 30.049 57.857 115.718

and I want to covert it to one row, there are many ways to do it:

1.The awk way:




cat nofs awk ‘{printf("%s ",$0)}‘

2.The tr way:



tr ‘\n‘ ‘ ‘ < nofs

3.The echo:







echo $(<nofs)
xargs echo < nofs
cat nofs xargs

All of the above methods will output like:



nofs 30.049 57.857 115.718

8 How to output a certain
lines of a file?(Say, all but the first line)



tail -n +2 filename

will output the file contents from the second line.

9 How to list(copy) all the
executable files in a directory?

List:

1: find . -executable -type f

Copy:

1: find . -executable -type f | xargs -i cp {} /tmp

10 The short key for
adding source block in org mode:

1: <s TAB

11 How to remove the
duplicated newlines in a file?

I get a file with the following format:

write rewrite read re-read randread
randwrite

32149.29 35625.84 37261.05 37575.87 713.54 1606.12

57465.48 62242.62 66024.14 66969.32 1430.75 3365.54

89339.57 96388.80 104037.65 103917.83 2714.76 6479.37

128849.01 132933.47 133952.92 134381.05 5482.03 12207.46

126489.87 128470.04 129826.87 130348.56 10446.49 24424.78

127078.48 128236.06 128642.23 129169.20 19505.88 40367.71

126942.59 125676.09 128773.13 128896.08 32061.20 63187.50

127596.32 128102.95 128516.09 129485.38 51048.20 82756.15

126424.50 127839.95 128780.78 129846.62 72924.07 97219.43

125817.65 127208.07 128134.88 129057.43 92172.60 85037.41

128768.69 129389.45 130342.52 131162.48 107949.98 100109.50

127326.84 128567.19 129666.99 129796.52 117193.84 108822.87

And I just want to remove all the empty lines of the file, the following
command can be used:




sed ‘/^$/d‘ input_file_name > output_file_name

or




awk ‘$1‘ input_file_name > output_file_name

The command will output the following result:

12 How to transpose a
file(to convert all the colums to rows)?

Use the following script:

 1:   transpose_file()
2: {
3: lines_of_file=`wc -l < "$1"`
4: echo $lines_of_file
5: result_file_name="result"
6: >$result_file_name
7:
8: for ((line_index = 1;line_index < $lines_of_file + 1;line_index++))
9: do
10: sed -n ${line_index}p "$1" | tr ‘ ‘ ‘\n‘ | awk ‘$1‘ > /tmp/a
11: paste $result_file_name /tmp/a > /tmp/b
12: cp /tmp/b $result_file_name
13: done
14: }

Author: wujing

Created: 2014-05-01 四 11:48

Emacs 24.3.1
(Org mode 8.2.6)

Validate

Requirement-Driven Linux Shell Programming,码迷,mamicode.com

时间: 2024-08-11 08:41:51

Requirement-Driven Linux Shell Programming的相关文章

5 Shell Scripts for Linux Newbies to Learn Shell Programming – Part II

To Learn something you need to do it, without the fear of being unsuccessful. I believe in practicality and hence will be accompanying you to the practical world of Scripting Language. Learn Basic Shell Scripting This article is an extension of our F

Linux System Programming 学习笔记(十) 信号

1. 信号是软中断,提供处理异步事件的机制 异步事件可以是来源于系统外部(例如用户输入Ctrl-C)也可以来源于系统内(例如除0) 内核使用以下三种方法之一来处理信号: (1) 忽略该信号.SIGKILL和SIGSTOP不能被忽略. (2) 捕捉并且处理该信号.The kernel will suspend execution of the process's current code path and jump to a previously registered function. SIGK

Linux System Programming 学习笔记(五) 进程管理

1. 进程是unix系统中两个最重要的基础抽象之一(另一个是文件) A process is a running program A thread is the unit of activity inside of a process the virtualization of memory is associated with the process, the threads all share the same memory address space 2. pid The idle pro

Linux System Programming 学习笔记(四) 高级I/O

1. Scatter/Gather I/O a single system call  to  read or write data between single data stream and multiple buffers This type of I/O is so named because the data is scattered into or gathered from the given vector of buffers Scatter/Gather I/O 相比于 C标准

Linux Shell sort 指定排序第几列

ip.txt 里存储着ip信息 统计排序后取前10条 awk '{cnt[$1]++} END{for (ip in cnt) print ip":"cnt[ip]}' ip.txt | sort -k 2 -rn -t":" | head -n 10 awk '{cnt[$1]++} END{for (ip in cnt) print cnt[ip],ip}' ip.txt | sort -rn | head -n 10 sort -k  根据第几列排序  -n

linux shell脚本执行错误:bad substitution

脚本test.sh内容: #!/bin/bash read pressKey indexes=0 c=${pressKey:indexes:1} 使用调试方式执行:sh -x test.sh第3行总出现bad substitution提示信息. 百思不得其解: 于是百度,查到一条有用信息,这与linux shell使用的是/bin/sh,还是/bin/bash有关系.我的脚本中指定使用的是/bin/bash shell,但是我在调试的时候使用的是sh shell,因此调试时导致错误提示信息. 解

linux shell 数组建立及使用技巧

转自linux shell 数组建立及使用技巧 linux shell在编程方面比windows 批处理强大太多,无论是在循环.运算.已经数据类型方面都是不能比较的. 下面是个人在使用时候,对它在数组方面一些操作进行的总结. 1.数组定义 [[email protected] ~]$ a=(1 2 3 4 5)[[email protected] ~]$ echo $a1 一对括号表示是数组,数组元素用“空格”符号分割开. 2.数组读取与赋值 得到长度: [[email protected] ~

Linux shell脚本-基础学习笔记

Linux脚本能力不是太强,最近再补习下,毕竟linux shell在日常工作中还是很普遍的, 用起来更方便.省时省力. 以下是学习笔记,偏理论,后面有几个例子,供参考. shell脚本组成元素系统命令.文本处理工具(grep\sed等).变量.条件判断.循环结构和函数 -------------------------------------------- 三剑客:grep,sed,awk,还有wc,sort,head等 ------------------------------------

Linux Shell脚本攻略(1.10)

1.10 获取.设置日期和延时 很多应用程序需要以不同的格式打印日期.设置日期和时间.根据日期和时间执行某项操作.延时通常用于在程序执行过程中提供一段等待时间(比如1秒).同样的,我们也能够一多种格式打印日期,或者在命令行中设置日期.在类Unix系统中,日期被存储为一个整数,其大小为自世界标准时间起所流逝的秒数.这种计时方式称为纪元时或Unix时间. 1.10.1 获取.设置时间 以下的程序给出了多种用法: #!/bin/bash start=$(date +%s) #获取纪元时间 date #