Learn Bash Scripting
Bash is a Unix shell and command language
What is Bash?
Bash (Bourne Again SHell) is a command-line interpreter that executes commands from a terminal or a file. Bash scripts are plain text files that contain a series of commands to be executed sequentially. Bash scripting allows you to automate tasks in Unix-like systems by writing a series of commands in a script file.
Learning Bash
1. Creating a Bash Script
A bash script is simply a text file with executable commands. By convention, scripts have a .sh extension. A basic example of a bash script would look like:
#!/bin/bash
echo "Hello, world!"
The first line
#!/bin/bashis called a shebang. It tells the system to use Bash to execute the script.The second line is a the
echocommand, which prints text to the screen.
2. Saving and Running the Script
Save the file with the
.shextension (example,hello.sh)Make it executable by modifying the files permissions
chmod +x hello.sh
Run the script by calling
./hello.sh
or
sh hello.sh
Bash Script Basics
Variables
name="Chloe"
echo "Hello, $name"
Don’t use spaces around the = when assigning value to a variable
Use $ to reference the variable
User Input
read -p "Enter your name: " user_name
echo "Welcome, $user_name!"
Conditionals
if [ "$name" = "Chloe" ]; then
echo "That's you!"
else
echo "That's not me!"
fi
Loops
For loop:
for i in 1 2 3
do
echo "Number $i"
done
While loop:
count=1
while [ $count -le 3 }
do
echo "Count is $count"
count=$((count +1))
done
Functions
greet() {
echo "Hi, $1!"
}
greet "Chloe"
Best Practices
Use meaningful variable names.
Always quote your variables (
"${var}") when calling them to prevent issues with spaces.Include comments to explain your code:
# This is a comment
Quality of Life Improvements
The default editor in bash for most linux systems is nano. Vim/Vi is an editor that can be especially useful for editing programs like bash scripts. Generally speaking, Vim is a more intuitive text editor, and will likely save you time and sanity when editing text files. You can set your default editor to vim by calling export EDITOR=vim. Additionally, if you want to take things a step further, you can edit your commands with vim keybindings directly in the command line set -o vi and if you don’t like this change you can always revert back set -o emacs. Most .bashrc configs come with ll being an alias to "ls -l", but if it’s not already set, you can add this alias, or other aliases, to the .bashrc file alias ll="ls -l".
Challenge
Resources
Learn Shell: an interactive way to learn Bash basics.
Bash Scripting Tutorial: A beginner’s guide to Linux shell script and command line.
GNU Bash Manual: an all in one comprehensive Bash guide.
HackerRank Shell: practice your Bash knowledge by solving challenges.
learnyoubash: a work shop based on the bash-handbook.
Shell Style Guide: A more advance look at Bash shell scripting.
Missing Semester of Your CS Education: Shell tools and scripting.