shell学习笔记

1,I/O重定向
> 输出到文件,如果不存在该文件会新建。如果存在,则覆盖内容。
>> 输出到文件,添加到文件的结尾。不会导致已存在文件内容被覆盖。
< 输入重定向,来源于文件


sort 命令
sort source_file sorted_file  等同于如下写法:sort>sorted_file<source_file
该命令的效果是,将source_file的内容排完序后,输出到sorted_file

要使用排序的文本替换原始文件,请输入:
sort -o vegetables vegetables此命令序列将排序输出存入 vegetables 文件( -o vegetables)。

转换文件的内容大小写
tr "[a-z]" "[A-Z]" source_file dest_file


对管道的理解:
管道是不利用临时文件,将一个程序的输出与另一个程序的输入连接起来的方法。
管道的定义:
"A pipe is nothing but a temporary storage place where the output of one command is stored and then
passed as the input for second command. Pipes are used to run more than two commands ( Multiple
commands) from same command line."

more  输出一屏的内容

查看一个文件的第20行-30行的内容输出到目标文件
$ tail +20 < hotel.txt | head -n30 >hlist
以上的代码有点不理解?


"A process is program (command given by user) to perform specific Job. In Linux when you star
process, it gives a number to process (called PID or process-id), PID starts from 0 to 65535."

 

bc 和 Linux shell 对于true/false 使用不同的值:
bc: true/false : 1/0
linux shell:true/false : 0/Non zero value

使用操作符时,两边的操作数需要与操作符有空格间隔。
例如:test 1 = 1

逻辑操作符:
!expression         逻辑非
expression1 -a expression2    与操作
expression2 -o expression2    或操作

for in
do
done

while []
do
done

case  in
xxx) command;;
xxx) command;;
esac


shell 脚本的调试
sh -v shell_script
sh -x shell_script

ls > /dev/null
/dev/null 是特殊的linux文件,程序可以将任何不想要的输出,发送到该文件


局部和全局shell变量
一般的变量仅对当前shell可见,如果切换新的shell,则无法访问老的shell变量。
如果希望该变量全局可见,可以用export命令导出该变量。

shell里&&以及||---短路运算符
示例:$ rm myf && echo "File is removed successfully" || echo "File is not removed"

I/O重定向
cat>dest.txt
10
-20
11
2
^D
将这四个数字输入到dest.txt中,按ctrl+D保存输入。
sort<dest.txt
-20
2
10
11

linux的标准输入输入:stdin,stdout,stderr
对应的文件描述符分别为:0,1,2
rm unkown.txt 2>output.txt
该重定向,会将stderr重定向输出到output.txt


Function(函数)
Function is series of instruction/commands.


trap 命令用于在收到某种信号(中断,kill,quit等)时,采取相应的操作。
比如,人为中断程序时,shell 脚本可以利用trap命令,在完全退出时,做一些清理临时文件的操作。

 

shift命令
将位置参数左移。可以在后面制定左移的数量
$1 = -f $2 = foo $3 = bar
执行shift命令后:
$1=foo, $2=bar, $3=
该命令在解析命令行参数时有用,不过一般针对是比较简单的命令行参数场景。

 

awk
awk '{print $0}' source_file
$0是特殊的wak变量,打印source_file的一整行记录。
awk -f source_shell  -f选项是让awk,从给定的文件中读取命令。

awk中的预定义的变量
NR --number of input record
NF --number of fields in input record

printf "%s is my sweet home",ENVIRON["HOME"]

awk脚本文件中,支持用{}将代码块包含起来。
在awk中,system()函数用来执行给定的系统命令,比如cp,rm等
示例:system("rm foo")
命令的输出对于程序而言是无法获取的,不过system()函数会返回exit code,从而可以判断命令是否执行OK。
if(system(cmd) != 0)
 printf "not ok\n"
else
 printf "ok\n"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值