Wednesday, February 12, 2014

some basic bash syntax

just for use in case it is forgotten.


1) number:
declare -i x=017
declare -i x=2#101
declare -i x=8#17
declare -i x=16#b

2) arithmetic:
n=1
n=`expr $n + 1`
n=`expr $n - 1`
echo $[ 5 + 4 - 2 ]
echo $[(5+3) *2]
echo $(( 5 + 4 ))
let i=5
let i=i+1
let "i = i + 2"
(( i+ 4 ))

3) compare number:
[ $num == 1 ]
[[ $num == 1 ]]

x=2
(( x = 2 ))

4) array:
declare -a nums=(45 33 100 65)
echo ${nums[0]}
echo ${#nums[*]} #number of elements

10) if condition:
if [ $answer = Y -o "$answer" = y ]
if (( $1 < 0 || $1 > 30 ))

11) for
for i in "a" "b" "c"
do
    echo $i
done

12) case
echo -n "Choose a foreground color for your xterm window: "
read color
case "$color" in
[Bb]l??)
    xterm -fg blue -fn terminal &
    ;;
[Gg]ree*)
    xterm -fg darkgreen -fn terminal &
    ;;
red | orange)        
    xterm -fg "$color"  -fn terminal &
    ;;
*)
    xterm -fn terminal
    ;;
esac
echo  "Out of case command

13) until
hour=0
until (( hour > 24 ))
do
    case "$hour" in
        [0-9]|1[0-1]) echo "Good morning!"
            ;;
        12)           echo "Lunch time."
            ;;
        1[3-7])       echo "Siesta time."
            ;;
        *)            echo "Good night."
            ;;
    esac
    (( hour+=1 ))
done

14) select
PS3="Select a program to execute: "
select program  in 'ls -F' pwd date
do
    $program
done

15) trap
trap 'echo "Ctrl-C will not terminate $0."'  INT
trap 'echo "Ctrl-\\ will not terminate $0."'  QUIT
trap 'echo "Ctrl-Z will not terminate $0."'  TSTP
echo  "Enter any string after the prompt.
When you are ready to exit, type \"stop\"."
while true
do
    echo –n "Go ahead...> "
    read
    if [[ $REPLY == [Ss]top ]]
    then
        break
    fi
done

20) update arg:
set 1 2 3
set $(date)
echo $2 # $2 will be the element from date

21) HERE doc:
cat << FINISH
> Hello
> World
> FINISH

cat <<- FINISH
> Hello
> World
> [\t*]FINISH #there may be tab before FINISH



shift
getops
eval

31) array
#declare an array
os[0]="Centos"
os[1]="Ubuntu6"
echo ${os[0]}

#declare an array
declare -a os=(Centos Ubuntu12 freebsd)
#show all the elements in the array
echo ${os[@]}
#show the size of the array
echo ${#os[@]}
#length of the first element
echo ${#os}
echo ${#os[0]}
#length of the second element
echo ${#os[1]}

#get element 1 and 2 from the array
echo ${os[@]:1:2}
#get char 0~5 from second element
echo ${os[1]:0:6}

#search Centos in the array and replace it with Centos6
echo ${os[@]/Centos/Centos6}

#add an element in the array
os=("${os[@]}" "solaris")
echo ${os[@]}

#remove the third element
#but the element is just set to null, which can be checked in the following real remove
#the size of the array will be changed
unset os[2]
echo ${os[2]}
echo ${#os[@]}

#real remove of the element
#remove the third element
pos=2
os=(${os[@]:0:$pos} ${os[@]:$(($pos + 1))})
echo ${#os[@]}
echo ${os[@]}

#remove the third element
os=(${os[@]:0:$pos} ${os[@]:$(($pos + 1))})
echo ${#os[@]}
echo ${os[@]}

#search the pattern os and remove pattern os
declare -a new_os=( ${os[@]/os*/} )
echo ${new_os[@]}

#copy the array to a new array
new_os=("${os[@]}")
echo ${new_os[@]}

#merge two arrays
number=(1 2 3)
os_num=("${os[@]}" "${number[@]}")
echo ${os_num[@]}

#delete the array os_num
unset os_num
echo ${os_num[@]}

#read a file and put its content into an array
#need to create a file to check the following
file_arr=( `cat "file" `)
for f in "${file_arr[@]}"
do
    echo $f
done

100) PS1设置
\t    当前时间是HH:MM:SS格式
\d    日期是"星期 月 日"的格式(如Tue May 26)
\n    换行符
\s    shell的名字,$0的基名(最后一个斜线后面的部分)
\w    当前的工作目录
\W    当前工作目录的基名
\u    当前用户的用户名
\h    主机名
\#    该命令的编号
\!    该命令的历史编号
\$    如果有效的UID是0,是一个#号,否则是$
\nnn  对应于八进制数nnn的字符
\\    反斜杠
\[    开始一非打印字符序列;可在提示符中嵌入一个终端控制序列
\]    非打印字符序列的结束
bash 2.x版以上新增的
\a    ASCII报警字符
\@    以12小时AM/PM格式表示的当前时间
\H    主机名
\T    以12小时格式表示的当前时间:HH:MM:SS
\e    ASCII擦除符
\v    bash的版本
\V    bash的发行号和路径级

101) set开关
allexport            -a 从这个选项被设置开始就自动表明要输出的新变量或修改过的变量,直至选项被复位
braceexpand          -B 打开花括号扩展,是一个缺省设置
emacs                   使用emacs内置编辑器进行命令行编辑,是一个缺省设置
errexit              -e 当命令返回一个非0退出状态(失败)时退出,读取初始化文件时不设置
histexpand           -H 执行历史替换时打开! 和!! 扩展,是一个缺省设置
history                 打开命令行历史;缺省为打开
ignoreeof               禁止用EOF(Control-D)键退出shell;必须键入退出,和设置shell变量IGNOREEOF=10一样
keyword              -k 将关键字参数放到命令的环境中
interactive-comments    对于交互式shell,#用来将后面的文本作为注释
monitor              -m 设置作业控制
noclobber            -C 防止文件在重定向时被重写
noexec               -n 读命令,但不执行.用来检查脚本的语法.交互式运行时不设置
noglob               -d 禁止用路径名扩展;即关闭通配符
notify               -b 通知用户什么时候后台作业完成
nounset              -u 扩展一个没有设置的变量时显示一个错误信息
onecmd               -t 在读取和执行命令后退出
physical             -P 设置时,在键入cd或pwd时禁止符号链接.用物理目录替代
posix                   如缺省操作不符合POSIX标准就改变shell行为
privileged           -p 设置时,shell不读.profile或ENV文件,且不从环境继承shell函数;自动为setuid脚本开启特权
posix                   将缺省行为改为POSIX 1003.2
verbose              -v 为调试打开verbose模式
vi                      使用vi内置编辑器进行命令行编辑
xtrace               -x 为调试打开echo模式

102) jobs
jobs 列出所有正在运行的作业
^z(Ctrl-z) 终止(暂停)作业;屏幕上将出现提示符
bg 启动被终止的后台作业
fg 将后台作业调到前台
stop 暂停一个后台作业
stty tostop 当后台作业向终端发送输出时就暂停它
kill 向zhidiing作业发送kill信号
wait [n] 等待一个指定的作业并返回它的退出状态,这里n是一个PID或作业号
103) jobs命令的参数
%n 作业号n
%string 以string开头的作业名
%?string 作业名包含string
%% 当前作业
%+ 当前作业
%- 当前作业前的一个作业
-r 列出所有运行的作业
-s 列出所有暂停的作业

104) 历史变量
FCEDIT       使用fc命令的UNIX编辑器的路径名
HISTCMD      当前命令的历史编号,或在历史清单中的序号
HISTCONTROL  如果设置了ignorespace的值,以空格开头的行将不会进入历史清单
             如果设置了ignoredups的值,和最后一个历史行匹配的行不会进入
             ignoreboth的值综合了两个选项的效果.如果没设置,或设成上面两个值以外的其他值,那么解释器读到的所有行都将保存在历史清单中
HISTFILE     指定保存命令行历史的文件,缺省是~/.bash_history.如没设置,当一个交互式shell退出时不会保存命令行历史
HISTFILESIZE 历史文件能包含的最大行数.当给这个变量赋值后,如果有必要,历史文件将被截尾,以使包含的行数不超过这个数.缺省值是500
HISTIGNORE   以冒号分隔的一系列模式,用来决定哪些命令行应该保存在历史清单中.每个模式确定行的开始且包括正常的shell匹配字符模式.用于模式中的&使history命令忽略重复:例如,ty??;&将匹配任何以ty开头,后跟两个字符的命令行,以及该命令的重复形式.这些命令不会放入历史清单中
HISTSIZE     记录在命令历史中的命令数.缺省值是500

105) fc参数
-e editor  将历史清单调入编辑器中
-l n-m     列出编号从n到m的命令
-n         关闭历史清单的编号
-r         反转历史清单的序号
-s string  访问以string开头的命令

106) 替换和历史
!              说明开始历史替换
!!             重新执行上一条命令
!N             重新执行历史清单中的第N条命令
!-N            重新执行从当前命令往回数的第N条命令
!string        重新执行最后一条以串string开头的命令
!?string?      重新执行最后一条包含串string的命令
!?string?%     重新执行历史清单中最近一个包含串string的命令行参数
!$             用上条命令的最后一个参数最为当前命令行
!!string       将string添加到上一条命令的最后并执行
!N string      将string添加到历史清单中第N条命令的最后并执行
!N:s/old/new/  在前面的第N条命令中,将第一次出现的old串替换成new串
!N:gs/old/new/ 在前面的第N条命令中,将所有的old串替换成new串
^old^new^      在上一条命令中,用new串替换old串
Command!N:wn   在当前命令后添加一个来自前第N个命令的参数(wn)并执行它.wn是一个从0,1,2,...开始的数,表明前面那个命令的第几个词;词0是命令本身,1是它的第一个参数

107) 元字符
*          匹配0或多个字符
?          匹配一个字符
[abc]      匹配a,b,c这组字符中的一个
[!abc]     匹配a,b,c这组字符以外的某个字符
{a,ile,ax} 匹配一个或一组字符
[!a~z]     匹配不在a到z这个范围内的某个字符
\          转义或禁用后面那个元字符

108) 扩展的文件名globbing
打开方式: shopt -s extglob
abc?(2|9)1       ?与0次或一次出现在括弧中的任意模式相匹配.竖杠代表或条件;例如2或9.匹配abc21,abc91或abc1
abc*([0-9])      *与0次或多次出现在括弧中的任意模式相匹配.匹配abc后跟0个或多个数字;例如abc,abc1234,abc3,abc2等
abc+([0-9])      +与一次或多次出现的括弧中的任意模式相匹配.匹配abc后跟一个或多个数字;例如abc3,abc123等
no@(one|ne)      @只与括弧中任意模式的一次出现相匹配.匹配noone或none
no!(thing|where) !与括弧中的任意模式除外的其他所有串相匹配.匹配no,nobody或noone,但是没有nothing或nowhere

109) declare选项
-f 列出函数的名字和定义
-r 将变量设为只读
-x 将变量名输出到子shell中
-i 将变量设为整型
-a 将变量当作一个数组;即分配元素
-F 只列出函数名
(-a和-F只在bash2.x版中实现)

110) local函数可以用来创建局部变量,但仅限于在函数内使用

111) _(下划线) 上一个命令的最后一个参数

112) bash的变量
BASH           展开为调用bash实例时使用的全路径名
BASH_ENV       和ENV一样,但只可在bash2.0或更高版本中设置.在bash2.x以前版本中没有
BASH_VERSINFO  使用2.0以上版本的bash时,展开为版本信息.在bash2.x以前版本中没有
BASH_VERSION   展开为当前bash实例的版本号
CDPATH         cd命令的搜索路径,它是以冒号分隔的目录列表,shell通过它来搜索cd命令指定的目标目录.例如:~:/usr
COLUMNS        设置该变量就给shell编辑模式和选择的命令定义了编辑窗口的宽度
DIRSTACK 在2.0或以上版本的bash中,代表目录栈的当前内容.在bash2.x以前版本中没有
EDITOR         内置编辑器emacs,gmacs或vi的路径名
ENV            每一个新的bash shell(包括脚本)启动时执行的环境文件.通常赋予这个变量的文件名是.bashrc.ENV的值被解释作路径名前,shell先要对其进行参量扩展,命令替换和算术扩展
EUID           展开为在shell启动时被初始化的当前用户的有效用户ID
FCEDIT         fc命令的默认编辑器名
FIGNORE        执行文件名补全时,可忽略的以冒号分隔的后缀列表.以FIGNORE中任一项为后缀的文件名被从匹配的文件名列表中排除.一个例值为o:~
FORMAT         用来格式化在命令管道上的time保留字的输出
GLOBIGNORE     在文件名扩展(称为globbing)时被忽略的文件列表.在bash2.x以前版本中没有
GROUPS         一列当前用户所属的组.在bash2.x以前版本中没有
HISTCMD        当前命令的历史编号或历史清单中的序号.如HISTCMD被复位,即使它随后就会重置,也将是去它的特殊属性
HISTCONTROL    如果设置了值ignorespace,以一个空格符开头的行将不会进入历史清单.如果设置了值ignoredups,那和前一个历史行匹配的行不会进入.值ignoreboth结合了这两个选项.如果被复位,或设置成除了上面所说的任意其他值时,所有被解释器所读的行都将保存在历史清单中
HISTFILE       指定保存命令行历史的文件.缺省值是~/.bash_history.如果被复位,交互式shell退出时将不保存命令行历史
HISTFILESIZE   历史文件能包含的最大行数.当给这个变量赋值后,如果有必要,历史文件将被截尾,以使包含的行数不超过这个数.缺省值是500
HISTSIZE       记录在命令行历史文件中的命令数.缺省是500
HOME           主目录;未指定目录时,cd命令将转向该目录
HOSTFILE       包含一个格式和如同/etc/hosts的文件的名字,当shell需要补全一个主机名时将读取该文件.文件可以交互式更改;下一次试图补全主机名时,bash将新文件的内容添加到已经存在的数据库中
HOSTTYPE       自动设置正在运行bash的机器的类型.缺省值是由系统决定的
IFS            内部字段分隔符,一般是空格符(SPACE),制表符(TAB)和换行符(NEWLINE),用语由命令替换,循环结构中的表和读取的输入产生的词的字段划分
IGNOREEOF      控制shell接收到单独一个EOF字符时的反应.如果设置,它的值就是shell退出前在一个输入行的最前面键入的连续EOF字符的个数.如果变量存在但没有一个数字值,或没有值,那么缺省值是10.如果它不存在,EOF意味着给shell的输入的终止,它只在交互式shell中有效
INPUTRC        readline启动文件的文件名,不考虑缺省的~/.inputrc
LANG           为没以LC_开头的变量明确选择的种类确定locale类
LC_ALL         忽略LANG和任何其他LC_变量的值.在bash2.x以前的版本中没有
LC_COLLATE     对路径名扩展的结果进行排序时的整理顺序,以及匹配文件名与模式时的范围表达式,等价类和整理序列的行为.在bash2.x以前版本中没有
LC_MESSAGES    用于转换前面有一个$的双引号串的locale.在bash2.x以前版本中没有
LINENO         每次shell在一个脚本或函数中替换代表当前连续行号(从1开始)的十进制数时,都将引用该参数
MACHTYPE       包含一个描述正在运行bash的系统的串
MAIL           如果该参数被设置为某个邮件文件的名字,而MAILPATH未被设置,当邮件到达MAIL指定的文件时,shell会通知用户
MAIL_WARNING   如果设置了该变量,当bash发现用于检查邮件的文件在上次检查后又被访问了,将打印消息"The mail in [filename where mail is stored] has been read"
MAILCHECK      这个参数定义shell将隔多长时间(以秒为单位)检查一次由参数MAILPATH或MAILFILE指定的文件,看看是否有邮件到达,缺省值是6000秒(10分钟),如果将它设为0,shell每次输出主提示符之前都会去检查邮件
MAILPATH       由冒号分隔的文件名列表.如果设置了这个参数,只要有邮件到达任何一个由它指定的文件,shell都会通知用户,每个文件名后面都可以跟一个百分号和一条消息,当文件修改时间发生变化时,shell会打印这条消息.缺省的消息是:You have mail
OLDPWD         前一个工作目录
OPTARG         上一个由getopts内置命令处理的选项参数的值
OPTERR         如果设置成1,显示来自getopts内置命令的错误信息
OPTIND         下一个由getopts内置命令处理的参数的序号
OSTYPE         自动设置成一个串,该串描述正在运行bash的操作系统.缺省值由系统决定
PATH           命令搜索路径.由冒号分隔的目录列表,shell用来搜索命令,缺省路径系统决定,由安装bash的管理员设置.常见值:/usr/gnu/bin:/usr/local/bin:/usr/ucb:/usr/bin:/usr/bin:
PIPESTATUS     一个数组,包含一列最近在管道上执行前台作业的进程退出状态值
PPID           父进程的进程ID
PROMPT_COMMAND 赋给这个变量的命令将在主提示符显示前执行
PS1            主提示符串,缺省值是$
PS2            次提示符串,缺省值是>
PS3            与select命令一起使用的选择提示符串,缺省值是#>
PS4            当开启追踪时使用的调试提示符串,缺省值是+,追踪可以用set -x开启
PWD            当前工作目录;由cd设置
RANDOM         每次引用该变量,就产生一个随机正数.随机数序列可以通过给RANDOM赋值来初始化.如果RANDOM被复位,即使随后再设置,它也失去特定的属性
REPLY          当没有给read提供参数时设置
SECONDS        每次SECONDS被引用,将返回调用shell以来的秒数.如果给SECONDS赋一个值,以后引用返回的值将是赋值以来的秒数上所赋的值.如果SECONDS被复位,即使随后再设置,它也将失去特定的属性
SHELL          当调用shell时,它扫描环境寻找该名字,shell给PATH,PS1,PS2,MAILCHECK和IFS设置缺省值.HOME和MAIL由login(1)设置
SHELLOPTS      包含一列开启的shell选项,比如braceexpand,hashall,monitor等
SHLVL          每启动一个bash实例时将其加1
TMOUT          指定退出前等待输入的秒数
UID            展开为当前用户的用户ID,在shell启动时初始化复位变量.只要不被设为只读,局部变量和环境变量都可以被unset命令复位
printf命令的格式说明符
\"             双引号
\0NNN          一个八进制字符,这里NNN代表0到3位
\\             反斜杠
\a             报警或蜂鸣
\b             退格
\c             不产生更多的输出
\f             换页
\n             换行
\r             回车
\t             水平制表符
\v             垂直制表符
\xNNN          十六进制字符,这里NNN是1到3位
%%             一个%
%b             参数用\转义成一个串

113) 变量修饰符
${variable:-word}         如果变量variable已被设置且非空,则代入它的值;否则,代入word
${variable:=word}         已被设置且值非空,就代入它的值;否则,将variable的值设为word.始终代入variable的值.位置参数不能用这种方式赋值
${variable:+word}         如果变量variable已被设置且值非空,代入word;否则,什么都不代入(代入空值)
${variable:?word}         如果变量variable已被设置且值非空,就代入它的值;否则,打印word并且从shell退出.如果省略了word,就会打印信息:parameter null or not set
${variable:offset}        获得变量variable值中从offset开始的子串,偏移量为从0到串的末尾
${variable:offset:length} 获得变量variable值中从offset开始,长度为length的子串

114) 变量扩展子串
${变量%模式}  将变量值的尾部与模式进行最小匹配,并将匹配到的部分删除
${变量%%模式} 将变量值的尾部与模式进行最大匹配,并将匹配到的部分删除
${变量#模式}  将变量值的头部与模式进行最小匹配,并将匹配到的部分删除
${变量##模式} 将变量值的头部与模式进行最大匹配,并将匹配到的部分删除
${#变量}      替换为变量中的字符个数.如果是*或@,长度则是位置参量的个数

115) 位置参量
$0    指代当前shell脚本的名字
$0~$9 代表第1个到第9个位置参量
${10} 第10个位置参量
$#    其值为位置参量的个数
$*    其值为所有的位置参量
$@    除了被双引号引用的情况,含义与$*相同
"$*"  其值为"$1 $2 $3"
"$@"  其值为"$1""$2""$3"

116) 专用变量
$ 当前shell的PID
- 当前的sh选项设置
? 执行的上一个命令的退出值
! 最后一个进入后台的作业的PID

117) 重定向
<          重定向输入
>          重定向输出
>>         追加输出
2>         重定向标准错误输出
&>         重定向标准输出和标准错误输出
>&         重定向标准输出和标准错误输出(首选方式)
2>&1       将标准错误输出重定向到输出的去处
1>&2       将输出重定向到标准错误输出的去处
>|         重定向输出时忽略noclobber
<>filename 如果是一个设备文件(来自/dev),使用文件作为标准输入和标准输出

118) exec命令
exec ls        ls将顶替shell运行,ls运行结束后,它启动时所在的shell不会返回运行状态
exec<filea     打开文件filea,用于读标准输入
exec>filex     打开文件filex,用于写标准输出
exec 3<datfile 打开文件datfile,将其作为文件描述符3,用于读取输入
sort<&3        将文件datfile排序
exec 4>newfile 打开文件newfile,将其作为文件描述符4,用于写输出
ls >&4         将ls的输出结果重定向到newfile
exec 5<&4      使文件描述符5成为文件描述符4的一个副本
exec 3<&-      关闭文件描述符3

119) bash2.x shell调用选项
-c string      从string中读取命令.string后的任何参数都赋给位置参量,从$0开始
-D             一列前面有一个$的双引号串打印到标准输出.当前locale不是C或POSIX时,这些串服从于语言转换.-n选项是隐式的;不执行任何命令
-i             Shell实在交互模式.忽略TERM,QUIT和INTERRUPT
-s             从标准输入读取命令并且允许设置位置参量
-r             启动一个受限制的shell
--             用信号通知选项的结束并禁止更多的选项处理.--或-后的任何参数被当作文件名和参数
--dump-strings 同-D
--help         显示一个内置命令的使用信息并退出
--login        使bash作为一个登录shell被调用
--noediting    当bash交互式运行时,不使用readline库
--noprofile    bash启动时不读初始化文件:/etc/profile,~/.bash_profile,~/.bash_login或~/.profile
--norc         对于交互式shell,bash不会读~/.bashrc文件.如果运行的shell是sh,则默认是打开的
--posix        改变bash的行为以符合POSIX 1003.2标准,否则不改变
--quiet        缺省在shell启动时不显示任何消息
--rcfile file  如果bash是交互式的,使用该初始化文件代替~/.bashrc
--restricted   启动一个受限制的shell
--verbose      打开verbose;和-v一样
--version      显示该bash shell的版本信息并退出

120) 内置set命令选项
选项名               快捷开关 含义
allexport            -a       从这个选项被设置就自动标明要输出的新变量或修改过的变量,直至选项关闭
braceexpand          -B       打开花括号扩展,是一个缺省设置
emacs                         使用emacs内置编辑器进行命令行编辑,是一个缺省设置
errexit              -e       当一个命令返回一个非0退出状态时,退出.读取初始化文件时不设置
histexpand           -H       当执行历史替换时打开!和!!,是一个缺省设置
history                       打开命令行历史;缺省时为开
ignoreeof                     禁止用EOF(Control-D)键退出shell;必须键入exit才能退出.和设置shell变量IGNOREEOF=10一样
keyword              -k       为命令把keyword变量加到环境中
interactive-comments          对于交互式shell,#用来将后面的文本作为注释
monitor              -m       允许作业控制
noclobber            -C       防止文件在重定向时被重写
noexec               -n       读命令,但不执行.用来检查脚本的语法.交互式运行时不设置
noglob               -d       Disables pathname expansion (i.e., turns off wildcards).
notify               -b       Notifies user when background job finishes.
nounset              -u       Displays an error when expanding a variable that has not been set.
onecmd               -t       Exits after reading and executing one command.
physical             -P       If set, does not follow symbolic links when typing cd or pwd. The physical directory is used instead.
posix                         Shell behavior is changed if the default operation doesn't match the POSIX standard.
privileged           -p       When set, the shell does not read the .profile or ENV file and shell functions are not inherited from the environment; automatically set for setuid scripts.
posix                         Changes the default behavior to POSIX 1003.2.
verbose              -v       Turns on the verbose mode for debugging.
vi                            For command-line editing, uses the vi built-in editor.
xtrace               -x       Turns on the echo mode for debugging.

121) The shopt Command Options
cdable_vars          If an argument to the cd built-in command is not a directory, it is assumed to be the name of a variable whose value is the directory to change to.
cdspell              Corrects minor errors in the spelling of a directory name in a cd command. The errors checked for are transposed characters, a missing character, and a character too many. If a correction is found, the corrected path is printed, and the command proceeds. Only used by interactive shells.
checkhash            Bash checks that a command found in the hash table exists before trying to execute it. If a hashed command no longer exists, a normal path search is performed.
checkwinsize         Bash checks the window size after each command and, if necessary, updates the values of LINES and COLUMNS.
cmdhist              Bash attempts to save all lines of a multiple-line command in the same history entry. This allows easy re-editing of multiline commands.
dotglob              Bash includes filenames beginning with a dot (.) in the results of filename expansion.
execfail             A noninteractive shell will not exit if it cannot execute the file specified as an argument to the exec built-in command. An interactive shell does not exit if exec fails.
expand_aliases       Aliases are expanded. Enabled by default.
extglob              The extended pattern matching features (regular expression metacharacters derived from Korn shell for filename expansion) are enabled.
histappend           The history list is appended to the file named by the value of the HISTFILE variable when the shell exits, rather than overwriting the file.
histreedit           If readline is being used, a user is given the opportunity to re-edit a failed history substitution.
histverify           If set, and readline is being used, the results of history substitution are not immediately passed to the shell parser. Instead, the resulting line is loaded into the readline editing buffer, allowing further modification.
hostcomplete         If set, and readline is being used, bash will attempt to perform hostname completion when a word containing an @ is being completed. Enabled by default.
huponexit            If set, bash will send SIGHUP (hangup signal) to all jobs when an interactive login shell exits.
interactive_comments Allows a word beginning with # to cause that word and all remaining characters on that line to be ignored in an interactive shell. Enabled by default.
lithist              If enabled, and the cmdhist option is enabled, multiline commands are saved to the history with embedded newlines rather than using semicolon separators where possible.
mailwarn             If set, and a file that bash is checking for mail has been accessed since the last time it was checked, the message The mail in mailfile has been read is displayed.
nocaseglob           If set, bash matches filenames in a case-insensitive fashion when performing filename expansion.
nullglob             If set, bash allows filename patterns that match no files to expand to a null string, rather than themselves.
promptvars           If set, prompt strings undergo variable and parameter expansion after being expanded. Enabled by default.
restricted_shell     The shell sets this option if it is started in restricted mode. The value may not be changed. This is not reset when the startup files are executed, allowing the startup files to discover whether or not a shell is restricted.
shift_verbose        If this is set, the shift built-in prints an error message when the shift count exceeds the number of positional parameters.
sourcepath           If set, the source built-in uses the value of PATH to find the directory containing the file supplied as an argument. Enabled by default.
source               A synonym for dot (.).

122) Built-In Commands
.                               Executes program in context of current process; same as source.
.                               file The dot command reads and executes command from file.
:                               Do-nothing command; returns 0 exit status.
alias                           Lists and creates "nicknames" for existing commands.
bg                              Puts a job in the background.
bind                            Displays current key and function bindings, or binds keys to a readline function or macro.[a]
break                           Breaks out of the innermost loop.
break [n]                       See "The break Command" on page 919.
builtin [sh–builtin [args]]    Runs a shell built-in, passing it args, and returning 0 exit status. Useful if a function and built-in have the same name.[a]
cd [arg] Changes the directory  to home if no arg or to value of arg.
command command [arg]           Runs a command even if a function has the same name (i.e., bypasses function lookup).[a]
continue [n]                    See "The continue Command" on page 920.
declare [var]                   Displays all variables or declares variables with optional attributes.[a]
dirs                            Displays a list of currently remembered directories resulting from pushd.
disown                          Removes an active job from the job table.
echo [args]                     Displays args terminated with a newline.
enable                          Enables and disables shell built-in commands.[a]
eval [args]                     Reads args as input to the shell and executes the resulting command(s).
exec command                    Runs command in place of this shell.
exit [n]                        Exits the shell with status n.
export [var]                    Makes var known to subshells.
fc                              History's fix command for editing history commands.
fg                              Puts background job into foreground.
getopts                         Parses and processes command-line options.
hash                            Controls the internal hash table for quicker searches for commands.
help [command]                  Displays helpful info about built-in commands and, if command is specified, detailed help about that built-in command.[a]
history                         Displays the history list with line numbers.
jobs                            Lists jobs put in the background.
kill [–signal process]         Sends the signal to the PID number or job number of the process. Type kill –l for a list of signals.
let                             Used for evaluating arithmetic expressions and assigning results of arithmetic calculations to variables.
local                           Used in functions to restrict the scope of variables to the function.
logout                          Exits the login shell.
popd                            Removes entries from the directory stack.
pushd                           Adds entries to the directory stack.
pwd                             Prints present working directory.
read [var]                      Reads line from standard input into variable var.
readonly [var]                  Makes variable var read-only. Cannot be reset.
return [n]                      Returns from a function where n is the exit value given to the return.
set                             Sets options and positional parameters. See Table 14.2 on page 875.
shift [n]                       Shifts positional parameters to the left n times.
stop pid                        Halts execution of the process number PID.
suspend                         Stops execution of the current shell (but not if a login shell).
test                            Checks file types and evaluates conditional expressions.
times                           Prints accumulated user and system times for processes run from this shell.
trap [arg] [n]                  When shell receives signal n (0, 1, 2, or 15), executes arg.
type [command]                  Prints the type of command (e.g., pwd is a built-in shell command).
typeset                         Same as declare. Sets variables and gives them attributes.
ulimit                          Displays and sets process resource limits.
umask [octal digits]            Sets user file creation mode mask for owner, group, and others.
unalias                         Unsets aliases.
unset [name]                    Unsets value of variable or function.
wait [pid#n]                    Waits for background process with PID number n and reports termination status.

123)The read Command
read answer         Reads a line from standard input and assigns it to the variable answer
read first last     Reads a line from standard input to the first whitespace or newline, putting the first word typed into the variable first and the rest of the line into the variable last
read                Reads a line from standard input and assigns it to the built-in variable REPLY (Bash and Korn shell)
read –a arrayname  Reads a list of words into an array called arrayname [a]
read –e            Used in interactive shells with command-line editing in effect; for example, if editor is vi, vi commands can be used on the input line[a]
read –p prompt     Prints a prompt, waits for input, and stores input in REPLY variable[a]
read –r line       Allows the input to contain a backslash[a]

124) Positional Parameters
$0           References the name of the script
$#           Holds the value of the number of positional parameters
$*           Lists all of the positional parameters
$@           Means the same as $*, except when enclosed in double quotes
"$*"         Expands to a single argument (e.g., "$1 $2 $3")
"$@"         Expands to separate arguments (e.g., "$1" "$2" "$3")
$1 ... ${10} References individual positional parameters

125) The test Command Operators
String Test
[ string1 = string2 ]       String1 is equal to String2 (space surrounding = required).
[ string1==string2 ]        (Can be used instead of the single = sign on bash versions 2.x.)
[ string1 != string2 ]      String1 is not equal to String2 (space surrounding != required).
[ string ]                  String is not null.
[ –z string ]              Length of string is zero.
[ –n string ]              Length of string is nonzero.
[ –l string ]              Length of string (number of characters).

                            EXAMPLE
                            test –n $word      or     [ –n $word ]
                            test tom = sue      or     [ tom = sue ]

Logical Test
[ string1 –a string1 ]     Both string1 and string2 are true.
[ string1 –o string2 ]     Either string1 or string2 is true.
[ ! string1 ]               Not a string1 match.

Logical Test (Compound Test)
[[ pattern1 && pattern2 ]]  Both pattern1 and pattern2 are true.
[[ pattern1 || pattern2 ]]  Either pattern1 or pattern2 is true.
[[ ! pattern ]]             Not a pattern match.

Integer Test
[ int1 –eq int2 ]          Int1 is equal to int2.
[ int1 –ne int2 ]          Int1 is not equal to int2.
[ int1 –gt int2 ]          Int1 is greater than int2.
[ int1 –ge int2 ]          Int1 is greater than or equal to int2.
[ int1 –lt int2 ]          Int1 is less than int2.
[ int1 –le int2 ]          Int1 is less than or equal to int2.

Binary Operators for File Testing
[ file1 –nt file2 ]        True if file1 is newer than file2 (according to modification date).
[ file1 –ot file2 ]        True if file1 is older than file2.
[ file1 –ef file2 ]        True if file1and file2 have the same device or inode numbers.

126) The let Command Operators
–  Unary minus
+   Unary plus
!   Logical NOT
~   Bitwise NOT (negation)
*   Multiply
/   Divide
%   Remainder
+   Add
–  Subtract

let Operators Not Implemented Prior to bash 2.x
<<                                  Bitwise left shift
>>                                  Bitwise right shift
<= >= < >                           Comparison operators
== !=                               Equal to and not equal to
&                                   Bitwise AND
^                                   Bitwise exclusive OR
|                                   Bitwise OR
&&                                  Logical AND
||                                  Logical OR
= *= /= %= += –= <<= >>= &= ^= |=  Assignment and shortcut assignment

127) File-Testing Operators
-b filename    Block special file
-c filename    Character special file
-d filename    Directory existence
-e filename    File existence
-f filename    Regular file existence and not a directory
-G filename    True if file exists and is owned by the effective group ID
-g filename    Set-group-ID is set
-k filename    Sticky bit is set
-L filename    File is a symbolic link
-p filename    File is a named pipe
-O filename    File exists and is owned by the effective user ID
-r filename    File is readable
-S filename    File is a socket
-s filename    File is nonzero size
-t fd          True if fd (file descriptor) is opened on a terminal
-u filename    Set-user-ID bit is set
-w filename    File is writable
-x filename    File is executable

128) Signal Numbers and Signals
1) SIGHUP   9)  SIGKILL     17) SIGCHLD     25) SIGXFSZ
2) SIGINT   10) SIGUSR1     18) SIGCONT     26) SIGVTALRM
3) SIGQUIT  11) SIGSEGV     19) SIGSTOP     27) SIGPROF
4) SIGILL   12) SIGUSR2     20) SIGTSTP     28) SIGWINCH
5) SIGTRAP  13) SIGPIPE     21) SIGTTIN     29) SIGIO
6) SIGABRT  14) SIGALRM     22) SIGTTOU     30) SIGPWR
7) SIGBUS   15) SIGTERM     23) SIGURG
8) SIGFPE   16) SIGSTKFLT   24) SIGXCPU

129) Debugging Options
bash –x scriptname     Echo option         Displays each line of script after variable substitutions and before execution.
bash –v scriptname     Verbose option      Displays each line of script before execution, just as you typed it.
bash –n scriptname     Noexec option       Interprets but does not execute commands.
set –x                 Turns on echo       Traces execution in a script.
set +x                  Turns off echo      Turns off tracing.

No comments:

Post a Comment