程序员

Shell使用笔记

2018-07-14  本文已影响61人  liuchungui

最近使用shell命令次数越来越频繁,所以做个笔记,方便以后的查找。

if语句使用

if [ -f A ] || [ -d B ]; then
  echo "文件存在"
elif [ -d B ]; then
  echo "文件夹存在"
else
  echo "文件不存在"
fi

知识点:
1、其中,流程关键是if、elif、else、fi
2、表示或的条件是用两个中括号括起来的。

数组操作

获取数组所有元素

${array[*]}
${array[@]}

获取数组中元素个数

length=${$array[*]}

获取第一个元素

first=array[0]

参考:http://c.biancheng.net/cpp/view/7002.html

For循环使用

对所有参数遍历,可以下面这么写:

for i in $*;do
    echo $i
done

注:$*代表了所有元素

也可以如c语言一样写:

for ((i=0; i<10; i++)); do
    echo $i
done

参考:shell中for循环总结

参数变量

参考:Shell特殊变量:Shell 0,#, *,@, $?, $$和命令行参数

shell的判断条件

判断文件或目录是否存在

比较字符写法:

参考: http://wangqiaowqo.iteye.com/blog/1312511

获取文件名和后缀

file="thisfile.txt"
#获取文件名
echo "filename: ${file%.*}"
#获取后缀
echo "extension: ${file##*.}"

shell间接引用

有两种方式:

一种是使用!

a=123
b=a
echo $b 结果为a
echo ${!b} 结果为123

另外一种是eval

a=123
b=a
echo $b 结果为a
eval c=\${$b}
echo $c 结果为123

参考:http://blog.csdn.net/hepeng597/article/details/8057692

使用sed进行字符串替换

下面语句,将index.html中的gw.js替换为gw.js?100

sed -i "" "s/gw.js/gw.js?100/g" index.html

使用参考:http://blog.csdn.net/dawn_moon/article/details/8547408

shell中,字符串替换

下面语句,将.com替换为.cn

test="baidu.com"
echo ${test//.com/.cn}

参考见:http://www.cnblogs.com/chengmo/archive/2010/10/02/1841355.html

shell时间使用

首先,获取当前时间戳

timestamp=$(date +%s)

注意:+前面有个空格

然后,获取当前时间

echo $(date +"%F %T")
echo $(date +"%F_%H:%M:%S")

注意:+后面的字符串是格式

参考:
http://bbs.csdn.net/topics/310230625
http://blog.sina.com.cn/s/blog_95b655e001015r51.html

字符串分割

下面一段脚本,将域名用空格分隔成数组

$domainName="ts.baidu.com pan.baidu.com" 
OLD_IFS="$IFS" 
IFS=" " 
array=($domainName)
IFS="$OLD_IFS"
length=${#array[*]}

参考:http://www.cnblogs.com/jiayy/p/3766286.html

字符串截取:

上面中,*只是一个通配符可以不要

示例如下:

str="1/2/3"
echo ${str##*/}  #输出:3
echo ${str#*/} #输出:2/3
echo ${str%%/*} #输出:1
echo ${str%/*} #输出:1/2

参考:http://www.111cn.net/sys/linux/43822.htm

du使用

# 查看当前目录下文件占用磁盘大小
du -sh *
#查看磁盘大小
df -h

查看当前文件夹下文件数量,不包括文件夹

ls -l |grep "^-"|wc -l

遇到if语句中[: too many arguments错误

是因为if判断中的变量过长,只需要在变量加上双引号就可以了

http://bluemood.blog.51cto.com/1142811/754832

shell通过jq操作json

安装jq,然后通过jq中的语句进行使用
参考:
https://github.com/stedolan/jq/wiki/Installation
jq文档

上一篇 下一篇

猜你喜欢

热点阅读