shell编程

#!/bin/bash。这是一个典型的Bash脚本的开头,指定了脚本要使用的解释器,即Bash。

1
2
3
4
5
6
7
8
#!/bin/bash

# Author : Forrest

pwd
ls
mkdir testDir

添加执行权限

1
chmod +x filename

用read命令来获取keyboard的输入,并将输入结果赋值给变量 The following script uses the read command which takes the input from the keyboard and assigns it as the value of the variable PERSON and finally prints it on STDOUT.

用$符号来获取变量的值 To access the value stored in a variable, prefix its name with the dollar sign ($)

1
2
3
4
5
6
7
8
#!/bin/bash

# Author : Forrest

echo "what is your name"
read name
echo "hello ,$name"
echo "done"

Using Variables

Defining Variables

1
2
3
4
variable_name=variable_value

NAME="Forrest"
NUMBER=123

Accessing values

1
2
NAME="Forrest"
echo $NAME

Read-only Variables

1
2
3
NAME="Forrest"
readonly NAME
NAME="another name"

err:

1
-bash: NAME: readonly variable

readonly 变量的只读属性是永久性的,不能在脚本中或shell会话中被修改或取消。Unsetting Variables

1
unset vaiable_name

Special Variables

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
echo "what is your name"
read name
echo "hello ,$name"
# special variable
echo "current script pid: $$"
echo "filename : $0"
echo "first parameter: $1"
echo "second parameter :$2"
echo "quoted values $@"
echo "quoted values $*"
echo "total number of quoted $#"

for TOKEN in $*
do
echo $TOKEN
done

echo "exit status $?"

Using Shell Arrays

查看shell是 ksh 还是bash

1
echo $SHELL

image-20230830201146754

1
2
3
4
5
6
7
8
#!/bin/bash

Arr[0]="0"
Arr[1]="1"
Arr[2]="2"
echo "first item ${Arr[0]}"
echo "first method ${Arr[*]}"
echo "second method ${Arr[@]}"

Decision Making

if else

1
2
3
4
5
6
7
8
a=10
b=20
if [$a==$b]
then
echo "a equlas b"
else
echo "a not equals b"
fi

if elseif

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/bash

a=10
b=20
if [ $a == $b ]
then
echo "a equals b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
fi

case .. esac

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash

option="${1}"

case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR=${2}
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0} `:usage :[-f file] | [-d directory]"
exit 1
;;
esac

IO Redirection

Output

who command which redirects the complete output of the command in the users file.

1
who > users
1
echo line 1 >  users
1
echo line 2 >> uses

eval

eval 是一个在Shell脚本中用于执行字符串作为命令的特殊命令。它会将传递给它的字符串作为Shell命令进行解释和执行。eval 常用于动态生成和执行命令,可以将字符串中的变量、表达式和命令进行求值和执行。

1
2
3
4
5
6
x=5
y=3
operation="x+y"
result=$(eval "echo \$(( $operation ))")
echo "Result: $result"

使用多行注释

你可以使用 :<<COMMENTCOMMENT 来实现多行注释。例如:

1
2
3
4
5
6
7
bashCopy code:<<COMMENT
这是多行注释的内容。
可以有多行。
这里可以写注释。
COMMENT

echo "这是实际的代码。"

在上面的示例中,冒号 : 后面的 <<COMMENT 表示将会读取从 COMMENT 开始的多行文本,这部分文本会被当作注释而被忽略。当Shell执行脚本时,它会跳过这些注释内容。

权限问题

chmod

parameter : + - =

+表示全局(User group other)添加某些权限

-表示全局(User Group Other) 删除某些权限

=表示设置(User | Group | Other)的权限是什么

1
chmod o+wx testfile
1
chmod 743 testfile

shell编程
http://example.com/2023/09/02/shell编程/
作者
Forrest
发布于
2023年9月2日
许可协议