最近用shell做个小工具,发现很多东西在使用的时候,反而没有那么清楚的印象。总结一下最近的小技巧,希望拯救下自己就贫瘠的记忆
1. shell [[]]判断后,多条语句 &&
2. shell 清空文件:
way 1: echo "" >$file 不好,会多一行空白行
way 2: > $file 好,解决了way1的问题
3. read file by line:
while read line;do
done< $file
4. diference between unset and "" :
5. grep 多个pattern: grep -E 'PATTERN1.*PATTERN2' FILE
6. 取出第二个字段: "a b"
s="a b"
echo ${s##* }
7. grep的参数里引用其他变量中,但是里面有dollar符号的:
'^'"$user"'\s+\$'"$hashNum"`
8. $() and `` 斜单引号
$()POSIX command substitution syntax ,you can
https://www.quora.com/Bash-shell-What-does-the-sign-mean-when-one-puts-date-in-the-dollar-sign
But I recommend using $() all the time because you can nest other subcommands inside it. So, you can do things like $(command1 -params $(command2 -params)) or go completely haywire with more nestings.
For example: ret=$(ls /root)
如果希望取得命令的返回结果,必须用$()的形式, 单反冒号是不行的
9. file replace one line which contrains some substring: sed -i -e "s/^${user}.*/${replaced}" $file
10. shell boolean: var=true, if [ $var = true ]
11. get last line of file: tail -1 $file
12. ”sed“ match space or tab:
sed -i "/^DenyUsers[[:space:]].*$user.*/ s/$user/meas/g" /etc/ssh/sshd_config
sed -i "/^DenyUsers\s.*$user.*/ s/$user/something/g" /etc/ssh/sshd_config
13. sed, add one file to another file after matched lines,非常实用:
sed -i '/\/bin\/ksh/r'" $file" $script note: add content from $file to $script after line "/bin/ksh"
14. shell 逻辑运算,条件判断:http://www.tldp.org/LDP/abs/html/comparison-ops.html
15. shell, difference between "print" "echo":
未完待续