15 common shell script cases.
1.*hello world** Simplest script example:
#!/bin/bash
echo "hello, world!"
2.*Count the number of files in the directory** Count the number of files in the current directory:
#!/bin/bash
count=$(ls -1 | wc -l)
echo "there are $count files in the current directory."
3.*Create Backup** Back up files or directories by timestamp:
#!/bin/bash
filename="important_file.txt"
timestamp=$(date +%y%m%d%h%m%s)
cp "$filename" "$_$date +'%y%m%d')_backup"
4.*Find & Delete Empty Folders** Delete empty subdirectories in the current directory and its subdirectories:
#!/bin/bash
find . type d -empty -exec rmdir {}
5.*Process Monitoring & Restart** Automatically start a process when it doesn't exist (e.g. service):
#!/bin/bash
process_name="my_server"
if ! pgrep -x "$process_name" > /dev/null; then
path/to/start_script.sh &
fi6.*Get basic system information** Display system CPU and memory usage:
#!/bin/bash
echo "cpu usage: $top -bn1 | grep "cpu(s)" | awk '')%"
free -m | awk 'nr==2'
7.*Scheduled Execution Task** Create a task schedule that executes every minute (with crontab):
#!/bin/bash
echo "* */path/to/script.sh" >>/.crontab
crontab ~/.crontab
8.*File Content Replacement** Replace a specific string in a text file:
#!/bin/bash
sed -i 's/old_string/new_string/g' file.txt
9.*File** Use the curl command to download a file from the Internet
#!/bin/bash
url=""
wget -o downloaded_file.zip "$url"
10.*Rename files in bulk** Rename a set of files according to a pattern:
#!/bin/bash
for file in *.txt; do
mv "$file" "$.md"
done 11.*Compress and extract files** The compressed directory is tarGZ format:
#!/bin/bash
tar -czvf archive.tar.gz directory_to_compress/
Unzip the targz file:
tar -xzvf archive.tar.gz
12.*Check Disk Space** Output Disk Remaining Space Information:
#!/bin/bash
df -ht /home
13.*Find Large Files** Find files larger than 100MB in the current directory:
#!/bin/bash
du -h --max-depth=1 | grep '[0-9\.]g'
14.User Input Processing prompts the user for input and writes the input to a file
#!/bin/bash
read -p "Please enter a line of text:" input_text
echo "$input_text" >>user_input.log
15.*Check Network Connection** Simply test network connectivity:
#!/bin/bash
ping -c 1 google.com &&echo "The network connection is normal" ||echo "The network connection is abnormal"
Linux commands