Bash 101

If you're looking to enhance your programming skills or simply want to become more efficient in using your computer, learning Bash is an excellent way to achieve that goal. Bash, short for Bourne-Again SHell, is a command-line interface (CLI) that allows you to interact with your Linux operating system using text-based commands. Yes, the thing from the hacker movie. While it may seem intimidating at first, Bash is a powerful tool that can help you perform complex tasks with ease once you get the hang of it.

One of the main benefits of learning Bash is its versatility. With Bash, you can automate repetitive tasks, manage files and directories, and even write scripts to execute complex operations. Bash is also highly customizable, allowing you to tailor your experience to your specific needs and preferences.

Moreover, Bash is installed on most Unix-based operating systems, including macOS and Linux, making it a widely accessible tool for developers, sysadmins, and power users alike. With its vast array of commands and features, learning Bash is a worthwhile investment that can pay off in productivity gains and greater control over your system.

Let's start easy and look at some essential commands first.

Essential Commands #

If you are new to Linux, here are some essential Bash commands that you should learn to get started:

These are just a few of the many Bash commands that you will use in Linux. As you become more familiar with Linux, you'll discover additional commands that will help you be more productive.

In the following more commands and control logic will be introduced throughout the sections.

Variables in Bash #

Assigning Variables #

In Bash, you can assign a value to a variable using the = operator. The variable name should be on the left side of the = operator, and the value should be on the right side. Here's an example:

name="John"
echo $name

In this example, we've created a variable called name and assigned it the value "John". We then use the echo command to print the value of the name variable to the terminal. The output will be:

John

Using Variables in Commands #

You can use variables in commands by placing the variable name inside a pair of $ symbols. For example:

greeting="Hello"
echo "$greeting, world!"

In this example, we've created a variable called greeting and assigned it the value "Hello". We then use the echo command to print a greeting to the terminal, using the value of the greeting variable. The output will be:

Hello, world!

Using Command Output as Variables #

You can also assign the output of a command to a variable using command substitution, which involves placing the command inside a pair of $() symbols. Here's an example:

timestamp=$(date +%s)
echo "The current timestamp is $timestamp"

In this example, we're using the date command to get the current timestamp, and assigning the output to a variable called timestamp. We then use the echo command to print a message to the terminal, including the value of the timestamp variable. The output will be something like:

The current timestamp is 1681010279

Exporting Variables #

If you want to make a variable available to other processes or sub-shells, you can use the export command to mark the variable for export. Here's an example:

export MY_VAR="hello"

In this example, we're creating a variable called MY_VAR and assigning it the value "hello". We then use the export command to mark the variable for export, which means it will be available to any child processes or sub-shells launched from the current shell. You can confirm that the variable has been exported by running the env command, which will display a list of environment variables currently available. You should see MY_VAR=hello in the output. You can filter the output using grep: env | grep MY_VAR.

if-Conditions #

if statements are an essential part of programming logic in Bash scripts. The most basic form of an if statement in Bash is:

if [ condition ]; then
# Commands to execute if condition is true
fi

# or

if [ condition ]
then
# Commands to execute if condition is true
fi

The [ condition ] part can be any valid Bash expression that evaluates to either true or false. If the condition is true, the commands inside the then block will be executed. Note that the then keyword must be on the next after the if statement or is separated by ;, and the fi keyword must be on a separate line.

Here is an example if statement that checks if a file exists:

if [ -e file.txt ]
then
echo "The file exists."
fi

In this example, the [ -e file.txt ] expression checks if the file file.txt exists in the current directory. If the file exists, the message "The file exists." will be printed to the terminal.

Using if-else statements in Bash #

You can also use the if-else syntax to execute different commands depending on whether the condition is true or false. The syntax for an if-else statement in Bash is:

if [ condition ]
then
# Commands to execute if condition is true
else
# Commands to execute if condition is false
fi

Here is an example if-else statement that checks if a number is positive or negative:

if [ $num -gt 0 ]
then
echo "The number is positive."
else
echo "The number is negative."
fi

In this example, the $num variable stores the value of the number to be checked. If the number is greater than zero, the message "The number is positive." will be printed, otherwise, the message "The number is negative." will be printed.

Using if-elif-else statements in Bash #

You can also use the if-elif-else syntax to execute different commands based on multiple conditions. The syntax for an if-elif-else statement in Bash is:

if [ condition1 ]
then
# Commands to execute if condition1 is true
elif [ condition2 ]
then
# Commands to execute if condition2 is true
else
# Commands to execute if all conditions are false
fi

Here is an example if-elif-else statement that checks if a number is positive, negative, or zero:

if [ $num -gt 0 ]
then
echo "The number is positive."
elif [ $num -lt 0 ]
then
echo "The number is negative."
else
echo "The number is zero."
fi

In this example, the $num variable stores the value of the number to be checked. If the number is greater than zero, the message "The number is positive." will be printed. If the number is less than zero, the message "The number is negative." will be printed. Otherwise, if the number is equal to zero, the message "The number is zero." will be printed.

Loops in Bash #

Bash provides several types of loops that you can use to execute commands repeatedly based on certain conditions. The most commonly used loops in Bash are the for loop and the while loop.

For Loop #

The for loop is used to iterate over a sequence of values, such as a range of numbers or a list of filenames. The syntax for a for loop is as follows:

for variable in sequence
do
commands
done

In this syntax, variable is a variable that is set to each value in the sequence, and commands is a placeholder for any commands to be executed for each value of in the sequence. For example, to iterate over the values 1 to 10 and print each value to the terminal, you can use the following for loop:

for i in {1..10}
do
echo $i
done

While Loop #

The while loop is used to execute a block of commands as long as a certain condition is true. The syntax for a while loop is as follows:

while condition
do
commands
done

In this syntax, condition is a test that is evaluated before each iteration of the loop, and commands is a placeholder for any commands to be executed on each iteration of the loop as long as condition is true. For example, to print the numbers from 1 to 10 using a while loop, you can use the following code:

i=1
while [ $i -le 10 ]
do
echo $i
i=$((i+1))
done

In this code, i is initially set to 1, and the loop continues as long as i is less than or equal to 10. The echo command is used to print the value of i, and i is incremented by 1 after each iteration of the loop using the $((i+1)) syntax.

sudo #

sudo is a command in Linux and other Unix-based operating systems that allows users to run commands with administrative or "superuser" privileges. The term "sudo" stands for "superuser do", which indicates that the command being executed should be run with the privileges of the superuser, or root user.

When a user executes a command with sudo, they are prompted to enter their own password (not the root user's password) to verify their identity and authorization to run the command with elevated privileges. This allows users to perform tasks that require administrative privileges without having to log in as the root user or switch to the root user's account, which can be dangerous and lead to unintentional errors or security vulnerabilities.

In general, it's a good practice to use sudo only when necessary and to limit the use of administrative privileges to tasks that require them. This can help prevent accidental damage or modifications to critical system files and configurations.

User Management #

Adding a User using Bash #

To create a new user in Bash, you can use the adduser command followed by the username of the new user. For example, to create a user named "johndoe", you would run the following command:

sudo adduser johndoe

This command will prompt you to set a password for the new user and provide some additional information, such as their full name and contact information. Once you've provided all the necessary information, the new user account will be created, and you can log in as that user using their username and password.

Adding a User to the Sudo Group #

If you need to grant administrative privileges to the new user, you can add them to the sudo group by running the following command:

sudo usermod -aG sudo johndoe

This will add the user "johndoe" to the sudo group, allowing them to run commands with administrative privileges when necessary. You can add users to any group you wish such as www-data.

Change Password on Bash #

To set a password for a user in Bash, you can use the passwd command followed by the username of the user whose password you want to set. For example, to set a password for the user "johndoe", you would run the following command:

sudo passwd johndoe

This command will prompt you to enter and confirm the new password for the user. When you enter the password, it won't be displayed on the screen for security reasons, so make sure to enter it carefully. Once you've entered the new password and confirmed it, the password will be set for the user "johndoe", and they'll be able to log in using their new password. If you're setting a password for a user other than yourself, you'll need administrative privileges, which you can obtain using the sudo command.

System Control using shutdown #

In Bash, you can use the shutdown command to shut down, reboot, or perform other power-related operations on your system. For example, to shut down your system immediately, you can run the following command with sudo privileges:

sudo shutdown -h now

The -h option stands for "halt", which means to shut down the system, and the now option specifies that the action should be taken immediately. Similarly, if you want to reboot your system, you can use the -r option instead of -h:

sudo shutdown -r now

This command will reboot your system immediately. You can also use other options with the shutdown command to schedule a shutdown or reboot at a specific time, send a message to users, and more. You can learn more about the shutdown command by typing man shutdown in your terminal.

Bash Aliases #

Aliases are custom shortcuts that you can define in your ~/bash_aliases or ~/.bashrc file (depending on the system architecture) to execute commonly used commands or command sequences. Aliases can help streamline your workflow and save time by reducing the amount of typing you need to do. They can also help you avoid typos or mistakes when entering complex commands by providing a convenient shorthand that you can easily remember.

In addition to providing a faster and more efficient way of working with the command line, aliases can also help you customize your environment to better suit your needs. For example, you can create aliases to launch specific applications or open frequently used files. You can also use aliases to set default options for commands or create your own custom commands that combine several existing commands into a single, more powerful operation.

Using aliases can also help you learn more about the command line and how it works. By creating and experimenting with aliases, you can gain a deeper understanding of how commands and options work together, and become more comfortable with the syntax and structure of Bash commands.

Overall, using aliases from your ~/bash_aliases or ~/.bashrc file can provide a significant boost to your productivity and efficiency when working with the command line. By creating custom shortcuts that suit your needs, you can save time, avoid mistakes, and gain a deeper understanding of the Bash environment.

How to use shells (bash, etc.) efficiently? #

Efficient work in shells requires a certain set of parameters. Here is what I've found very useful:

  1. Use shortcuts: Bash has several shortcuts that can save you time. For example, you can press Ctrl+A to move to the beginning of the line, Ctrl+E to move to the end of the line, and Ctrl+R to search through your command history.

  2. Use tab completion: Bash also has tab completion, which can save you time when typing long file or directory names. Simply type the first few letters of the file or directory name, and then press the Tab key to complete the name.

  3. Use aliases: You can create aliases for frequently used commands to save time. For example, you can create an alias for ls -la as ll. To create an alias, type alias ll='ls -la' in the terminal. For more check the section on using ~/.bash_aliases / ~/.bashrc files.

  4. Use command substitution: You can use command substitution to save time when using the output of one command as input to another command. For example, you can use the output of ls as input to grep by typing grep pattern $(ls).

  5. Use pipes: You can use pipes to combine multiple commands and save time. For example, you can use the output of ls as input to grep and then use the output of grep as input to wc by typing ls | grep pattern | wc -l.

  6. Use history: You can use the command history to save time when reusing commands. To view your command history, type history in the terminal. You can then use the up and down arrow keys to navigate through your history, or you can use Ctrl+R to search through your history.

  7. Use scripts: If you find yourself performing the same set of commands frequently, you can create a Bash script to automate the process. Simply create a file with the commands you want to run, and then make the file executable by typing chmod +x script.sh. You can then run the script by typing ./script.sh.

FAQ #

How to terminate a running process on bash? #

To kill a running process on Bash, you can use the kill command followed by the process ID (PID) of the process you want to terminate. You can find the PID of a running process by using the ps command. For example, to kill a process with PID 1234, type kill 1234 in the terminal. If the process is not responding to the kill command, you can use the kill -9 command followed by the PID to force the process to terminate:

$ kill -9 1234

It's important to be careful when using the kill command as it can cause data loss and other issues if used improperly.

How to change your hostname on Debian/Ubuntu Systems? #

To change the hostname on a Debian or Ubuntu system, you can use the hostnamectl command. First, log in to your system as the root user or a user with sudo privileges. Then, run the following command to set the new hostname:

sudo hostnamectl set-hostname new_hostname

Replace "new_hostname" with the desired hostname you want to set for your system. After running this command, your new hostname will be set immediately. You can verify the new hostname by running the following command:

hostname

This will load the new hostname from the /etc/hostname file and set it as the current hostname for your Ubuntu system. Overall, the process of changing the hostname on various systems is quite similar to that on Debian: Arch works the same here.

🙏🙏🙏

Since you've made it this far, sharing this article on your favorite social media network would be highly appreciated 💖! For feedback, please ping me on Twitter.

Published