Linux(18): Creating Bash Scripts

1. Core Purpose & Concepts

  • Core Purpose: To write a series of Linux commands that need to be executed in order into a text file, creating a “script”. By running this single script file, a multi-step task can be automated without manually entering each command.
  • Core Terminology:
    • Bash Script: A plain text file containing a series of Linux commands. The <span>.sh</span> extension is a conventional naming method to help humans recognize it, but it is not required by the system.
    • Interpreter: A program that can read and execute the commands in the script file. For Bash scripts, the interpreter is the Bash Shell itself.
    • Shebang (<span>#!</span>):Must be located on the first line of the script file, starting with a special sequence of <span>#!</span>. It tells the operating system which interpreter to use to execute this file. For Bash scripts, it is always <span>#!/bin/bash</span>.
    • Executable Permission: A permission attribute of a file that marks it as runnable as a program. This permission must be granted using the <span>chmod +x</span> command.
    • <span>$PATH</span> Environment Variable: A list of directory paths where all executable programs are located. When you enter a command in the terminal, the Shell looks for the corresponding program in the directories listed in this variable.
    • <span>~/.bashrc</span>: An important configuration file for the Bash Shell. Commands in this file are executed every time a new terminal is opened. It is the best place to modify the <span>$PATH</span> variable.
    • <span>~/bin</span> Directory: A conventional directory under the user’s home directory, specifically for storing the user’s own executable scripts. By adding this directory to <span>$PATH</span>, scripts stored here can be called directly by name like system commands from any path.

2. Key Steps & Commands

To create a script that can be run anytime and anywhere, the following steps are usually followed:

Step 1: Create and Write the Script

  1. Create File: Use <span>nano</span> or another text editor to create a new file.

    Bash

    nano my_backup.sh
  • ounter(line
  • Add Shebang: On the first line, write the Shebang at the beginning, specifying the Bash interpreter.

    Bash

    #!/bin/bash
    • ounter(line
  • Add Commands: Below the Shebang, write the commands you want to execute, one line at a time, just like in the terminal.

    Bash

    # This is an example script for creating backups# tar -czf ~/Desktop/my_backup.tar.gz ~/Documents ~/Pictures
    • ounter(line
    • ounter(line

    Step 2: Grant Execute Permission

    To allow the script to be run directly, rather than only through <span>bash my_script.sh</span>, it must be granted execute permission.

    Bash

    chmod +x my_backup.sh

    Step 3: Make the Script Globally Available (Recommended)

    1. Create <span>bin</span> Directory: Create a <span>bin</span> directory in your home directory (if it does not already exist).

      Bash

      mkdir -p ~/bin
    • ounter(line
  • Move Script: Move the script to the <span>~/bin</span> directory, and you can remove the <span>.sh</span> suffix to make it look more like a native command.

    Bash

    mv my_backup.sh ~/bin/my_backup
    • ounter(line
  • Modify <span>$PATH</span>: Edit the <span>~/.bashrc</span> file, adding a line at the end to include the <span>~/bin</span> directory in the <span>PATH</span> environment variable.

    Bash

    # Open the configuration file with nano
    ano ~/.bashrc
    # Add the following line at the endexport PATH="$HOME/bin:$PATH"
  • Make it Effective: Close and Reopen your terminal. Now, you can run your script by simply typing <span>my_backup</span> from any directory.

  • Script vs. Alias

    Feature Alias Script
    Complexity Suitable for creating “nicknames” for single-line, simple commands. Designed to accommodate multi-line commands, can include complex logic, loops, and functions.
    Structure Defined in the <span>.bash_aliases</span> file. Independent file, clearer structure.
    Scheduled Tasks Cannot be scheduled by tools like Cron. Can be scheduled by Cron, forming the basis for automation.

    3. Practical Use Cases

    • Automated Backup: Create a script that uses the <span>tar</span> command to periodically package and compress important directories (like <span>~/Documents</span>, <span>~/Pictures</span>) into a backup file.
    • Project Initialization: Write a script to create a standard directory structure for a new project (like <span>src</span>, <span>dist</span>, <span>tests</span>) with commands like <span>git init</span> executed for initialization.
    • System Status Report: Create a script that automatically collects system information (like disk space <span>df</span>, memory usage <span>free</span>) and outputs the report to a log file.

    4. Common Pitfalls

    • Forgetting or Miswriting Shebang: If there is no <span>#!/bin/bash</span>, or it is not on the first line, the system may not know which interpreter to use when running the script directly with <span>./script.sh</span>, leading to failure.
    • Forgetting to Grant Execute Permission:<span>chmod +x</span> is a very easy step to forget but is crucial. If forgotten, trying to run with <span>./script.sh</span> will prompt “Permission denied”.
    • <span>$PATH</span> Not Taking Effect Immediately: After modifying the <span>.bashrc</span> file, you must restart the terminal session for the new <span>$PATH</span> variable to take effect. It will not be effective in the current terminal.
    • Permission Issues in Scripts: Scripts are executed with the identity of the user running them. If a command in the script requires administrative privileges (for example, modifying files in the <span>/etc</span> directory), the script must be run with <span>sudo ./my_script.sh</span>, otherwise that command will fail.

    Leave a Comment