【Linux/Shell/Git】Shell基础

本文详细介绍了Shell脚本的基础知识,包括echo命令的使用、if语句、循环结构等,并解答了常见问题,如如何使脚本可执行、标准输出与错误输出的重定向方法,以及解释了 $? 标记的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考 https://linux.cn/article-5311-1.html

1. Shell脚本中的“echo”

用于字符串的输出

echo  # echo后啥都不加 输出空行
echo "hello"(或echo hello)  # hello
echo \"hello\"  # "hello"

输出变量的值时,必须使用“$”

x=10
echo x  # x
echo $x # 10

2. Shell脚本中的if语句

if [ 条件 ]  (中括号两边必须有空格!)
then
	....
else
	....
fi

例如,写个比较大小的脚本:

x=10
y=20
if [ x -gt y ] # 如果x >= y
then
	echo 1
else
	echo 0
fi

3. Shell脚本中的循环

for循环:

for i in 1 2 3 4 5
do
	echo $i
done

while 循环:

while [ 条件 ]
do
	....
done

break可以跳出当前层循环(如果循环嵌套,需跳出多次)
continue继续下一次循环。

4. Q&A

Shell脚本是什么、它是必需的吗?

一个Shell脚本是一个文本文件,包含一个或多个命令。作为系统管理员,我们经常需要使用多个命令来完成一项任务,我们可以添加这些所有命令在一个文本文件(Shell脚本)来完成这些日常工作任务。

如何将标准输出和错误输出同时重定向到同一位置?

这里有两个方法来实现:
方法一:

2>&1 (# ls /usr/share/doc > out.txt 2>&1 )

方法二:

&> (# ls /usr/share/doc &> out.txt )

shell脚本中“$?”标记的用途是什么?

在写一个shell脚本时,如果你想要检查前一命令是否执行成功,在if条件中使用“$?”可以来检查前一命令的结束状态。如果结束状态是0,说明前一个命令执行成功。如果结束状态不是0,说明命令执行失败。 简单的例子如下:

root@localhost:~# ls /usr/bin/shar
/usr/bin/shar
root@localhost:~# echo $?
0

如何使脚本可执行 ?

使用chmod命令:

chmod a+x myscript.sh

“#!/bin/bash”的作用 ?

#!/bin/bash是shell脚本的第一行,称为释伴(shebang)行。这里#符号叫做hash,而! 叫做 bang。它的意思是命令通过 /bin/bash 来执行。

Git中的rebase和merge

https://www.jianshu.com/p/4079284dd970

Git指令的Shell脚本,能够快速便捷地管理Git库,包括添加修改、提交修改、显示库状态、推送到远程库、从远程库更新到本地、版本恢复等操作。 使用方法: 1. 在Linux系统中,将本文件放在Git库目录下,利用Shell运行本文件; 2.在windows系统中,需下载安装与操作系统相对应的Git软件,并将本文件放在Git库目录下,双击即可运行。 运行示例: Please choose the first letter of options. [Add|Commit|Diff|Fetch|Exit|Help|Log|Push|User|Reset|Status]? h A: Add all changes to repository. C: Commit all changes to repository. D: Show differences between current version with HEAD->. E: Exit shell script. F: Fetch origin/master and merge. L: Show latest two-weeks logs of repository. P: Push commissions to origin/master. U: User command mode(Press ‘Enter’ to exit). R: Reset current version according version_id. S: Show status of repository. Please choose the first letter of options. [Add|Commit|Diff|Fetch|Exit|Help|Log|Push|User|Reset|Status]? s On branch master Your branch is up-to-date with 'origin/master'. Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) modified: Git.sh modified: PyNote/PyNote_2.md no changes added to commit (use "git add" and/or "git commit -a") Please choose the first letter of options. [Add|Commit|Diff|Fetch|Exit|Help|Log|Push|User|Reset|Status]? a On branch master Your branch is up-to-date with 'origin/master'. Changes to be committed: (use "git reset HEAD ..." to unstage) modified: Git.sh modified: PyNote/PyNote_2.md
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值