【Shell脚本基础系列-1】入门 Getting started

本文介绍了Linux Shell的基础知识,包括如何使用touch创建或修改文件时间戳,chmod设置文件执行权限,以及变量的定义和参数传递。通过实例演示了shebang的重要性,以及如何执行和理解变量在脚本中的作用。

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

目录

  1. 入门
  2. if-else分支和for/while循环
  3. 环境变量
  4. 函数的使用
  5. 文件读写操作
  6. 睡眠
  7. 进程状态监测
  8. 用户交互

Getting started

Create an empty file Using touch

  1. Primary function of touch: To modify a timestamp

  2. Common utility:
    To create a file if it does not already exist

    $ touch hello_world.sh 
    

Chmod

$ bash hello_world.sh
$ ./hello_world.sh (Error: permission denied)

By default, files are not executable.

$ chmod 755 hello_world.sh 
$ ./hello_world.sh (Fine!)

$ hello_world.sh (Error: command not found)
  • Why ./

    Linux systems look for command on the path, not the current directory. ./ tells the system don’t bother with the path, look at the current directory.

The Shebang

Tells which command processor should handle this script Must be the first line, or will be ignored as a comment

  • For bash
    • #!/usr/bin/env bash (<- recommended)
    • #!/bin/bash
  • For python
    • #!/usr/bin/env python
  • For java script
    • #!/usr/bin/env node

Variables

#!/usr/bin/env bash

NAME="Bob Roberts"
COLOR=Blue

echo Hi $NAME, your favorite color is $COLOR.

Semantics

  • Must begin with a letter or an underscore (not a number)
  • Are case sensitive (usually all uppercase)
  • No spaces either side of the equal sign (double quote sign needed if spaces are needed in the value)

Parameters

Make it possible to interact with the user

#!/usr/bin/env bash

USER_NAME=$1
echo Hello $USER_NAME
echo $(date)  # out date and time
echo $(pwd)   # print working directory

exit 0

Check if the execution is successful: print the last (most recent) exit code that the system received

echo $?  
  • $0: the name of the script, the path is included
  • $1: the 1st parameter
  • $2: the 2nd parameter
  • ${10}: the 10th parameter (use of curly braces required for above 9.)

References

LinkedIn Learning: https://www.linkedin.com/learning/learning-linux-shell-scripting-2018

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值