Shell脚本攻略读书笔记之三

Shell脚本攻略读书笔记之三

1.环境变量

Note that var = value and var=value are different. It is a usual mistake to write var = value instead of var=value. The later one is the assignment operation, whereas the earlier one is an equality operation
注意var = value 不同于var=value。这是一个容易犯的错误。var=value是一个赋值操作,而var = value是一个判断操作。

The export command is used to set the env variable.
export命令是用于设置环境变量的。

When given a command for execution,the shell automatically searches for the executable
in the list of directories in the PATH environment variable (directory paths are delimited by
the “:” character).
当给出一个可执行命令时,shell会自动从环境变量PATH中搜索可以执行的命令(这个PATH环境变量是由:分割文件路径)。

export PATH=$PATH:$JAVA_HOME/bin:$HBASE_HOME/bin

[root@server4 ~]# var=10
[root@localhost ~]# echo $var
10
[root@localhost ~]# echo '$var'
$var
[root@localhost ~]# echo "$var"
10

Get the length of a variable value using the following command:length=${#var}
使用命令:length=${#var}获取一个字符串的长度。

[root@server4 ~]# length=${#var}
[root@server4 ~]# echo $length
2

定义一个追加函数【暂不理解,需补充】

prepend() { [ -d "$2" ] && eval $1=\"$2':'\$$1\" && export $1; }
prepend() { [ -d "$2" ] && eval $1=\"$2\$\{$1:+':'\$$1\}\" && export $1 ;}

可以这样使用:
prepend PATH /opt/myapp/bin

2.eval命令

1.间接引用

eval命令首先会将命令进行替换,然后再执行命令。该命令使用于那些一次扫描无法实现功能的变量。该命令对变量进行两次扫描。需要进行两次扫描的变量称之为复杂变量。

[root@localhost ~]# set 11 22 33 44
[root@localhost ~]# echo $4
44
[root@localhost ~]# echo "\$$#"
$4
[root@localhost ~]# echo \$$#
$4
[root@localhost ~]# eval echo \$$#
44
2但是这个eval对于楼下的实现却没有成功【我也很不解,希望有人指点一下。谢谢】
[root@localhost ~]# myfile="cat HelloLinux.txt"
[root@localhost ~]# echo $myfile
cat HelloLinux.txt
[root@localhost ~]# `echo $myfile`
HelloLinux
/root
this is third line.added in 20180704
[root@localhost ~]# file="cat HelloLinux.txt"
[root@localhost ~]# echo $file
cat HelloLinux.txt
[root@localhost ~]# $myfile
HelloLinux
/root
this is third line.added in 20180704
[root@localhost ~]# $file
HelloLinux
/root
this is third line.added in 20180704

3.算术运算

obase指的是目标进制,ibase指的是源进制。

[root@server4 ~]# no=100
[root@server4 ~]# echo "obase=2;$no" |bc
1100100
[root@server4 ~]# no=1100100
[root@server4 ~]# echo "obase=10;ibase=2;$no" | bc
100
[root@server4 ~]# echo "sqrt(100)" | bc 
10
[root@server4 ~]# echo "10^10" | bc
10000000000
[root@server4 ~]# echo "10^2" | bc
100

4.file discriptors[文件描述符]

File descriptors are integers that are associated with file input and output.
0:stdin(standard input)
1:stdout(standard output)
2:stderr(standard error)

[root@server4 ~]# ls + > out.txt
ls: cannot access +: No such file or directory
[root@server4 ~]# echo $?
2
above command prints the stderr text to the screen rather than to a file(and because there is no stdout,out.txt will be empty)

in the following command,we redirect to a file and stdout to another file as follows:
[root@server4 ~]# ls + 2> out.txt

you can redirect stderr exclusively to a file and stdout to another file as follows.
cmd 

猜你喜欢

转载自blog.csdn.net/liu16659/article/details/81185586
今日推荐