Shell Script Basics

文章摘要

Bpple-GPT

Shell Script Basics


参考:

开始第一个例子,先创建一个文件夹📂开始学习

root@cloud:~# mkdir shlearn
root@cloud:~# cd shlearn
root@cloud:~/shlearn# vim test.sh

root@cloud:~/shlearn# test.sh
test.sh: command not found

root@cloud:~/shlearn# ls
test.sh

root@cloud:~/shlearn# ./test.sh
-bash: ./test.sh: Permission denied

root@cloud:~/shlearn# chmod +x test.sh
root@cloud:~/shlearn# ./test.sh
hello world

这里有一点需要注意的是跟Windows-cmd一样:

注意,一定要写成./test.sh,而不是test.sh,运行其它二进制的程序也一样,直接写test.sh,linux系统会去 <span class="ne-text">PATH</span>里寻找有没有名称为test.sh的,

而只有Python,/bin, /sbin, /usr/bin,/usr/sbin等在PATH里,你的当前目录通常不在PATH里,所以写成test.sh是会找不到命令的,就会提示 <span class="ne-text">test.sh: command not found</span>

要用./test.sh告诉系统说,就执行当前目录下的 <span class="ne-text">./test.sh</span>

#另一种执行方式:
bash test.sh

基本语法

变量

root@cloud:~/shlearn# bx = 3366
bx: command not found
root@cloud:~/shlearn# $bx=3366
=3366: command not found
root@cloud:~/shlearn# $ bx=3366
$: command not found

#正确方式
root@cloud:~/shlearn# bx=3366
root@cloud:~/shlearn# echo bx
bx

单引号和双引号:

双引号能够识别变量,双引号能够实现转义

root@cloud:~# name=bx
root@cloud:~# echo '$name'
$name
root@cloud:~# echo "$name"
bx

变量删除

unset 变量名

可以利用以下两个命令去查看变量 <span class="ne-text">set</span> <span class="ne-text">env</span>

set命令可以查看所有变量,而env命令只能查看环境变量。

#!/bin/bash
$name=bx
$age=18
$num=17
echo "hello world"
echo "shell脚本本身的名字: $0"
echo "传给shell的第一个参数: $1"
echo "传给shell的第二个参数: $2"
echo "所有:$@"
echo "个数:$#"
root@cloud:~/shlearn# ./test.sh 1 2 3 4
./test.sh: line 2: =bx: command not found
./test.sh: line 3: =18: command not found
./test.sh: line 4: =17: command not found
hello world
shell脚本本身的名字: ./test.sh
传给shell的第一个参数: 1
传给shell的第二个参数: 2
所有:1 2 3 4
个数:4

几个参数,例子:

#!/bin/bash
for i in "$*"
do
    echo "The parameters is: $i"
done

x=1
for y in "$@"
do
    echo "The parameter$x is: $y"
    x=$((x + 1))
done
 ~  vim demo2.sh                                       
 ~  bash demo2.sh 1 2 5 9 3 4                  
The parameters is: 1 2 5 9 3 4
The parameter1 is: 1
The parameter2 is: 2
The parameter3 is: 5
The parameter4 is: 9
The parameter5 is: 3
The parameter6 is: 4

预定义参数:

$? 最后一次执行的命令的返回状态。如果这个变量的值为0,证明上一个命令正确执行;如果这个变量的值为非О(具体是哪个数,由命令自己来决定),则证明上一个命令执行不正确了。
$$ 当前进程的进程号(PID)
$! 后台运行的最后一个进程的进程号(PID)

反引号:(``)

执行命令 (<span class="ne-text">$()</span>也可以)

root@cloud:~# echo ls
ls
root@cloud:~# echo `ls`
shlearn snap
root@cloud:~# echo $(ls)
shlearn snap

注释

  • **单行注释 **<span class="ne-text">#</span>
  • **多行注释 **<span class="ne-text">#</span>
    没有专门的语句,只能一行一行的添加

用键盘敲击出的不只是字符,更是一段段生活的剪影、一个个心底的梦想。希望我的文字能像一束光,在您阅读的瞬间,照亮某个角落,带来一丝温暖与共鸣。

BX33661

isfp 探险家

站长

不具版权性
不具时效性

文章内容不具时效性。若文章内容有错误之处,请您批评指正。


目录

欢迎来到Bpple的站点,为您导航全站动态

65 文章数
20 分类数
44 评论数
15标签数
最近评论
bpple

bpple


一切顺利

fetain

fetain


good luck

bx

bx


good luck

热门文章

Emoji收集

2024-11-01

550
Hello Halo

2024-10-30

532
本地部署LLM

2024-08-22

511
Uptime Kuma

2024-11-29

507
241

访问统计