Basic bash script tutorial

Bash Script Tutorial

1. Script Basics

1.1 Creating a Bash Script

  1. Create a script file with a .sh extension:

    bash 复制代码
    touch myscript.sh
  2. Make the script executable:

    bash 复制代码
    chmod +x myscript.sh
  3. Add the shebang line at the top to specify the interpreter:

    bash 复制代码
    #!/bin/bash

1.2 Running a Bash Script

Run the script from the terminal by providing the path:

bash 复制代码
./myscript.sh

2. Variables

2.1 Defining Variables

Variables do not need a data type declaration in Bash:

bash 复制代码
name="John"
age=25

2.2 Accessing Variables

Use the $ symbol to access a variable's value:

bash 复制代码
echo "My name is $name and I am $age years old."

2.3 Reading User Input

You can use the read command to get input from the user:

bash 复制代码
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"

3. Conditionals

3.1 if Statements

bash 复制代码
if [ condition ]; then
  # Code to execute if the condition is true
fi

3.2 if-else Statements

bash 复制代码
if [ condition ]; then
  echo "Condition is true"
else
  echo "Condition is false"
fi

3.3 if-elif-else Example

bash 复制代码
if [ $age -lt 18 ]; then
  echo "You are a minor."
elif [ $age -ge 18 ] && [ $age -lt 65 ]; then
  echo "You are an adult."
else
  echo "You are a senior."
fi

3.4 File Conditionals

Check if a file or directory exists:

bash 复制代码
if [ -f "/path/to/file" ]; then
  echo "File exists."
fi

if [ -d "/path/to/directory" ]; then
  echo "Directory exists."
fi

3.5 String Comparison

bash 复制代码
str1="hello"
str2="world"

if [ "$str1" == "$str2" ]; then
  echo "Strings are equal."
else
  echo "Strings are not equal."
fi

4. Loops

4.1 for Loop

bash 复制代码
for i in 1 2 3; do
  echo $i
done

4.2 for Loop with Range

bash 复制代码
for i in {1..5}; do
  echo $i
done

4.3 while Loop

bash 复制代码
count=1
while [ $count -le 5 ]; do
  echo $count
  ((count++))
done

4.4 until Loop

bash 复制代码
count=1
until [ $count -gt 5 ]; do
  echo $count
  ((count++))
done

5. Arrays

5.1 Declaring Arrays

bash 复制代码
fruits=("apple" "banana" "cherry")

5.2 Accessing Array Elements

bash 复制代码
echo ${fruits[0]}  # Output: apple

5.3 Looping Through an Array

bash 复制代码
for fruit in "${fruits[@]}"; do
  echo $fruit
done

5.4 Array Length

bash 复制代码
echo ${#fruits[@]}  # Output: 3

6. Functions

6.1 Defining a Function

bash 复制代码
function greet() {
  echo "Hello, $1!"
}

6.2 Calling a Function

bash 复制代码
greet "Alice"  # Output: Hello, Alice!

6.3 Returning Values

Bash functions return values using return or output:

bash 复制代码
function add() {
  local sum=$(( $1 + $2 ))
  echo $sum
}

result=$(add 10 20)
echo "Sum: $result"  # Output: Sum: 30

7. File and Directory Operations

7.1 Creating Directories

bash 复制代码
mkdir myfolder

7.2 Checking if a Directory Exists

bash 复制代码
if [ ! -d "myfolder" ]; then
  mkdir myfolder
fi

7.3 Listing Files in a Directory

bash 复制代码
for file in *; do
  echo $file
done

8. Input/Output Redirection

8.1 Redirecting Output to a File

bash 复制代码
echo "Hello, World!" > output.txt  # Overwrites the file
echo "Append this line" >> output.txt  # Appends to the file

8.2 Redirecting Input from a File

bash 复制代码
while read line; do
  echo $line
done < input.txt

8.3 Redirecting Error Output

bash 复制代码
command 2> error.log  # Redirect stderr to error.log
command > output.log 2>&1  # Redirect stdout and stderr to output.log

9. Special Variables

9.1 Positional Parameters

bash 复制代码
#!/bin/bash
echo "Script name: $0"
echo "First argument: $1"
echo "Second argument: $2"

9.2 Script Exit Status

bash 复制代码
command
if [ $? -eq 0 ]; then
  echo "Command succeeded."
else
  echo "Command failed."
fi

9.3 Looping Through Arguments

bash 复制代码
for arg in "$@"; do
  echo "Argument: $arg"
done

10. Miscellaneous

10.1 Exit Script with Status Code

bash 复制代码
if [ "$user" != "admin" ]; then
  echo "Access denied."
  exit 1
fi

10.2 Sleeping for a Few Seconds

bash 复制代码
sleep 5  # Waits for 5 seconds

10.3 Commenting in Bash

Use # for single-line comments:

bash 复制代码
# This is a comment
echo "This is code."

11. Combining Everything in a Complete Script Example

Here's a complete example script that demonstrates many of these concepts:

bash 复制代码
#!/bin/bash

# Function to create a directory if it doesn't exist
create_directory() {
  if [ ! -d "$1" ]; then
    mkdir "$1"
    echo "Directory '$1' created."
  else
    echo "Directory '$1' already exists."
  fi
}

# Greet the user
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"

# Create directories
projects=("project1" "project2" "project3")
for project in "${projects[@]}"; do
  create_directory "$project"
done

# Example of a conditional
if [ "$user_name" == "admin" ]; then
  echo "Welcome, admin!"
else
  echo "You are not the admin."
fi

# Example of a loop
for i in {1..5}; do
  echo "Iteration $i"
done

# Function with return value
function add() {
  local result=$(( $1 + $2 ))
  echo $result
}

sum=$(add 10 20)
echo "The sum of 10 and 20 is: $sum"

相关推荐
xiaoye-duck9 小时前
《C++ 项目:手写大模型接入 SDK》Gemini接口设计(上):初始化、全量响应实现和测试
开发语言·网络·c++·语言模型
nice_lcj52011 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河6612 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
nice_lcj52016 小时前
ThreadLocal 入门:它是怎么隔离数据的、为什么会导致内存泄漏
java·开发语言·后端·面试·并发编程·内存泄漏·threadlocal
紧跟先前的步伐16 小时前
Go AI Agent 实战 28|Agent 的预算、超时与停止条件
开发语言·人工智能·后端·ai·golang
bksczm17 小时前
InnoDB 行格式详解:DYNAMIC / COMPACT / COMPRESSED / REDUNDANT
java·开发语言·数据库
春涧草茶18 小时前
慢就是快16-1协程
开发语言·前端·python
Dovis(誓平步青云)18 小时前
启元 T1 Pro 人机相声搭档:语音-触摸双通道的启元机器人节奏引擎设计
开发语言·前端·javascript·microsoft·交互
做科研的周师兄18 小时前
【R语言实战】MixSIAR 氢氧同位素水源解析全流程:从混合空间校验到贝叶斯 MCMC 收敛诊断(后附完整代码)
java·大数据·开发语言
.痞老板.20 小时前
java ee--计算机是如何工作的
java·开发语言·java-ee