Shell脚本攻略读书笔记之四

Shell脚本攻略读书笔记之四

[root@server4 ~]# cat test3.sh 
#!/bin/bash
cat <<EOF> log.txt
LOG FILE HEADER
This is a test log file
Function:System statistics
EOF
[root@server4 ~]# chmod a+x test3.sh
[root@server4 ~]# ./test3.sh 

[root@server4 ~]# ll
total 3
-rw-r--r--. 1 root root       67 Jul 25 11:24 log.txt
-rwxr-xr-x. 1 root root      102 Jul 25 11:22 test3.sh

[root@server4 ~]# cat log.txt 
LOG FILE HEADER
This is a test log file
Function:System statistics

[root@server4 ~]# cat test3.sh 
#!/bin/bash
cat <<EOF> log.txt
LOG FILE HEADER
This is a test log file
Function:System statistics
EOF

2.数组

[root@server4 ~]# array_var=(1 2 3 4 5 6)
[root@server4 ~]# echo $array_var[0]
1[0]
[root@server4 ~]# echo ${array_var[0]}
1
[root@server4 ~]# echo ${array_var[1]}
2
[root@server4 ~]# echo ${array_var[*]}
1 2 3 4 5 6
[root@server4 ~]# echo ${array_var[@]}
1 2 3 4 5 6
[root@server4 ~]# echo ${#array_var[@]}
6
[root@server4 ~]# echo ${#array_var[*]}
6

3.alias别名

空格坏事儿
[root@server4 ~]# alias hello = 'echo hello'
-bash: alias: hello: not found
-bash: alias: =: not found
-bash: alias: echo hello: not found
[root@server4 ~]# alias hello='echo hello'
[root@server4 ~]# hello
hello
[root@server4 ~]# hello
hello

查看当前用户下的别名:
[root@server4 ~]# cat ~/.bashrc 
# .bashrc

# User specific aliases and functions

alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'

# Source global definitions
if [ -f /etc/bashrc ]; then
    . /etc/bashrc
fi

取消hello的别名:
[root@server4 ~]# unalias hello
[root@server4 ~]# hello
bash: hello: command not found...

4.密码隐藏

[root@server4 ~]# cat test4.sh
#!/bin/bash
echo -e "Enter password:"
stty -echo  #这是什么???
read password
stty echo
echo
echo "The password your input is $password"

[root@server4 ~]# sh -x test4.sh
+ echo -e 'Enter password:'
Enter password:
+ stty -echo
+ read password
+ stty echo
+ echo

+ echo Password read.
Password read.
[root@server4 ~]# ./test4.sh
Enter password:

Password read.
[root@server4 ~]# vi test4.sh
[root@server4 ~]# ./test4.sh
Enter password:

The password your input is 123456

4.调试脚本

[root@server4 ~]# cat test7.sh 
#!/bin/bash
for i in {1..6}
do
 set -x
 echo $i
done
echo "script executed"
  • 调试脚本
[root@server4 ~]# sh -x test7.sh
+ for i in '{1..6}'
+ set -x
+ echo 1
1
+ set +x
+ echo 2
2
+ set +x
+ echo 3
3
+ set +x
+ echo 4
4
+ set +x
+ echo 5
5
+ set +x
+ echo 6
6
+ set +x
script executed
  • 执行脚本
[root@server4 ~]# ./test7.sh
+ echo 1
1
+ for i in '{1..6}'
+ set -x
+ echo 2
2
+ for i in '{1..6}'
+ set -x
+ echo 3
3
+ for i in '{1..6}'
+ set -x
+ echo 4
4
+ for i in '{1..6}'
+ set -x
+ echo 5
5
+ for i in '{1..6}'
+ set -x
+ echo 6
6
+ echo 'script executed'
script executed

猜你喜欢

转载自blog.csdn.net/liu16659/article/details/81414067