shell tips

时间:2022-05-19 19:44:09

-2、获取本机eth0的ip地址

ifconfig eth0 | grep inet | grep -v inet6 | awk '{print $2}' | tr -d "addr:"

  

-1、按指定的字符串截取

${variable#*string} 从左向右截取第一个string后的字符串

${variable##*string}从左向右截取最后一个string后的字符串

${variable%string*}从右向左截取第一个string后的字符串

${variable%%string*}从右向左截取最后一个string之后的字符串

0、判断某个命令是否安装,可调用如下函数

installed () {
command -v "$1" >/dev/null 2>&1
}

  

1、shopt 命令可以设置shell的可选参数

shopt [-psu] [optname...]

-s  开启某个选项

-u  关闭某个选项

-p  列出所有可设置的选项

其中开启extglob选项,shell将启用模式匹配

2、eval能够执行字符串中的命令,例子如下:

monster@monster-Z:~/TEST/sh$ command="pwd"
monster@monster-Z:~/TEST/sh$ eval $command
/home/monster/TEST/sh

  

3、unset用于删除变量

4、IFS变量为分隔符设置,默认为' '。当然,我们可以对它进行修改,如下所示:

IFS: a list of characters that separate fields; used when the shell splits words as part of expansion

monster@monster-Z:~$ NAME=(A B C D)
monster@monster-Z:~$ echo "${NAME[*]}"
A B C D
monster@monster-Z:~$ IFS='|'
monster@monster-Z:~$ echo "${NAME[*]}"
A|B|C|D

  

5、如果在执行脚本的时候不想启动一个子shell,那就使用source命令:`source script_name.sh`或者用`. script_name.sh`

这样脚本就不用执行权限,脚本的命令都在当前shell的上下文中执行,所以脚本对环境变量的改变在脚本执行结束之后依然是可见的

6、set 调试选项:

"set -f " 或者"set -o noglob" 表示禁止用正则表达式匹配

"set -v " 或者"set -o verbose"表示执行命令时,连带着输出命令

"set -x " 或者"set -o xtrace"表示在执行命令前输出命令,以便进行调试

同时,这些命令还可以在脚本中设置,通过在脚本的第一行添加想要加入的选项,例如:#!/bin/bash -xv

monster@monster:~/TEST/sh$ set -v
monster@monster:~/TEST/sh$ ls
ls
hello.sh test.sh
monster@monster:~/TEST/sh$ set -f
set -f
monster@monster:~/TEST/sh$ ls *
ls *
ls: cannot access *: No such file or directory
monster@monster:~/TEST/sh$

  

7、shell启动时读取的配置文件

一般shell在启动时都会先读取/etc/profile,它会设置一些变量,例如:PATH, USER, HOSTNAME等等

但是因为系统中往往可能存在多种类型的shell,因此我们需要将bash相关的配置放在/etc/bashrc中,一般会被/etc/profile或一些用户的shell初始化文件所引用

~/.bash_profile中可以放置一些用户特有的配置,而~/.bash_login只在用户登录时执行,~/.profile只在~/.bash_profile和~/.bash_login都不存在的时候被读取,它对于其他shell也是可见的,因此要注意它的语法

~/.bashrc一般由non-login shell使用,其中定义了一些alias和某些程序需要用到的variables,一般在/etc/bashrc读取后读取

~/.bashrc通常在用户logout的时候执行,通常用于远程登录,用户退出时的清理工作

8、特殊的参数:

$* : Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable

$@:Expands to the positional parameters, starting from one.When the expansion occurs within double quotes, each parameter expands to a separate word

$#:Expands to the number of positional parameters in decimal

$?:Expands to the exit status of the most recently executed foreground pipeline

$-:A hyphen expands to the current option flags as specified upon invocation, by the set built-in command, or those set by the shell itself

$$:Expands to the process ID of the shell

$!:Expands to the process ID of the most recently executed background(asynchronous) command

$0:Expands to the name of the shell or shell script

9、引号问题:

A single quote may not occur between single quotes, even when preceded by a backslash

10、grep命令基本操作

grep的参数"-n"表示显示行号,"-v"表示匹配不包含字符串的行,"-c"输出匹配的行的数目

匹配以"root"开头的行:

monster@monster:~/TEST/sh$ grep ^root /etc/passwd
root:x:0:0:root:/root:/bin/bash

匹配以":"结尾的行:

monster@monster:~/TEST/sh$ grep :$ /etc/passwd
libuuid:x:100:101::/var/lib/libuuid:

匹配完整的单词,如下:

monster@monster:~/TEST/sh$ cat text.txt
ABCDE
ABC DE
monster@monster:~/TEST/sh$ grep -w ABC text.txt
ABC DE

匹配行中包含字符'A'或'D'的行:

monster@monster:~/TEST/sh$ cat text.txt
ABC
DEF
GHI
monster@monster:~/TEST/sh$ grep [AD] text.txt
ABC
DEF

匹配由五个字符组成的行,且以'c'开头,以'h'结尾

monster@monster:~/TEST/sh$ grep '^c...h$' /usr/share/dict/words
catch
cinch
*
cloth
coach
conch
couch
cough
crash
crush

  

11、if 语句的一些判断条件:

[ -f FILE ] :如果FILE为常规文件则为真

[ -a FILE ]:True if FILE exists.

[ -z STRING ]:True if the length of "STRING" is zero

[ -d STRING ]: 判断目录是否存在

[ -n STRING ] 或者 [ STRING ]:True if the length of "STRING" is non-zero.

[ STRING1 == STRING2 ]:True if the strings are equal."=" may be used instead of "==" for strict POSIX compliance

[ ARG1 OP ARG2 ]:“OP” is one of -eq, -ne, -lt , -le, -gt, or -ge.These arithmetic binary operator return true if "ARG1" is equal to, not equal to, less than, less than or equal to, great than or equal to "ARG2", respectively, "ARG1" and "ARG2" are integers.

[ ! EXPR],[ ( EXPR ) ]

[ EXPR1 -a EXPR2 ]:True if both EXPR1 and EXPR2 are true

[ EXPR1 -o EXPR2]:True if either EXPR1 or EXPR2 is true

12、Use { and } instead of ( and ) if you do not want Bash to fork a subshell

13、正则表达式也可以在if语句的判断语句中使用:

monster@monster:~$ gender="female"
monster@monster:~$ if [[ "$gender" == f* ]]
> then echo "Pleasure to meet you, Madame."; fi
Pleasure to meet you, Madame.

    

14、[] vs [[]]

Contrary to [, [[ prevents word splitting of variable values. So, if VAR="var with space", you do not need to double quote $VAR in the test-eventhough using quotes remains a good habit.

Also, [[ prevents pathname expansion, so literal strings with wildcards do not try to expand to filenames.

Using [[, == and != interpret strings to the right as shell glob patterns to be matched against the value to the left, for instance: [[ "value" = val* ]]

15、if语句的返回值是最后一条命令的执行结果,或者当没有一个条件语句符合的时候,返回true

16、if no argument is given to the exit command, the parent shell uses the current value of the $? variable

17、重定向相关:

(1)、If the standard output of a previous command is being piped to the standard input of the current command, then /proc/<current_process_ID>/fd/0 is updated to target the same anonymous pipe as /proc/<previsou_process_ID>/fd/1

(2)、If the standard output of the current command is being piped to the standard input of the next command,then /proc/<current_process_ID>/fd/1 is updated to target another anonymous pipe.

(3)、Redirection for the current command is processed from left to right

(4)、Redirection "N>&M" or "N<&M" after a command has the effect of creating or updating the symbolic link /proc/self/fd/N with the same target as the symbolic link /proc/self/fd/M

(5)、The redirection "N> file" and "N< file" have the effect of creating or updating the symbolic link /proc/self/fd/N with the target file

(6)、File descriptor closure "N>&-" has the effect of deleting the symbolic link /proc/self/fd/N

(7)、"&> FILE" is equivalent fo "> FILE 2>&1"

(8)、If /dev/fd is not available on a system, you'll have to find a way to bypass the problem.This can be done for instance using a hyphen(-) to indicate that a program should read from a pipe.

18、shift命令

This command takes one argument , a number. The positional parameters are shifted to the left by this number N.The positional parameters from N+1 to $# are renamed to variable names from $1 to $# - N+1.

If N is zero or greater than $#, the positional parameters are not changed and the command has no effect. If N is not present, it is assumed to be 1.The return status is zero unless N is greater than $# or less than zero; otherwise it is non-zero

19、declare命令

Using a declare statement, we can limit the value assignment to variables.

The following options are used to determine the type of data the variable can hold and to assign it attributes

-a:Variable is an array

-f:Use function names only

-i:The variable is to be treated as an integer; arithmetic evaluation is performed when the variable is assigned a value.

-p:Display the attributes and values of each variable.When -p is used, additional options are ignored.

-r:Make variables read-only,These variables cannot then be assigned values by subsequent assignment statements, nor can they be unset.

-t:Give each variable the trace attribute

-x:Mark each variable for export to subsequent commands via the environment

Using + instead of - turns off the attribute instead.

20、变量赋值

${VAR:-WORD} If VAR is not defined or null, the expansion of WORD is substituted; otherwise the value of VAR is substituted.

monster@monster-Z:~$ echo ${TEST:-test}
test
monster@monster-Z:~$ echo $TEST monster@monster-Z:~$ export TEST=a_string
monster@monster-Z:~$ echo ${TEST:-test}
a_string
monster@monster-Z:~$ echo ${TEST2:-$TEST}
a_string

${VAR:=WORD} if the hyphen (-) is replaced with the equal sign(=),the value is assigned to the parameter if it does not exist

monster@monster-Z:~$ TEST=a_string
monster@monster-Z:~$ echo ${TEST2:=$TEST}
a_string
monster@monster-Z:~$ echo $TEST2
a_string

${VAR:OFFSET:LENGTH}用于字符串截取

21、Replace parts of variable names

${VAR/PATTERN/STRING} or ${VAR//PATTERN/STRING}

The first form replaces only the first match, the second replaces all matches of PATTERN with STRING

monster@monster-Z:~/shell$ echo $STRING
thisisaverylongname
monster@monster-Z:~/shell$ echo ${STRING/name/string}
thisisaverylongstring

  

${VAR#WORD} and ${VAR##WORD} These constructs are used for deleting the pattern matching the expansion of WORD in VAR.WORD is expanded to produce a pattern just as in file name expansion.If the pattern matches the beginning of the expanded value of VAR, then the result of the expansion is the expanded value of VAR with the shortest matching pattern("#") or the longest matching pattern(indicated with "##")

if VAR is * or @, the pattern removal operation is applied to each positional parameter in turn, and expansion is the resultant list.

if VAR is an array variable subscribed with "*" or "@", the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

monster@monster-Z:~$ ARRAY=(one two one three one four)
monster@monster-Z:~$ echo ${ARRAY[*]#one}
two three four
monster@monster-Z:~$ echo ${ARRAY[*]#t}
one wo one hree one four
monster@monster-Z:~$ echo ${ARRAY[*]#t*}
one wo one hree one four
monster@monster-Z:~$ echo ${ARRAY[*]##t*}
one one one four

  

22、trap的执行问题

When Bash receives a signal for which a trap has been set while waiting for a command to complete, the trap will not be executed until the command completes.When Bash is waiting for an asychronous command via the wait built-in, the reception of a signal for which a trap has been set will cause the wait built-in to return immediately with an exit status greater than 128, immediately after which the trap is executed.