Shell 脚本攻略,第一章学习笔记

Introduction


A shell script is a text file that typically begins with a shebang, as follows:

#!/bin/bash

shebang : 对于什么Linux环境的脚本语言,脚本开始于特殊行,就叫 shebang。if a script is run as a command-line argument for sh, the shebang in the script is of no use. (exp: sh script.sh)

通过将文件改为可执行文件,则可以独立执行脚本文件。 

$chmod a+x script.sh
$./script.sh   ./represents the current directory

当终端打开时,它首先会执行一系列命令来定义各种配置,文本,颜色,等。 这些命令来自于.bashrc, 它位于用户“home”目录。

在bash中,通过分号或者另起一行来界定两个脚本语句。

$ cmd1 ; cmd2

$ cmd1
$ cmd2

Printing in the terminal


Printing 可以通过很多种方式执行,

echo :

特别注意:

$ echo "cannot include exclamation - ! within double quotes"

这个命令行会返回 : bash: !: event not found error. 

所以如果想要打印 !, 不要再双引号内使用,否则可能会转义!,以特殊字符转义字符(\)作为前缀。

$ echo Hello world !
$ echo 'Hello world !'
$ echo "Hello world \!" #使用特殊转义字符作为前缀\

printf:

There's more...

默认情况下,echo 在输出文本末尾换行,通过使用-n 可以避免。 echo 还可以接受双引导字符串中的转移序列为参数。

echo -e "1\t2\t3"
123

Printing colored output

字体颜色: reset=0 , black=30, red=31, green=32, yellow=33, blue=34, magenta=35, cyan=36, white=37

echo -e "\e[1;31m This is red text \e[0m"

\e[1;31 是转义字符串,设置字体为红色,\e[0 为颜色复位。

背景板颜色: reset=0, black=40, red=41, green=42, yellow=43, blue=44, magenta=45, cyan=46, white=47 

echo -e "\e[1;42m Green Background \e[0m"

Playing with variables and environment variables

脚本语言一般不需要声明变量类型。 可以直接被赋值。 在bash中,每一个变量的值都是字符串,不论你是否在赋值时使用引号,他们都被当做字符串存储。 

几个被shell环境和系统环境使用的特殊的变量,存储一个特数值,叫做环境变量。

Gettting ready

变量使用常用命名结构。当一个app执行时,它会传送一系列变量(环境变量)。 执行 env 命令可以查看相关的terminal 环境变量。

对于进程任何进程,在运行时间内,可以通过以下命令查看环境变量:

cat /proc/$PID/environ

PID 是相关程序的运行ID。

exp:假设当前程序正在运行 gedit, 可是使用pgrep 获得程序ID:

$pgrep gedit
12501

然后通过运行下面命令获得相关的环境变量:

$cat /proc/12501/environ
GDM_KEYBOARD_LAYOUT=usGNOME_KEYRING_PID=1560USER=s1ynuxHOME=/home/slynux

$cat /proc/12501/environ | tr '\0' '\n'

How to do it...

var=value

如果value中存在白色空格(any white space characters)(like a space), 需要使用单引号或双引号括起来。

Note: var = value 和var=value 是不同的。使用var =value代替var=value 是一个常见的错误。 后者是赋值操作,而前者是等式操作。

打印变量值

var="value" #Assignment of value of variable var.

echo $var
Or:
echo ${var}

output : 
value

同时也可以在双引号内引用变量,打印变量值

#!/bin/bash
#Filename : variables.sh
fruit=apple
count=5
echo "We have $count ${fruit}(s)"

output is as follows:
We have 5 apple(s)

Finding length of string

For example:
var=12345678901234567890
echo ${#var}
20

UID是一个重要的环境变量,用于检查当前脚本是 root user 还是 常规用户。

if [ $UID -ne 0]; then
echo Non root user. Please run as root.
else 
echo "Root user"
fi

##The UID for the root user is 0.

修改Bash 提示字符串(username@hostname:~$)

使用PS1 环境变量,修改提示字符串。默认的提示字符串在~/.bashrc 文件中

我们可以列出用于设置PS1变量的行,如下所示

$ cat ~/.bashrc | grep PS1
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '

设置用户自定义提示字符串:
slynux@localhost: ~$ PS1="PROMPT>"
PROMPT> Type commands here # Prompt string changed.

使用colored text 使命令行变色。

猜你喜欢

转载自blog.csdn.net/qq_32404185/article/details/89021422