echo -n "Enter your name :"
echo "Enter your name :\c" 都是不换行
tr -d '\r' < filename.txt | sort > file2name.txt tr命令 删除回车重定向
\{n\},匹配在它前面的单个字符重现的次数区间为n次;\{n,\},至少n次;\{n,m\},n到m次
?匹配于0个或1个前置的正则表达式 : ab?c 匹配 ac、abc;与ab*c比较,后者中间有任意个b
+ 匹配于1个或多个前置的正则表达式 : ab+c匹配 abc、abbc、abbbc 但是没有ac,可以等同于abb*c
sort -t: -k1 /etc/passwd 用户名排序
sort -t: -k3nr /etc/passwd 反向UID排序
uniq -d 仅显示重复的记录
uniq -u 仅显示未重复的记录
trap 'command' EXIT 其中EXIT为扑捉的信号,而command是扑捉到信号后要执行的命令。ERR/DEBUG
示例:
#!/bin/bash
ERRTRAP()
{
echo "[LINE:$1] Error: Command or function exited with status $?"
}
foo()
{
return 1;
}
trap 'ERRTRAP $LINENO' ERR
abc
foo
输出为:
-bash-3.2# sh 13605.sh
13605.sh: line 11: abc: command not found
[LINE:11] Error: Command or function exited with status 127
[LINE:12] Error: Command or function exited with status 1
变量,判断,重复动作
(1)$(( ))会对里面的算数表达式进行计算,在将计算后的结果放回到命令的文本内容。
(2)PATH=$PATH:/usr/local/bin 更新环境变量。
(3)unset -f 解除指定函数;unset -v 解除指定变量
替换运算符
(1)${varname:-word}如果存在切非null就返回其值。否则返回word。
用途:如果变量未定义,则返回默认值
范例:如果count未定义,则${count:-0}的值为0
模式匹配运算符
(1)${variable#pattern} 如果模式匹配于变量值的开头处,则删除匹配的最短部分,并返回剩下的部分
范例:path= /home/tolstoy/mem/long.file.name
${path#/*/} 则返回tolstoy/mem/long.file.name
(2)${variable##pattern} 如果模式匹配变量值的开头处,则删除匹配的最长处,并返回剩下的部分
path=/home/tolstoy/mem/long.file.name
${path##/*/} 则返回long.file.name
$((x += 2)) x=2得到的结果储存在x里面
if....then.....elif.....else.....fi
if [ "str1" = "str2" ];then ...fi
if [ -f "$file" ]
if [ ! -x "$file" ]
if [ -n "$str" -a -f "$file" ] 计算两种条件
if [ -n "$str" ] && [ -f "$str" ] 第一个成功才执行第二个
while与until
区别是如何对待condition 的退出状态,只要condition是成功退出,while会继续循环。只要condition未成功结束,until则执行循环。
read,break,true,sleep
#!/bin/bash
printf "Enter username: "
read user
while true
do
if who | grep "$user" > /dev/null
then
break
fi
sleep 20
done
等待特定用户登录,每30秒一次
函数小例子
wart_for_user () {
until who | grep "$1" > /dev/null
do
sleep ${2:-30}
done
}
return 跟exit意思差不多,但是如果函数中使用exit会退出脚本,而用return会返回一个退出值给调用者。
expr;{ i=`expr $i + 1` }={ i=$((i+1)) }
单引号;范例:#echo 'here are some : * ? [abc] ` $ \'
输出:here are some : * ? [abc] ` $ \
双引号;范例:x="I am x"
echo "\$x is \"$x\" . here is some output: '$(echo hello world)'"
双引号里,字符$、“、`与\,如需要用到字面上的意思,都必须前置\
输出为:$x is "I am x". here is some output: 'hello world'
$(echo hello world)=hello world =`echo hello world
set
转载于:https://blog.51cto.com/linuxmylife/1216761