What is a Bash Script?

Programming can be intimidating for beginners. Many people are intimidated by the prospect of having to learn a new language, syntax, and commands – there are so many parts that it’s difficult to know where to start!Select

Bash is a Unix shell, popularized by the GNU Project. It has been an industry standard for decades and is still universally used to this day. Bash scripts automate tasks on computers and are often used in system administration, forecasting, finance and accounting, banking, graphic design. This article talks about how to write a simple bash script and also explains some of the basic constructs you can use in it. A Bash Script is a text document that contains a series of commands and functions. It can be used to execute many commands at once, in sequence, or just one command. The script does not have to do anything with computers and can be for anything from locking doors on the way out, to an example I found on Wikipedia which was to “blink an LED”

This article is going to show you what a bash script is and how to use it. So, you might be wondering “What is a Bash Script?” This article will take you through the entire process of writing a bash script from start to finish.

What is a Bash Script?

Bash is a Unix shell, popularized by the GNU Project. It has been an industry standard for decades and is still universally used to this day. Bash scripts automate tasks on computers and are often used in system administration, forecasting, finance and accounting, banking, graphic design. This article talks about how to write a simple bash script and also explains some of the basic constructs you can use in it.

What are the uses of Bash Scripts?

Bash scripts are commonly used to automate tasks on Linux and UNIX systems. They can be used to launch programs, run commands, and perform other tasks.

Bash scripts are often used to automate system administration tasks, such as managing users, installing software, or backing up files. They can also be used to create custom applications or to add features to existing software.

Bash scripts can be run manually from the command line or they can be executed automatically by a scheduler. They can also be integrated into other programs or scripts.

Setting up your own bash script

A bash script is a text file containing a sequence of commands that are executed by the bash shell. To create a bash script, you need to use a text editor such as gedit or vi.

Once you have created your bash script, you need to make it executable. This can be done by using the chmod command. For example, if your script is called myscript.sh, you would type the following at the command prompt:

chmod +x myscript.sh

You can now run your bash script by typing ./myscript.sh at the command prompt.

How to Write a Bash Script.

There are a few things you need to know in order to write a bash script. First, you need to be familiar with the bash shell. Bash is aUnix shell and command language written by Brian Fox for the GNU Project as a free software replacement for the Bourne shell.

Second, you will need a text editor. Any text editor will do, but for the sake of this tutorial we will use nano. Nano is a small, free and friendly text editor which comes installed by default on many Linux distributions.

Writing your first script
Now that you have nano open, we can start writing our first script! In its simplest form, a bash script is just a list of commands that we would normally run from the command line, one after the other. Let’s say we wanted to create a script that would allow us to quickly set up a new user account on our system. We would want our script to do the following:

1) Prompt us for the username of the new user
2) Create a new directory for that user in /home
3) Create an empty password file for that user
4) Add the new user to our system using the information we provided
5) Set up some initial configuration files for the new user
6) Copy over any existing dotfiles (configuration files) from another user account
7) Allow us to choose whether or not to give the new user sudo access

How to Write a “Hello World” Bash Script

We’ll start simple with “Hello World”. This may seem trivial, but a hello world test is useful to understand the workflow of creating a Bash script, and to test the basic functionality. We’ll be using the nano text editor, but you can also write your scripts in another terminal or GUI based text editor.

1. Create a new file, hello.sh and open it with nano.

nano hello.sh

2. On the first line specify the interpreter to be used in the code. In this case it is Bash.The first part of the line, #!, is called the “shebang” and it indicates the start of a script.

#!/bin/bash

3. On a new line use echo to print a string of text to the screen.

echo “Hello World”

4. Save the code by pressing CTRL + X, then press Y and Enter.

5. Run the code from the terminal.

bash hello.sh

The output of the command is a single line of “Hello World.” This proves that our script works and we can move on to something a little more interesting

Bash scripting

One reason Bash (and Linux in general) is considered so powerful is because it’s scriptable. Anything you can manually type into Bash can also be listed in a plain-text file and run by Bash. You don’t have to manually run a hundred commands for an afternoon; you may script the commands and let your computer run them while you attend to more crucial tasks. Because almost all Linux applications operate on top of the Bash shell, almost all Linux applications can be programmed using Bash. Despite the fact that there are certain exceptions (graphical apps, for instance, might have their own scripting language or not at all), scripting your operating system allows you to automate tens of thousands of computer-related tasks.

The amount of work this saves Linux users each day is impossible to estimate. It’s not the usual automation that makes the difference, though; it’s the bespoke workflows that people invent for themselves, the things nobody else thinks need automation.

If experienced users mean something else when they say they want to learn Bash, it’s probably to enhance the way they write their commands rather than to learn Linux instructions. For instance, the following is a very basic Bash script that changes a temporary file (assume it was created by a different process) to a particular directory:

#!/usr/bin/bashcp tmp.png ~/public_html/`date +%Y%m%d`.png

That’s valid Bash. You can verify it by copying and pasting the command (the last line beginning with cp) into a terminal. As long as there’s a file called tmp.png and a directory called ~/public_html, the command works.

Learning Bash, though, is all about understanding how a simple command like this can be improved for the sake of automation. For instance, if the file tmp.png doesn’t exist, then the script fails. If this script is a key component to, for instance, a blogging site that requires a new image each day so that a custom header image can be constructed, then the script’s failure could cause catastrophic errors elsewhere. A user who knows Bash could add resiliency using Bash syntax:

#!/usr/bin/bashIMG="tmp.png"[[ -e tmp.png ]] || IMG="generic.png"cp ~/"${IMG}" ~/public_html/`date +%Y%m%d`.png

This is just one example of the process of learning to script with Bash, but it demonstrates how learning both Linux and Bash are equally useful and not entirely separate tasks.

How do we run them?

Running a Bash script is fairly easy. Another term you may come across is executing the script (which means the same thing). Before we can execute a script it must have the execute permission set (for safety reasons this permission is generally not set by default). If you forget to grant this permission before running the script you’ll just get an error message telling you as such and no harm will be done.

  1. ./myscript.sh
  2. bash: ./myscript.sh: Permission denied
  3. ls -l myscript.sh
  4. -rw-r–r– 18 ryan users 4096 Feb 17 09:12 myscript.sh
  5. chmod 755 myscript.sh
  6. ls -l myscript.sh
  7. -rwxr-xr-x 18 ryan users 4096 Feb 17 09:12 myscript.sh
  8. ./myscript.sh
  9. Hello World!

The shorthand 755 is often used for scripts as it allows you the owner to write or modify the script and for everyone to execute the script.

Here are the contents of myscript.sh

myscript.sh

  1. #!/bin/bash
  2. # A sample Bash script, by Ryan
  3. echo Hello World!

Let’s break it down:

  • Line 1 – Is what’s referred to as the shebang. See below for what this is.
  • Line 2 – This is a comment. Anything after # is not executed. It is for our reference only.
  • Line 4 – Is the command echo which will print a message to the screen. You can type this command yourself on the command line and it will behave exactly the same.
  • The syntax highlighting is there only to make it easier to read and is not something you need to do in your own files (remember they are just plain text files).

Why the ./

You’ve possibly noticed that when we run a normal command (such as ls) we just type its name but when running the script above I put a ./ in front of it. When you just type a name on the command line Bash tries to find it in a series of directories stored in a variable called $PATH. We can see the current value of this variable using the command echo (you’ll learn more about variables in the next section).

  1. echo $PATH
  2. /home/ryan/bin:/usr/local/bin:/usr/bin:/bin

The directories are separated by ” : “

Bash only looks in those specific directories and doesn’t consider sub directories or your current directory. It will look through those directories in order and execute the first instance of the program or script that it finds.

The $PATH variable is an individual user variable so each user on a system may set it to suit themselves.

This is done for a few different reasons.

  • It allows us to have several different versions of a program installed. We can control which one gets executed based on where it sits in our $PATH.
  • It allows for convenience. As you saw above, the first directory for myself is a bin directory in my home directory. This allows me to put my own scripts and programs there and then I can use them no matter where I am in the system by just typing their name. I could even create a script with the same name as a program (to act as a wrapper) if I wanted slightly different behaviour.
  • It increases safety – For example a malicious user could create a script called ls which actually deletes everything in your home directory. You wouldn’t want to inadvertantly run that script. But as long as it’s not in your $PATH that won’t happen.

You can launch a program or script even if it is not in one of the directories listed in your $PATH environment variable by instructing Bash where to look for it. To do this, provide an absolute or relative path in front of the program’s or script’s name. You’ll recall that the dot (.) refers to your current directory. This script may have also been executed using an absolute path, assuming it was located in my home directory.

  1. /home/ryan/myscript.sh
  2. Hello World!

The Shebang (#!)

#!/bin/bash

The script’s opening line is as follows. The Shebang is the collection of characters that follow the hash exclamation mark (#!) The path to the program or interpreter that should be used to run or interpret the remaining text lines in the text file is listed after it. (For Bash scripts, the path to Bash will be used; there are numerous other types of scripts, each with a different interpreter.)

Formatting is important here. The shebang must be on the very first line of the file (line 2 won’t do, even if the first line is blank). There must also be no spaces before the # or between the ! and the path to the interpreter.

Whilst you could use a relative path for the interpreter, most of the time you are going to want to use an absolute path. You will probably be running the script from a variety of locations so absolute is the safest (and often shorter than a relative path too in this particular case).

It is possible to leave out the line with the shebang and still run the script but it is unwise. If you are at a terminal and running the Bash shell and you execute a script without a shebang then Bash will assume it is a Bash script. So this will only work assuming the user running the script is running it in a Bash shell and there are a variety of reasons why this may not be the case, which is dangerous.

You can also run Bash, passing the script as an argument.

  1. bash myscript.sh
  2. Hello World!

Whilst this is safe it also involves unnecessary typing every time you want to run the script.

Given the observations above it is best to always include the shebang ( #! ). It is the most reliable and convenient approach.

An A-Z Index of the Linux command line: bash + utilities.

A Command  Utilies
 &Start a new process in the background
 aliasCreate an alias •
 aproposSearch Help manual pages (man -k)
 aptSearch for and install software packages (Debian/Ubuntu)
 apt-getSearch for and install software packages (Debian/Ubuntu)
 aptitudeSearch for and install software packages (Debian/Ubuntu)
 aspellSpell Checker
 atSchedule a command to run once at a particular time
 awkFind and Replace text, database sort/validate/index
B  
 basenameStrip directory and suffix from filenames
 base32Base32 encode/decode data and print to standard output
 base64Base64 encode/decode data and print to standard output
 bashGNU Bourne-Again SHell
 bcArbitrary precision calculator language
 bgSend to background
 bindSet or display readline key and function bindings •
 breakExit from a loop •
 builtinRun a shell builtin
 bzip2Compress or decompress named file(s)
C  
 calDisplay a calendar
 callerReturn the context of any active subroutine call •
 caseConditionally perform a command
 catConcatenate and print (display) the content of files
 cdChange Directory
 cfdiskPartition table manipulator for Linux
 chattrChange file attributes on a Linux file system
 chgrpChange group ownership
 chmodChange access permissions
 chownChange file owner and group
 chpasswdUpdate passwords in batch mode
 chrootRun a command with a different root directory
 chkconfigSystem services (runlevel)
 cksumPrint CRC checksum and byte counts
 clearClear terminal screen
 cmpCompare two files
 commCompare two sorted files line by line
 commandRun a command – ignoring shell functions •
 continueResume the next iteration of a loop •
 cpCopy one or more files to another location
 cpioCopy files to and from archives
 cronDaemon to execute scheduled commands
 crontabSchedule a command to run at a later time
 csplitSplit a file into context-determined pieces
 curlTransfer data from or to a server
 cutDivide a file into several parts
D  
 dateDisplay or change the date & time
 dcDesk Calculator
 ddData Duplicator – convert and copy a file, write disk headers, boot records
 ddrescueData recovery tool
 declareDeclare variables and give them attributes •
 dfDisplay free disk space
 diffDisplay the differences between two files
 diff3Show differences among three files
 digDNS lookup
 dirBriefly list directory contents
 dircolorsColour setup for ‘ls’
 dirnameConvert a full pathname to just a path
 dirsDisplay list of remembered directories
 dos2unixWindows/MAC to UNIX text file format converter
 dmesgPrint kernel & driver messages
 dpkgPackage manager (Debian/Ubuntu).
 duEstimate file space usage
E  
 echoDisplay message on screen •
 egrepSearch file(s) for lines that match an extended expression
 ejectEject removable media
 enableEnable and disable builtin shell commands •
 envEnvironment variables
 ethtoolEthernet card settings
 evalEvaluate several commands/arguments
 execExecute a command
 exitExit the shell
 expandConvert tabs to spaces
 exportSet an environment variable
 exprEvaluate expressions
F  
 falseDo nothing, unsuccessfully
 fdformatLow-level format a floppy disk
 fdiskPartition table manipulator for Linux
 fgSend job to foreground
 fgrepSearch file(s) for lines that match a fixed string
 fileDetermine file type
 findSearch for files that meet a desired criteria
 fmtReformat paragraph text
 foldWrap text to fit a specified width
 forExpand words, and execute commands
 formatFormat disks or tapes
 freeDisplay memory usage
 fsckFile system consistency check and repair
 ftpFile Transfer Protocol
 functionDefine Function Macros
 fuserIdentify/kill the process that is accessing a file
G  
 gawkFind and Replace text within file(s)
 getoptsParse positional parameters
 getfaclGet file access control lists
 grepSearch file(s) for lines that match a given pattern
 groupaddAdd a user security group
 groupdelDelete a group
 groupmodModify a group
 groupsPrint group names a user is in
 gzipCompress or decompress named file(s)
H  
 hashRemember the full pathname of a name argument
 headOutput the first part of file(s)
 helpDisplay help for a built-in command •
 historyCommand History
 hostnamePrint or set system name
 htopInteractive process viewer
I  
 iconvConvert the character set of a file
 idPrint user and group id’s
 ifConditionally perform a command
 ifconfigConfigure a network interface
 ifdownStop a network interface
 ifupStart a network interface up
 importCapture an X server screen and save the image to file
 installCopy files and set attributes
 iostatReport CPU and i/o statistics
 ipRouting, devices and tunnels
J  
 jobsList active jobs •
 joinJoin lines on a common field
K  
 killKill a process by specifying its PID
 killallKill processes by name
 klistList cached Kerberos tickets
L  
 lessDisplay output one screen at a time
 letPerform arithmetic on shell variables •
 linkCreate a link to a file
 lnCreate a symbolic link to a file
 localCreate a function variable •
 locateFind files
 lognamePrint current login name
 logoutExit a login shell •
 lookDisplay lines beginning with a given string
 lpcLine printer control program
 lprPrint files
 lprintPrint a file
 lprintdDelete a print job
 lprintqList the print queue
 lprmRemove jobs from the print queue
 lsattrList file attributes on a Linux second extended file system
 lsblkList block devices
 lsList information about file(s)
 lsofList open files
 lspciList all PCI devices
M  
 makeRecompile a group of programs
 manHelp manual
 mapfileRead lines from standard input into an indexed array variable •
 mkdirCreate new folder(s)
 mkfifoMake FIFOs (named pipes)
 mkfileMake a file
 mkisofsCreate a hybrid ISO9660/JOLIET/HFS filesystem
 mknodMake block or character special files
 mktempMake a temporary file
 moreDisplay output one screen at a time
 mostBrowse or page through a text file
 mountMount a file system
 mtoolsManipulate MS-DOS files
 mtrNetwork diagnostics (traceroute/ping)
 mvMove or rename files or directories
 mmvMass Move and rename (files)
N  
 ncNetcat, read and write data across networks
 netstatNetworking connections/stats
 nftnftables for packet filtering and classification
 niceSet the priority of a command or job
 nlNumber lines and write files
 nohupRun a command immune to hangups
 notify-sendSend desktop notifications
 nslookupQuery Internet name servers interactively
O  
 openOpen a file in its default application
 opOperator access
P  
 passwdModify a user password
 pasteMerge lines of files
 pathchkCheck file name portability
 PerfPerformance analysis tools for Linux
 pingTest a network connection
 pgrepList processes by name
 pkillKill processes by name
 popdRestore the previous value of the current directory
 prPrepare files for printing
 printcapPrinter capability database
 printenvPrint environment variables
 printfFormat and print data •
 psProcess status
 pushdSave and then change the current directory
 pvMonitor the progress of data through a pipe
 pwdPrint Working Directory
Q  
 quotaDisplay disk usage and limits
 quotacheckScan a file system for disk usage
R  
 ramram disk device
 rarArchive files with compression
 rcpCopy files between two machines
 readRead a line from standard input •
 readarrayRead from stdin into an array variable •
 readonlyMark variables/functions as readonly
 rebootReboot the system
 renameRename files
 reniceAlter priority of running processes
 remsyncSynchronize remote files via email
 returnExit a shell function
 revReverse lines of a file
 rmRemove files
 rmdirRemove folder(s)
 rsyncRemote file copy (Synchronize file trees)
S  
 screenMultiplex terminal, run remote shells via ssh
 scpSecure copy (remote file copy)
 sdiffMerge two files interactively
 sedStream Editor
 selectAccept user choices via keyboard input
 seqPrint numeric sequences
 setManipulate shell variables and functions
 setfaclSet file access control lists.
 sftpSecure File Transfer Program
 shiftShift positional parameters
 shoptShell Options
 shufGenerate random permutations
 shutdownShutdown or restart linux
 sleepDelay for a specified time
 slocateFind files
 sortSort text files
 sourceRun commands from a file ‘.’  •
 splitSplit a file into fixed-size pieces
 ssSocket Statistics
 sshSecure Shell client (remote login program)
 statDisplay file or file system status
 straceTrace system calls and signals
 suSubstitute user identity
 sudoExecute a command as another user
 sumPrint a checksum for a file
 suspendSuspend execution of this shell •
 syncSynchronize data on disk with memory
T  
 tailOutput the last part of a file
 tarStore, list or extract files in an archive
 teeRedirect output to multiple files
 testEvaluate a conditional expression
 timeMeasure Program running time
 timeoutRun a command with a time limit
 timesUser and system times
 tmuxTerminal multiplexer
 touchChange file timestamps
 topList processes running on the system
 tputSet terminal-dependent capabilities, color, position
 tracerouteTrace Route to Host
 trapExecute a command when the shell receives a signal •
 trTranslate, squeeze, and/or delete characters
 trueDo nothing, successfully
 tsortTopological sort
 ttyPrint filename of terminal on stdin
 typeDescribe a command •
U  
 ulimitLimit user resources •
 umaskUsers file creation mask
 umountUnmount a device
 unaliasRemove an alias •
 unamePrint system information
 unexpandConvert spaces to tabs
 uniqUniquify files
 unitsConvert units from one scale to another
 unix2dosUNIX to Windows or MAC text file format converter
 unrarExtract files from a rar archive
 unsetRemove variable or function names
 unsharUnpack shell archive scripts
 untilExecute commands (until error)
 uptimeShow uptime
 useraddCreate new user account
 userdelDelete a user account
 usermodModify user account
 usersList users currently logged in
 uuencodeEncode a binary file
 uudecodeDecode a file created by uuencode
V  
 vVerbosely list directory contents (‘ls -l -b’)
 vdirVerbosely list directory contents (‘ls -l -b’)
 viText Editor
 vmstatReport virtual memory statistics
W  
 wShow who is logged on and what they are doing
 waitWait for a process to complete •
 watchExecute/display a program periodically
 wcPrint byte, word, and line counts
 whereisSearch the user’s $path, man pages and source files for a program
 whichSearch the user’s $path for a program file
 whileExecute commands
 whoPrint all usernames currently logged in
 whoamiPrint the current user id and name (‘id -un’)
 wgetRetrieve web pages or files via HTTP, HTTPS or FTP
 writeSend a message to another user
X  
 xargsExecute utility, passing constructed argument list(s)
 xdg-openOpen a file or URL in the user’s preferred application.
 xxdMake a hexdump or do the reverse
 xzCompress or decompress .xz and .lzma files
 yesPrint a string until interrupted
 zipPackage and compress (archive) files
 .Run a command script in the current shell
 !!Run the last command again
 ###Comment / Remark

Basic Features of a Bash Script

Assuming you already know what a Bash shell is, we will now discuss some of the basic features of a Bash script. In Unix-like operating systems, such as Linux, a Bash script is a text file that contains a sequence of commands. These commands are executed by the Bash shell when the script is run.

A Bash script typically starts with a “#!” (shebang) followed by the path to the Bash interpreter, on the first line. The second line is often blank. The remainder of the script consists of one or more commands, each on its own line.

Comments can be added to a Bash script by starting a line with the “#” character. Anything following the “#” on that line will be ignored by the Bash interpreter. This can be useful for adding brief explanations of what particular commands do.

Variables can be declared and used within a Bash script just like in any other programming language. They are typically used to store data that will be used by various commands in the script. Variables can be assigned values when they are declared, or they can be assigned values later on using the “=” operator. For example:

MYVAR=”some value” # Assigns the value “some value” to MYVAR
echo $MYVAR # Prints out the value of MYVAR

The “echo” command is used to print out the contents of a variable (or any other text).

Functions can also be defined in a Bash script. Functions are blocks of code that can be executed just like commands. They are typically used to group together a number of related commands. For example:

myfunc() {
echo “This is my function”
}

This defines a function named “myfunc”. To execute the code in the function, we would simply type “myfunc” at the command prompt.

Bash scripts can also be run from within other programs, using the “system” or “exec” commands. This can be useful for automating tasks that need to be performed regularly.

Pros and Cons of BAsh

A Bash script is a text file containing a set of commands for a Unix-based operating system. The commands are executed in order, one after the other. Bash scripts can be used to automate tasks, such as running a set of commands at startup or shutdown.

There are several advantages to using Bash scripts. They are easy to create and edit, and they do not require any special software. Additionally, Bash scripts can be run on any Unix-based system without modification.

There are also some disadvantages to using Bash scripts. They can be difficult to debug, and they are not as portable as some other scripting languages. Additionally, Bash scripts do not have strong support for object-oriented programming.

Why use a bash script?

A bash script is a text file that contains a sequence of commands. These commands are typically used to automate tasks, such as building software or deploying websites.

Bash scripts are executed by the operating system when they are run. This means that they can be used to automate tasks that would otherwise require manual input.

Bash scripts are also portable, which means they can be run on any system that has a bash shell. This makes them ideal for use in cross-platform environments.

How do they work?

Bash scripts are short programs that are written in the Bash programming language. They are typically used to automate tasks that would otherwise be performed manually.

Bash scripts can be run from the command line or they can be called from other programs. When a Bash script is run, it is first interpreted by a program called the shell. The shell then executes the commands in the script.

Bash scripts can use any of the commands available to the Bash shell. They can also use any of the built-in functions of the Bash programming language. In addition, Bash scripts can call external programs and libraries.

Resources to Learn More About Bashing Scripts.

A bash script is a text file containing a sequence of commands for a computer to execute. They are typically used to automate repetitive tasks. Bash scripts can be used for a wide variety of purposes, including web development, system administration, and software engineering.

There are many resources available for learning more about bash scripts. Here are a few of the most popular:

The Bash Guide: This guide covers the basics of bash scripting and is a great resource for beginners.

Bash Cookbook: This book contains recipes for common bash scripting tasks. It is geared towards intermediate and advanced users.

Advanced Bash Scripting Guide: This guide covers more advanced topics in bash scripting, such as functions and arrays. It is intended for experienced users.

Linux Shell Scripting Tutorial: This tutorial covers both bash and sh scripting, and includes many examples.

Conclusion

In conclusion, a bash script is a file containing a set of commands that can be run together in order to automate a task. Bash scripts are an incredibly powerful tool that can be used to streamline almost any process on your computer. If you’re not already using them, I highly recommend giving them a try. With just a little bit of practice, you’ll be surprised at how quickly you can get up and running with bash scripting.

One Comment

  1. Thiis drsign is spectacular! You obviously know hoow too keep a reader amused.

    Between your wit aand your videos, I was almost movrd to start my oown blg
    (well, almost…HaHa!) Great job. I really enjoyed what youu had to say, and more than that,
    how you presdented it. Tooo cool!

Leave a Reply

Your email address will not be published. Required fields are marked *