【MIT Missing Semester 2】Shell Tools

本文深入探讨了Shell脚本的基础,包括变量、函数、逻辑分支和通配符使用。讲解了如何利用shell工具如find、grep进行文件搜索和代码查找,并介绍了历史命令的快捷使用以及目录导航技巧。此外,还提供了实用的bash脚本示例,如自定义的mcd函数。文章最后提出了几个练习题,以巩固所学知识。

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


这节主要是bash作为脚本语言的一些基本用法,以及一些常见的功能强大的shell tools

Shell Scripting

可以用变量、循环、条件等更为复杂的方式,主要还是为了完成shell-related任务

变量

foo=bar  # 将字符串bar赋值给变量foo
echo fool #这个会把fool理解为字符串

注意单引号和双引号是不一样的,单引号里面是字面量,不会进行变量替换;而双引号会替换
在这里插入图片描述
注意foo=bar里是不能有空格的,如果有空格foo = bar会理解为执行一个叫foo的程序,然后有参数=和bar,一般空格在shell里是来分割参数的
还可以将输出转化为变量 --> $(CMD)

foo=$(pwd)
echo $foo
echo "we are in $(pwd)"

另外<(CMD)可以进行process substitution,执行命令,然后将结果放到一个临时文件里,再把这个<()替换为临时文件
比如diff <(ls blogs) <(ls daily)

函数

vim mcd.sh

mcd () {
    mkdir -p "$1"
    cd "$1"
}

source mcd
mcd test
结果会新建一个test文件夹并进入
这里$1指的是第一个参数

  • $0 - Name of the script

  • $1 to $9 - Arguments to the script. $1 is the first argument and so on.

  • $@ - All the arguments

  • $# - Number of arguments

  • $? - Return code of the previous command,0表示没问题;true总是返回0,false总是返回1;grep查找没找到的时候也会返回1

    • 在这里插入图片描述
      在这里插入图片描述
  • $$ - Process identification number (PID) for the current script

  • !! - Entire last command, including arguments. A common pattern is to execute a command only for it to fail due to missing permissions; you can quickly re-execute the command with sudo by doing sudo !!

    • 比如mkdir xxxx发现没有权限,下一行可以直接sudo !!来替换这个路径

  • $_ - Last argument from the last command. If you are in an interactive shell, you can also quickly get this value by typing Esc followed by . or Alt+.

逻辑

false总是返回1,true总是返回错误码0.可以用|| &&来连接命令;另外;总是会分割命令

false || echo "Oops, fail"
# Oops, fail

true || echo "Will not be printed"
#

true && echo "Things went well"
# Things went well

false && echo "Will not be printed"
#

true ; echo "This will always run"
# This will always run

false ; echo "This will always run"
# This will always run

分支

#!/bin/bash

echo "Starting program at $(date)" # Date will be substituted

echo "Running program 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值