码迷,mamicode.com
首页 > 系统相关 > 详细

linux shell 基础语法A-1

时间:2019-08-29 21:41:07      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:roo   pass   shell 基础   指定   场景   图片   就是   null   http   

从echo开始
echo可以看做print printf之类的东西。几乎所有的shell脚本都离不开echo。
echo有如下几个作用:
(1)输出脚本执行流程的提示信息
(2)交互式脚本打印提示信息
(3)构建格式化的日志
(4)调试脚本时,可以用来打印出一些中间变量的值(当然也可以用bash +x调试执行脚本)

常用的option
-n:不换行打印
-e:识别转移字符(如\t)
许多脚本的usage就是echo来实现的(cmd -h or cmd --help)。

变量
变量分类:一般在shell中分为环境变量,用户变量,位置变量等的特殊变量三大类。shell是一种弱类型语言(强类型语言c,变量定义后要强制变换才能使用另一种变量类型,而shell不关心,变量的类型依据使用环境自己变化)。
但我们还是可以把shell中使用变量分为几个场景:
(1)字符串
root@ubuntu-jpk:~# echo "hello world"
hello world
(2)数值
root@ubuntu-jpk:~# a=1
root@ubuntu-jpk:~# b=2
root@ubuntu-jpk:~# c=$((a+b))
root@ubuntu-jpk:~# echo $c
3
(3)一维数组(列表)
root@ubuntu-jpk:~# list=(China America Japan)
root@ubuntu-jpk:~# echo ${list[0]}
China
root@ubuntu-jpk:~# echo ${list[1]}
America
(4)字典
实例 统计词频
#!/bin/bash
declare -A dict

while read word
do
if [ ! -n dict[${word}] ]
then
dict[${word}]=1
else
let dict[${word}]++
fi
done
echo -e "word\tcount"
for key in echo ${!dict[*]}
do
echo -e "$key\t${dict[$key]}"
done

root@ubuntu-jpk:/mnt/linux-shell-code/chapter2# cat testnum
a
b
b
b
c
c
jpk
jpk
a
root@ubuntu-jpk:/mnt/linux-shell-code/chapter2# cat testnum | bash dic.sh
word count
jpk 2
a 2
b 3
c 2

重定向
输出重定向> >>
输入重定向<
重定向多用于打印日志,和调整输出。重定向输出往往和文件描述符结合使用
常见的文件描述符有stdin0 stdout1 stderr2
(1)不想打印出错误信息
root@ubuntu-jpk:/# asdas
asdas: command not found
root@ubuntu-jpk:/# asdasd 2>/dev/null
(2)执行输出都打印到一个文件,包括错误
root@ubuntu-jpk:/mnt# asd >> testlog 2>&1
root@ubuntu-jpk:/mnt# date >> testlog 2>&1
root@ubuntu-jpk:/mnt# cat testlog
No command ‘asd‘ found, but there are 22 similar ones
asd: command not found
Thu Aug 29 20:50:27 CST 2019
(3)执行输出打印到一个文件,错误打印到另外一个文件
root@ubuntu-jpk:/mnt# date 1>>rightlog 2>>errorlog
root@ubuntu-jpk:/mnt# asd 1>>rightlog 2>>errorlog
root@ubuntu-jpk:/mnt# cat rightlog
Thu Aug 29 20:51:20 CST 2019
root@ubuntu-jpk:/mnt# cat errorlog
No command ‘asd‘ found, but there are 22 similar ones
asd: command not found
在shell脚本中不用每个命令都去后面都执行>> >
可以在脚本开头exec 1>file即可
输入重定向了解即可
root@ubuntu-jpk:/mnt# wc <<EOF

as
asd
asdd
EOF
3 3 12

管道
把前一个命令的输出对接到后一个命令的输入,管道对接的2个命令的文件描述符。grep等常用管道来进行检索。
root@ubuntu-jpk:/mnt# date | wc
1 6 29
root@ubuntu-jpk:/mnt# cat /etc/passwd |grep root
root:x:0:0:root:/root:/bin/bash

状态码
0是正确,其他都有问题。
如果使用exit 退出指定退出码大于255,就会对256取余操作。
技术图片

linux shell 基础语法A-1

标签:roo   pass   shell 基础   指定   场景   图片   就是   null   http   

原文地址:https://blog.51cto.com/12374206/2433778

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!