How to write a Bash script to run commands

Bash scripting is a powerful tool for automating complex tasks in Linux and Unix systems. One of the key features of bash scripting is the ability to run system commands within a script, enabling developers to automate repetitive tasks or complex workflows. In this article, we will explore the basic syntax and best practices for writing a bash script to run commands. Whether you’re a beginner or an intermediate-level bash programmer, this article will provide you with the foundational knowledge and skills to create robust and efficient scripts that can automate even the most complex tasks.

In this tutorial you will learn:

  • Basic syntax for running commands in a bash script
  • How to pass arguments and options to commands within a bash script
  • Using conditionals and loops to run commands conditionally or iteratively
Bash script to run commands
Bash script to run commands
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software N/A
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ – requires given linux commands to be executed as a regular non-privileged user

Basic syntax of running commands in a bash script

The basic syntax for running commands in a bash script is simple and straightforward. To run a command within a script, simply enter the command as you would in the command-line interface.

For example, to run the ls command within a script, you would write:

#!/bin/bash
ls

This script will execute the ls command when it is run, and display the contents of the current directory.

To run multiple commands within a script, simply add them to the script on separate lines:

#!/bin/bash
ls
pwd
echo "Hello, world!

In this script, the ls, pwd, and echo commands will all be executed sequentially when the script is run.

It’s important to note that when running commands within a script, any output from the command will be displayed on the console unless it is redirected or captured by the script. To capture command output, you can use shell variables or redirection operators to send output to a file or other location.

Overall, understanding the basic syntax of running commands in a bash script is crucial for creating scripts that can automate complex tasks and workflows in Linux and Unix systems.

How to pass arguments and options to commands within a bash script

Passing arguments and options to commands within a bash script is a powerful feature that enables scripts to be customized and controlled based on user input or other factors. There are several ways to pass arguments and options to commands within a bash script, including:

Command-line arguments

These are values passed to the script when it is executed, and can be accessed within the script using special variables. For example, the first argument passed to the script can be accessed using $1, the second using $2, and so on. Here’s an example:

#!/bin/bash
echo "The first argument is $1"
echo "The second argument is $2"

If this script is run with the command ./myscript.sh foo bar, the output will be:

Command-line arguments
Command-line arguments

Options



Options are flags that can be used to modify the behavior of commands. They are typically preceded by a dash (-) or two dashes (--). To pass options to a command within a script, simply include the option(s) as part of the command. Here’s an example:

#!/bin/bash
ls -l /path/to/dir

In this script, the ls command is run with the -l option, which causes it to display the long format listing of files in the specified directory.

Prompting for input

Sometimes it may be necessary to prompt the user for input within a script. This can be done using the read command, which reads a line of input from the user and stores it in a variable. Here’s an example:

#!/bin/bash
echo -n "Please enter your name: "
read name
echo "Hello, $name!"

In this script, the read command prompts the user for their name and stores the input in the name variable, which is then used to display a personalized greeting.

Overall, passing arguments and options to commands within a bash script is a powerful feature that can make scripts more versatile and user-friendly. By understanding how to use command-line arguments, options, and input prompts, bash programmers can create scripts that can be customized to fit a wide range of use cases.



Example of Bash script that runs a commands to backup a MySQL database

#!/bin/bash

# Define MySQL database connection parameters
DB_HOST="localhost"
DB_PORT="3306"
DB_USER="root"
DB_PASSWORD="password"
DB_NAME="mydatabase"

# Define backup file name and path
BACKUP_DIR="/var/backups/mysql"
BACKUP_FILE="$DB_NAME-backup-$(date +%Y-%m-%d-%H-%M-%S).sql.gz"
BACKUP_PATH="$BACKUP_DIR/$BACKUP_FILE"

# Create backup directory if it doesn't exist
if [ ! -d "$BACKUP_DIR" ]
then
    mkdir -p "$BACKUP_DIR"
fi

# Use mysqldump to create a backup of the database and compress it
mysqldump --host="$DB_HOST" --port="$DB_PORT" --user="$DB_USER" --password="$DB_PASSWORD" "$DB_NAME" | gzip > "$BACKUP_PATH"

# Verify that the backup file was created successfully
if [ -f "$BACKUP_PATH" ]
then
    echo "Database backup created successfully: $BACKUP_PATH"
else
    echo "Error creating database backup"
fi

In this script, we define variables for the MySQL database connection parameters and the backup file name and path. We then create the backup directory if it doesn’t exist. We use the mysqldump command to create a backup of the specified database, and pipe the output to the gzip command to compress it. The resulting backup file is saved to the specified backup path.

Finally, we verify that the backup file was created successfully and display a message indicating whether the backup was successful or not. By using a bash script to run the mysqldump command and compress the resulting backup file, we can automate the backup process and ensure that our MySQL database is backed up regularly and reliably.

Conclusion

In conclusion, using bash scripts to run commands can greatly enhance the power and flexibility of Linux and Unix systems, enabling developers to automate complex tasks and workflows. By understanding the basic syntax of running commands, passing arguments and options, and using conditionals and loops, intermediate-level bash programmers can create robust and efficient scripts that can handle a wide range of use cases.



Comments and Discussions
Linux Forum