0% found this document useful (0 votes)
12 views

How To Write A Bash Script To Run Commands - Linux Tutorials - Learn Linux Configuration

Uploaded by

John Williams
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

How To Write A Bash Script To Run Commands - Linux Tutorials - Learn Linux Configuration

Uploaded by

John Williams
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

Menu

How to write a Bash script to run commands


9 March 2023 by Luke Reynolds

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 work�ows. 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 e�cient 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

1 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

Bash script to run commands

So�ware Requirements and Linux Command Line Conventions

Category Requirements, Conventions or So�ware Version Used

System Any Linux distro

So�ware N/A

Privileged access to your Linux system as root or via the sudo


Other
command.

# – requires given linux commands to be executed with root


privileges either directly as a root user or by use of sudo command
Conventions
$ – 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:

1 #!/bin/bash
2

2 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

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:

1 #!/bin/bash
2 ls
3 pwd
4 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 �le 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 work�ows 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

3 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

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

1 #!/bin/bash
2 echo "The first argument is $1"
3 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

Options

Options are �ags 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:

1 #!/bin/bash
2 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 �les in the speci�ed directory.

4 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

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:

1 #!/bin/bash
2 echo -n "Please enter your name: "
3 read name
4 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 �t a wide range of
use cases.

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


database

1 #!/bin/bash
2
3 # Define MySQL database connection parameters
4 DB_HOST="localhost"
5 DB_PORT="3306"
6 DB_USER="root"
7

5 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

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 compres


mysqldump --host="$DB_HOST" --port="$DB_PORT" --user="$DB_USER

# 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 de�ne variables for the MySQL database connection parameters
and the backup �le 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 speci�ed database,
and pipe the output to the gzip command to compress it. The resulting backup �le
is saved to the speci�ed backup path.

Finally, we verify that the backup �le 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 �le, we can automate

6 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

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 �exibility of Linux and Unix systems, enabling developers to automate complex
tasks and work�ows. 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 e�cient scripts that can handle a wide
range of use cases.

Related Linux Tutorials:

• An Introduction to Linux Automation, Tools and Techniques


• Mastering Bash Script Loops
• Nested Loops in Bash Scripts
• Mint 20: Better Than Ubuntu and Microso� Windows?
• Best Linux distro for developers
• Handling User Input in Bash Scripts
• Ubuntu 20.04 Guide
• How to Use a Bash Script to Run Your Python Scripts
• Things to install on Ubuntu 22.04
• Can Linux Get Viruses? Exploring the Vulnerability of Linux…

System Administration
bash, �lesystem, programming, scripting
MX Linux vs Ubuntu
How to Use a Bash Script to Run Your Python Scripts

7 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

Comments and Discussions

Start Discussion 0 replies

NEWSLETTER

Subscribe to Linux Career Newsletter to receive latest news, jobs, career advice and featured
con�guration tutorials.

SUBSCRIBE

WRITE FOR US

LinuxCon�g is looking for a technical writer(s) geared towards GNU/Linux and FLOSS
technologies. Your articles will feature various GNU/Linux con�guration tutorials and FLOSS
technologies used in combination with GNU/Linux operating system.

When writing your articles you will be expected to be able to keep up with a technological
advancement regarding the above mentioned technical area of expertise. You will work
independently and be able to produce at minimum 2 technical articles a month.

APPLY NOW

TAGS

18.04 administration apache applications backup bash beginner browser

centos centos8 commands database debian desktop development docker error

8 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

fedora �lesystem �rewall gaming gnome Hardware installation java kali manjaro
multimedia networking nvidia programming python redhat rhel8 scripting
security server ssh storage terminal ubuntu ubuntu 20.04 virtualization webapp
webserver

ABOUT US

FEATURED TUTORIALS

VIM tutorial for beginners

How to install the NVIDIA drivers on Ubuntu 20.04 Focal Fossa Linux

Bash Scripting Tutorial for Beginners

How to check CentOS version

How to �nd my IP address on Ubuntu 20.04 Focal Fossa Linux

Ubuntu 20.04 Remote Desktop Access from Windows 10

Howto mount USB drive in Linux

How to install missing ifcon�g command on Debian Linux

AMD Radeon Ubuntu 20.04 Driver Installation

Ubuntu Static IP con�guration

How to use bash array in a shell script

Linux IP forwarding – How to Disable/Enable

How to install Tweak Tool on Ubuntu 20.04 LTS Focal Fossa Linux

How to enable/disable �rewall on Ubuntu 18.04 Bionic Beaver Linux

Netplan static IP on Ubuntu con�guration

How to change from default to alternative Python version on Debian Linux

Set Kali root password and enable root login

How to Install Adobe Acrobat Reader on Ubuntu 20.04 Focal Fossa Linux

How to install the NVIDIA drivers on Ubuntu 18.04 Bionic Beaver Linux

9 of 10 4/7/23, 12:27 PM
How to write a Bash script to run commands - Linux Tut... https://linuxconfig.org/how-to-write-a-bash-script-to-ru...

How to check NVIDIA driver version on your Linux system

Nvidia RTX 3080 Ethereum Hashrate and Mining Overclock settings on HiveOS Linux

LATEST TUTORIALS

Introduction to Vagrant

Check CPU and RAM usage of a Kubernetes pod

Kubernetes vs Docker, whatʼs the di�erence?

Install and Use MicroK8s on Ubuntu

How to Create and Manage a Pod in Kubernetes

How to Create, Manage, and Expose a Service in Kubernetes

Control CPU and RAM usage in Kubernetes

How to Setup Minikube for Kubernetes

Choosing a Kubernetes Networking Addon

What is Kubernetes used for?

How to create a cron job in Kubernetes

kubeadm vs minikube, pros and cons

How to Create a Kubernetes Cluster

How to use helm package manager for Kubernetes

How to deploy WordPress on a Kubernetes cluster

kubectl command examples (cheat sheet)

How to manage and troubleshoot Kubernetes logs

How to Install Kubernetes on All Linux Distros

How to Manage Kubernetes Clusters With kubectl

How to Deploy an Application in Kubernetes

© 2023 TOSID Group Pty Ltd - LinuxCon�g.org

10 of 10 4/7/23, 12:27 PM

You might also like