Getting Started with Python for Robotics Projects

In this tutorial, we will get started with Python development for robotics projects.

Prerequisites

ROS 2 Python Style Guide

Before we get started, it is important to note that we will be following the ROS 2 Python Style Guide throughout this tutorial and future tutorials where we use Python. This guide is based on PEP 8, the official style guide for Python code, with some ROS 2-specific modifications. 

  • 4 spaces for indents
  • 100 characters max per line
  • Single quotes for strings
  • Imports at the top, grouped by type
  • snake_case for functions and variables
  • CapWords convention for class names

Adhering to these guidelines will help make sure your code is consistent with ROS 2 projects in the community that use Python.

Create a Folder to Store Your Python Code

Let’s start by creating a folder to store our Python code. Open a terminal window, and type:

mkdir -p ~/Documents/python_tutorial
cd ~/Documents/python_tutorial

Open Visual Studio Code (Optional)

For those of you who will be using Visual Studio Code for your Python development, type this:

code .

Otherwise, you can open your favorite code editor.

Configure Visual Studio Code (Optional)

Let’s configure our settings so that our code follows the ROS 2 Python Style Guide which uses the PEP8 standards.

Click on the Extensions button on the left side.

1-click-on-extensions

Type autopep8 in the search bar.

Click Install the version made by Microsoft.

Type PyLint in the search bar.

Click Install the version made by Microsoft.

Click on “File” in the top-left corner.

Select “Preferences”

Click on “Settings”.

In the search bar at the top of the Settings page, type “editor rulers” and click “Edit in settings.json”.

2-editor-rulers

Add or modify:

{
 "workbench.colorTheme": "Solarized Dark",
 "editor.fontSize": 30,
 "terminal.integrated.fontSize": 30,
 "editor.rulers": [100],
 "[python]": {
   "editor.formatOnSave": true,
   "editor.defaultFormatter": "ms-python.autopep8",
   "editor.tabSize": 4,
   "editor.insertSpaces": true
 },
 "[cpp]": {
   "editor.tabSize": 2,
   "editor.insertSpaces": true
 },
 "editor.tabSize": 2,
 "editor.insertSpaces": true,
 "files.trimTrailingWhitespace": true,
 "autopep8.args": [
   "--max-line-length",
   "100",
   "--aggressive"
 ]
}

Save and close the settings.json file.

Let’s create a new Python file with intentional style issues to test our PEP 8 compliance setup. 

To test the configuration, create a new Python file named test_formatting.py. Right-click underneath the name of the folder on the left panel: “PYTHON_TUTORIAL”.

Click “New File”.

Name the file test_formatting.py.

Press Enter.

Paste the following code with intentional style issues:

class robot:
 def __init__( self,name ):
  self.Name=name

 def greet( self ):
    print( "Hello, my name is "+self.Name )

myRobot=robot("R2D2")
myRobot.greet( )
3-before-saving

Save the file. You should immediately see some changes and warnings. Let’s examine what autopep8 has automatically fixed and what issues remain.

After saving, your code should look more like this:

4-after-saving
class robot:
    def __init__(self, name):
        self.Name = name

    def greet(self):
        print("Hello, my name is " + self.Name)


myRobot = robot("R2D2")
myRobot.greet()

autopep8 has automatically fixed several issues:

  • Corrected indentation to use 4 spaces
  • Fixed spacing around operators and after commas
  • Removed extra spaces inside parentheses

However, there are still style problems that autopep8 doesn’t address. These should be highlighted by PyLint:

  • Class name should be in CapWords format (PascalCase)
  • Variable names should be in snake_case
  • The file, class, and methods need to have docstrings, which provide an explanation of what the code does (docstrings can be added directly in VS Code by going on the line underneath the method or class, and typing “””.

To fix these remaining issues, manually update your code as follows:

"""This module defines a simple Robot class for demonstration purposes."""


class Robot:
    """Simple robot class that can greet."""

    def __init__(self, name):
        """Initialize the robot with a name."""
        self.name = name

    def greet(self):
        """Print a greeting from the robot."""
        print(f"Hello, my name is {self.name}")


my_robot = Robot("R2D2")
my_robot.greet()

After making these changes and saving the file, you should see no more warnings in the “Problems” tab at the bottom of your screen.

5-after-fixing-warnings-pylint-autopep8

By using autopep8 and PyLint in VS Code, we’ve set up an environment that helps us adhere to the ROS 2 Python Style Guide. autopep8 automatically handles many formatting issues, while PyLint provides additional guidance on style and best practices.

Remember, while these tools are extremely helpful, they don’t catch everything. It’s important to understand the principles behind the style guide and apply them as you write your code. 

In future robotics projects, this setup will help you write clean, consistent Python code that adheres to ROS 2 standards, making your code more readable and maintainable. 

Finally, let’s run the code.

Look for the “Run” button (a triangle play icon) in the top-right corner of the editor.

Click this button to run the currently open Python file.

6-run-the-code

You should get this output:

7-run-the-code-test-formatting

Hello, my name is R2D2

You can also run the file, by going to the terminal window, and typing:

python3 test_formatting.py

Creating Variables

In this section, we will learn how to create and use variables in Python.

Variables in Python are like containers; they store data values. Unlike some other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

Let’s begin. Right-click in the Explorer pane and select “New File”.

Name the file robot_variables.py, and press Enter.

In the new file, let’s start by creating our first variable:

robot_name = 'AutomaticAddison'

Here, robot_name is a variable, and we’ve assigned it the value ‘AutomaticAddison’, which is a string. 

Python knows the type of the variable based on the value it’s given. This feature is known as dynamic typing.

You can also store numbers in variables. Let’s create an integer variable and a floating-point variable:

robot_speed = 5  # This is an integer
robot_accuracy = 99.9  # This is a float

The # symbol in Python is used to create comments. Comments are notes within the code that Python ignores when running the program.

We can use variables to perform calculations. 

For example, if we want to increase the robot_speed by 3, we can do so like this:

robot_speed = robot_speed + 3
print(robot_speed)

Now run the code.

In the terminal, you’ll see the value of robot_speed printed out.

8-robot-speed-printed-out

Notice how we used the same variable to update its own value. 

Python also allows you to create multiple variables in a single line. Here’s how you can assign different robot parts to different variables simultaneously:

arm, leg, head = 'ArmBot', 'LegBot', 'HeadBot'
print(arm)
print(leg)
print(head)

Run the code.

9-run-the-code-arm-leg-head

Finally, variables can be reassigned to different data types.

For example, if we want to reassign robot_speed to a string, we can do that like this:

robot_speed = 'fast'
print(robot_speed)

Run the code again.

10-robot-speed-a-string

And just like that, robot_speed now holds a string instead of an integer.

Understanding Data Types

Let’s learn about data types in Python. 

In Python, data types are the classifications we give to different kinds of data. Understanding them helps you manage how Python will process your data. 

Let’s look at the most common data types used in Python.

In VS Code, right-click in the Explorer pane and select “New File”.

Name the file robot_data_types.py and press Enter.

First, we have integers, known as int. These are whole numbers without a decimal point. For example:

distance = 120
print(distance)

#Check the data type
print(type(distance))

Here is the output:

11-integer

Next is the floating-point number, or float, which is a number with a decimal. It’s often used in Python for more precise measurements or calculations:

speed = 25.5
print(speed)

#Check the data type
print(type(speed))
12-float

Strings, or str, are sequences of characters used for storing text. In Python, you enclose strings in quotes:

robot_name = 'AutomaticAddisonBot'
print(robot_name)

# Check the data type
print(type(robot_name))
13-string

Booleans, or bool, represent one of two values: True or False. This data type is useful when dealing with conditions in your programming:

is_active = True
print(is_active)

# Check the data type
print(type(is_active))
14-boolean

Lists are ordered collections of values that can hold a mix of data types, and they are mutable, meaning you can change their content without changing their identity:

components = ['sensors', 'motors', 'camera']
print(components)

# Check the data type
print(type(components))
14-list

Tuples are similar to lists, but they are immutable, meaning once they are created, their values cannot be changed:

dimensions = (20, 30, 40)
print(dimensions)

# Check the data type
print(type(dimensions))
15-tuple

Dictionaries, or dict, store key-value pairs and are extremely useful for storing data items like a database:

robot_specs = {'name': 'AutoBot', 'speed': 25.5}
print(robot_specs)

# Check the data type
print(type(robot_specs))
16-dictionaries

Understanding Casting

Let’s explore the concept of casting in Python. 

Casting is important when you need to specify or alter the data type of a variable in your code. This is particularly useful in robotics when you need to ensure that data types match expected parameters for functions or calculations.

In VS Code, right-click in the Explorer pane and select “New File”.

Name the file robot_casting.py and press Enter.

First, if you have a number as a string but need to perform mathematical operations, you’ll need to convert it to an integer or float:

speed_str = '30'
print(speed_str)
print(type(speed_str))

speed_int = int(speed_str)
print(speed_int)
print(type(speed_int))
17-casting

This converts the string ’30’ to the integer 30, enabling arithmetic operations.

Similarly, if you’re working with floating-point numbers but need to convert them to integers for functions that do not accept floats, you can use:

distance_float = 120.5
print(distance_float)
print(type(distance_float))

distance_int = int(distance_float)
print(distance_int)
print(type(distance_int))

Here, distance_float is converted to 120, truncating the decimal part.

18-cast-float-to-int

On the other hand, sometimes you need to perform accurate division calculations with integers. In Python, dividing two integers yields an integer result. 

To get a float result, one of the numbers must be a float. You can achieve this by casting:

length = 25
width = 4
aspect_ratio = float(length) / width

print(aspect_ratio)

This ensures aspect_ratio holds the value 6.25 rather than just 6.

19-float-casting

Lastly, let’s look at converting numbers to strings, which is common when you need to concatenate numbers to strings for messages or outputs:

age = 5
age_str = str(age)
message = 'The robot is ' + age_str + ' years old.'
print(message)

This casts the integer 5 to the string ‘5’, making it possible to construct the full message string without errors.

20-cast-string

Working with Output

Let’s see how to work with output in Python. Managing output effectively is important for debugging, monitoring the state of your robotics applications, and providing interactive user experiences. Let’s get started.

In VS Code, right-click in the Explorer pane and select “New File”.

Name the file robot_output.py and press Enter.

In Python, the print() function is the most common way to output data. Whether you’re outputting simple messages or complex data structures, print() can handle it all. Let’s look at some examples.

First, a straightforward message:

print("Hello, robot world!")

This sends the text “Hello, robot world!” to the console, which is useful for simple notifications about the program’s status.

21-hello-robot-world

You can also use the print() function to output multiple items in one line by separating them with commas:

robot_name = 'AutomaticAddisonBot'
task_status = 'active'

print('Robot Name:', robot_name, '- Status:', task_status)

This will output:

22-print-robot-status

For more complex outputs, you might want to format strings. Python’s string formatting capabilities are powerful. 

Here’s how you can use formatted string literals, also known as f-strings:

battery_level = 85
print(f'Battery Level: {battery_level}%')

This injects the value of battery_level directly into the string, making it simpler to construct detailed messages dynamically.

23-battery-level

Sometimes, you may want to redirect your output from the console to a file. This is especially useful for logging data that you want to review later. Here’s how you can do it:

with open('log.txt', 'a') as file:
    print('An error occurred', file=file)

This code snippet opens log.txt in append mode (‘a’) and writes “An error occurred” to the file instead of the console.

In the terminal window, type:

dir

You will see our new file log.txt.

That’s it for this tutorial! You’ve taken your first big step into Python programming. Thanks for following along with me, and I will see you in the next tutorial.

Keep building!

How to Install Python in Ubuntu Linux – ROS 2

In this tutorial, we’re going to walk through how to install Python on Ubuntu Linux. Whether you’re setting up your development environment for the first time or updating to the latest version, this tutorial will ensure you get Python installed correctly on your system.

Prerequisites

If you prefer learning through video rather than text, check out the YouTube video below where I walk you through the entire process step by step. Otherwise, keep reading.

I am going to start by creating a folder for all the code I will write in this tutorial.

Open a terminal window.

Type the following commands:

mkdir -p ~/Documents/python_tutorial
cd ~/Documents/python_tutorial

Let’s start by checking which version of Python we have installed.

python3 --version 

Press Enter. 

1-python-version

This command will tell you the version of Python 3 that is currently installed.

If Python 3 is not installed or if you need a different version, we can install it using Ubuntu’s package manager.

sudo apt-get update
sudo apt-get install python3 

If you also need pip, which is the Python package installer, you can install it by typing:

sudo apt install python3-pip 

After the installation has completed, you can verify that Python and pip are installed correctly by repeating the version check for Python and also checking pip by typing:

pip3 --version
2-pip

That’s it. You now have Python and pip installed on your Ubuntu system. With Python set up, you’re ready to start developing applications, including those for robotics projects.

Thanks, and I’ll see you in the next tutorial.

Top 50 Linux Terminal Commands Every Roboticist Should Know

In this tutorial, we will cover the top 50 most popular Linux commands that every roboticist should know.

When you work on robotic projects, you will use the Linux terminal all the time. Learning these essential commands will help you work more efficiently.

Please follow along and try the commands in your own Linux environment. Feel free to pause the video when you need to, and have fun experimenting.

Don’t worry about memorizing these commands. Eventually, you will know these commands by heart after you use them again and again throughout your robotics career.

Prerequisites

Ok, let’s open a terminal window, so we can get started!

If you prefer learning through video rather than text, check out the YouTube video below where I walk you through all the commands, step by step. Otherwise, keep reading.

Identifying current user with “whoami”

The first command we’ll cover is “whoami”. This simple command tells you the username of the currently logged-in user.

whoami
1-whoami

Changing directory with “cd”

The next command we’ll cover is “cd”, which stands for “change directory”. This command allows you to navigate through the filesystem by changing your current working directory.

To use “cd”, type “cd” followed by the path of the directory you want to navigate to, then press Enter. 

For example, to navigate to the “Downloads” directory in your home folder, you would type:

cd Downloads/

If you want to go back to the folder above where you are now, you can use two dots like this:

cd ..

This takes you up one level in your folders.

If you want to go to your ROS 2 workspace, you type:

cd ~/ros2_ws/

The tilde symbol ( ~) is a shortcut that means “my home folder.”

Now let’s move to the Documents folder.

cd ~/Documents/
2-cd

Creating directories with “mkdir”

The “mkdir” command is used to create new directories in the filesystem. It stands for “make directory”.

To create a new directory, type “mkdir” followed by the name you want to give the new directory, then press Enter. 

Let’s try it.

mkdir linux_tutorial

You can also create multiple directories at once by specifying multiple names separated by spaces, like this:

mkdir folder1 folder2 folder3
3-mkdir

Removing directories with “rm -rf”

The “rm -rf” command is used to delete directories.

To remove a directory, type “rm -rf” followed by the name of the directory you want to remove.

For example, 

rm -rf folder3
4-rm-rf

Creating empty files with “touch”

The “touch” command is used to create empty files in the filesystem. It can also be used to update the timestamp of existing files without modifying their contents.

To create a new empty file, type “touch” followed by the name you want to give the file, including the desired extension, then press Enter. 

For example, to create an empty text file named “new_file.txt”, you would type:

cd linux_tutorial
touch new_file.txt

You can create multiple empty files at once by specifying multiple names separated by spaces, like this:

touch file1.txt file2.txt file3.txt

Editing text files using “nano” and “gedit”

When working with text files in Linux, you can use command-line text editors like “nano” or graphical text editors like “gedit”.

To open a file with “nano”, type “nano” followed by the filename, then press Enter. 

For example, to open a file named “example.txt”, you would type:

nano example1.txt

If the file doesn’t exist, “nano” will create a new empty file with that name. You can then type your text, and use keyboard shortcuts like Ctrl+O to save and Ctrl+X to exit.

To open a file with “gedit”, type “gedit” followed by the filename, then press Enter. 

Install gedit:

sudo apt-get install gedit

Create the file:

gedit example2.txt

“gedit” provides a graphical user interface with menu options for saving and closing files.

Listing directory contents with “ls” and “dir”

The “ls” command is used to list the contents of a directory. It stands for “list”.

To list the files and directories in your current location, simply type “ls” and press Enter. This will display a plain listing of the names.

ls

The “dir” command is similar to “ls” but provides a slightly different output format.

dir
5-ls-dir

Creating a bash script

Bash scripts are files containing a series of commands that can be executed together.

To create a bash script, start by opening a new file in a text editor (like nano or gedit). Begin the script with the shebang line “#!/bin/bash” to indicate that it should be run with the bash shell.

Then, write your commands one per line. For example:

gedit basic_bash_script_example.sh

Write this code:

#!/bin/bash 
echo "Hello, world!" 
ls -l
6-bash-script

Save the file, and close gedit.

So that we can run the script, we need to make it executable using the “chmod” command with the “+x” option:

chmod +x basic_bash_script_example.sh

You can then run your script:

bash basic_bash_script_example.sh

You can also type:

./basic_bash_script_example.sh
7-basic-bash-script

Changing file permissions with “chmod”

The “chmod” command is used to change the permissions of files and directories. It stands for “change mode”.

Permissions specify who can read, write, and execute a file. They are represented by a combination of letters (r for read, w for write, x for execute) for each of the three user classes (owner, group, others).

To see the permissions, create a file now:

touch chmod_example.txt

Now type:

ls -la

To change permissions, use “chmod” followed by the desired permission settings and the filename. For example, to give everyone read, write, and execute permissions (r, w, and x, respectively), you type:

chmod 777 chmod_example.txt

Exploring the .bashrc file

The .bashrc file is a script that is executed whenever you open a new terminal window. It is located in your home directory and is used to set up your environment, define aliases, and set environment variables.

To edit your .bashrc file, you can use any text editor. For example:

gedit ~/.bashrc

Creating command aliases with “alias”

An alias is a shortcut that you can use to run a command or a series of commands. You can define aliases in your .bashrc file so that they are available every time you open a new terminal window.

To create an alias, you use the alias command followed by the name of the alias and the command(s) you want it to run.

Let’s say you want to create a quick command to build a ros2 workspace.

gedit ~/.bashrc

Write this at the bottom of the .bashrc file:

alias build='cd ~/ros2_ws/ && colcon build && source ~/.bashrc'

Save the file, and close it.

Now, whenever you want to build your ROS 2 workspace, you can type:

build
9-alias

Setting environment variables using export

Environment variables are variables that are available to all the processes running in a terminal window.

You can set environment variables in your .bashrc file so they are available every time you start a new terminal window.

To set an environment variable, use the export command followed by the name of the variable and its value.

For example, to set an environment variable called MY_VAR to the value 8, you can add the following line to your .bashrc file:

gedit ~/.bashrc

Add this at the bottom of the file.

export MY_VAR=8

Save the file, and close it.

Open a new terminal window, and verify the value of MY_VAR.

echo $MY_VAR
10-echo-my-var

Clearing terminal screen with “clear”

The “clear” command is used to clear the terminal screen, moving the prompt to the top of the screen.

Simply type “clear” and press Enter to clear the screen:

clear

This command is useful when your terminal gets cluttered with output and you want to start with a clean screen.

Exploring options with “intro to options”

Most Linux commands have options that modify their behavior. Options are specified using a dash (“-“) or double dash (“–“) followed by a letter or word.

For example, to see the help information for the “ls” command, you can use:

ls --help

Alternatively, the see the command’s manual, you can type:

man ls

Then press “q” to quit.

Determining present working directory with “pwd”

The “pwd” command is used to print the current working directory (the directory you are currently in).

To use this command, simply type “pwd” and press Enter:

pwd
11-pwd

Removing files with “rm”

The “rm” command is used to remove files.

To remove a file, type “rm” followed by the name of the file you want to remove. For example, to remove a file called “chmod_example.txt”:

cd ~/Documents/linux_tutorial/
rm chmod_example.txt

To remove a folder, add -rf (recursive + force) to the command:

clear
12-rm
dir
mkdir remove_test
dir
rm -rf remove_test
dir

Opening files or directories with “open”

The “open” command is used to open files or directories with the default application associated with that file type.

To open a file or directory, type “open” followed by the name or path of the file or directory you want to open. For example:

open ~/ros2_ws/
13-open

Moving files or directories with “mv”

The “mv” command is used to move files and directories from one location to another. It can also be used to rename files and directories.

To move a file, type “mv” followed by the name of the file you want to move and the destination directory. 

For example, to move a file called “new_file.txt” to the “Downloads” directory:

cd ~/Documents/linux_tutorial
dir
mv new_file.txt ~/Downloads/
dir

Open a new terminal to check:

cd ~/Downloads/
dir

To rename a file, type “mv” followed by the current filename and the new filename. For example, to rename “old_name.txt” to “new_name.txt”:

cd ~/Documents/linux_tutorial
touch old_name.txt
dir
mv old_name.txt new_name.txt
dir
14-mv

Copying files or directories with “cp”

The “cp” command is used to copy files and directories from one location to another.

To copy a file, type “cp” followed by the name of the file you want to copy and the destination directory. 

For example, to copy a file called “copy_example.txt” to the “Downloads” directory:

touch copy_example.txt
cp copy_example.txt ~/Downloads

Open a new terminal to check:

open ~/Downloads/

To copy a directory and its contents, use the “-r” (recursive) option:

mkdir my_cp_directory
cp -r  my_cp_directory ~/Downloads/
15-cp

Previewing beginning of files with “head”

The “head” command is used to display the first few lines of a file.

To preview the beginning of a file, type “head” followed by the name of the file. 

For example, to display the first 10 lines of a file called “head_example.txt”:

gedit head_example.txt

Type this inside the file:

# This is
# Automatic Addison
# Keep building!
# 4
# 5
# 6
# 7
# 8
# 9
# 10
# 11
# 12
# 13
# 14
# 15

Save the file, and close it.

head head_example.txt

To display the first 5 lines:

head -n 5 head_example.txt
16-head

Viewing end of files with “tail”

The “tail” command is used to display the last few lines of a file.

tail head_example.txt

Similar to “head”, you can change the number of lines displayed using the “-n” option. For example, to display the last 5 lines:

tail -n 5 head_example.txt
17-tail

Displaying current date and time with “date”

The “date” command is used to display the current date and time.

date

The output will show the current date and time in the default format.

You can customize the output format using format specifiers. For example, to display the date in the format “YYYY-MM-DD”, use:

date +"%Y-%m-%d"

Refer to the “date” command’s manual page (“man date”) for more information on available format specifiers.

man date
18-date

Redirecting standard output with “redirecting standard output”

In Linux, you can redirect the output of a command to a file instead of displaying it in the terminal. This is done using the “>” operator.

To redirect the output of a command to a file, type the command followed by “>” and the name of the file. For example, to redirect the output of the “ls” command to a file called “directory_contents.txt”:

cd ~/Documents/linux_tutorial
ls > directory_contents.txt

If the file doesn’t exist, it will be created. If the file already exists, its contents will be overwritten.

To append the output to an existing file instead of overwriting it, use the “>>” operator:

ls >> directory_contents.txt

Concatenating and displaying files with “cat”

The “cat” command is used to concatenate and display the contents of files.

To display the contents of a single file, type “cat” followed by the name of the file. 

cat directory_contents.txt
19-cat

Viewing text files with “less”

The “less” command allows you to view the contents of a text file one page at a time. “less” is particularly useful for viewing large files that don’t fit on a single screen.

less head_example.txt

Once you’re in “less”, you can navigate through the file using various keyboard shortcuts:

  • Press “Space” to go to the next page
  • Press “b” to go back one page
  • Press “q” to quit “less” and return to the terminal

Displaying text with echo

The “echo” command is used to display text or the value of variables in the terminal.

To display a simple message, type “echo” followed by the text you want to display. 

For example:

echo "I am Automatic Addison"

You can also use “echo” to display the value of environment variables. 

For example, to display the value of the “ROS_DISTRO” variable:

echo $ROS_DISTRO
20-echo

Counting words, lines, and characters with “wc”

The “wc” command is used to count the number of words, lines, and characters in a file.

wc head_example.txt

The output shows the number of lines, words, and characters in the file, in that order.

21-wc

Connecting commands with piping

In Linux, you can connect multiple commands together using pipes. The output of one command becomes the input of the next command.

To use pipes, type the first command followed by the pipe symbol (“|”), then type the next command. 

For example, to count the number of files in a directory:

ls | wc -l

In this example, the output of the “ls” command (the list of files) is piped to the “wc” command, which counts the number of lines (“-l” option).

You should see this as your output:

9

Sorting lines of text with “sort”

The “sort” command is used to sort lines of text alphabetically or numerically.

To sort the contents of a file, type “sort” followed by the name of the file. 

For example, to sort the lines in a file called “head_example.txt”:

sort head_example.txt

The output will show the sorted lines of the file.

You can also sort in reverse order.

sort -r head_example.txt

Note that this sort command will not change the actual file. It will just display the sorted output in the terminal window.

22-sort

Performing shell expansions

Shell expansions are a feature that modify the way the shell interprets and executes commands. 

Suppose you need to quickly create directories for three different projects each named for the current year:

mkdir -p Project_{A,B,C}_$(date +%Y)

This command creates directories named Project_A_2024, Project_B_2024, and Project_C_2024 in the current directory.

dir

{A,B,C} expands to create three strings: A, B, and C.

$(date +%Y) executes the date command to fetch the current year (e.g., 2024), replacing it in the command.

23-shell-expansion

Comparing files line by line with “diff”

When working on projects that involve multiple versions of files, especially in a collaborative environment, it’s essential to track and understand changes between different file versions. The diff allows you to compare two files line by line and outputs the differences between them.

Let’s create a copy of this file:

cp head_example.txt head_example_copy.txt
gedit head_example_copy.txt

Modify one of the lines in the file, and save it.

I will remove the first line “This is”.

24-diff-a

Save the file, and close it.

To use diff, simply provide the names of the two files you want to compare:

diff head_example.txt head_example_copy.txt

This command will display the lines that differ between the two files, along with symbols that indicate whether lines were added, deleted, or changed. 

25-diff-b

Lines prefixed with < indicate content present in the first file but not in the second.

Lines prefixed with > show content that is in the second file but not in the first.

Let’s take a closer look at our output.

“1d0” means:

  • The line 1 from the first file (head_example.txt)
  • Is deleted (d)
  • When compared to the very beginning (before line 1) of the second file (head_example_copy.txt)

< # This is: 

  • This line shows the content that exists in the first file but not in the second file. The < symbol indicates that this line is from the first file.

Searching for files with “find”

The “find” command is used to search for files and directories based on various criteria such as name, size, or modification time.

To search for a file by name, type “find” followed by the directory to search in and the “-iname” option with the file name pattern. 

For example, to search for a file named “head_example_copy.txt” in the Documents directory and its subdirectories:

cd ~/Documents/
find . -iname "head_example_copy.txt"

To find a folder named “folder1” in the current directory or its subdirectories, you can use the find command with a slight modification. Here’s the command you can use:

find . -type d -iname "folder1"
26-find

Searching text with “grep”

The “grep” command is used to search for specific text patterns within files.

To search for a text pattern in a file, type “grep” followed by the pattern and the file name. 

For example, to search for the word “example” in a file named “grep_example.txt”:

cd ~/Documents/linux_tutorial/
echo "This is an example line." > grep_example.txt
cat grep_example.txt
echo "Another line here." >> grep_example.txt
cat grep_example.txt
echo "One more example." >> grep_example.txt
cat grep_example.txt

Now type:

grep "example" grep_example.txt

You can even make the search case-insensitive:

grep -i "EXAMPLE" grep_example.txt

The output will show the lines in the file that contain the search word.

27-grep

Estimating file space usage with “du”

The “du” command is used to estimate the disk space used by files and directories.

To display the disk space used by a specific file or directory, type “du” followed by the file or directory name. 

For example:

du -h ~/ros2_ws/

The output will show the disk space used by each file and subdirectory within “my_directory”, as well as the total disk space used by the directory.

28-du

Displaying filesystem space usage with “df”

The “df” command is used to display information about the disk space usage of filesystems.

To display the disk space usage of all mounted filesystems, simply type “df”:

df -h
29-df-h

Viewing command history with “history”

The “history” command is used to display a list of previously executed commands in the current shell session.

To view the command history, type “history”:

history
30-history

Displaying process status with “ps”

The “ps” command is used to display information about running processes.

To display the processes associated with the current shell session, type “ps”:

ps

The output will show the process ID (PID), terminal, CPU time, and command name for each process.

To display all processes running on the system, use the “-e” option:

ps -e
31-ps

Displaying system resource usage with “top”

The “top” command is used to display real-time information about system resource usage and running processes.

To start “top”, simply type “top”:

top

Press “q” to quit “top”

Press “M” to sort processes by memory usage (i.e. Shift + M)

Press “P” to sort processes by CPU usage (i.e. Shift + P)

32-top

Terminating processes with “kill” and “killall” 

The “kill” command is used to send a signal to a process, typically to terminate it, while the “killall” command is used to send a signal to all processes with a specified name.

To terminate a process with “kill”, type “kill” followed by the process ID (PID). For example, to terminate a process with PID 1234:

kill 1234

To terminate all processes with a specific name using “killall”, type “killall” followed by the process name. For example, to terminate all processes named “firefox”:

Start firefox.

firefox

Check out the processes:

top

Close firefox.

killall firefox

Display background processes with “jobs”

The “jobs” command is used to display a list of background processes started by the current shell session, while the “bg” and “fg” commands are used to manage these processes.

To start a process in the background, append an ampersand (“&”) to the end of the command. 

For example, let’s start the sleep command as a background process:

<command> &

Becomes:

sleep 100 &

To list the background processes, type “jobs”:

jobs

Each process will be displayed with a job number and its status (e.g., “Running” or “Stopped”).

33-jobs

Managing background processes with “bg,” and “fg”

To bring a background process to the foreground, type “fg” followed by the job number. 

For example, to bring job 1 to the foreground:

fg %1

To send a foreground process to the background, press “Ctrl+Z” to suspend it, then type “bg” to resume it in the background:

bg
34-bg-fg

Compressing files with “gzip”

The “gzip” command is used to compress files to reduce their size.

To compress a file, type “gzip” followed by the file name. 

For example, to compress a file named “grep_example.txt”:

cd ~/Documents/linux_tutorial
touch grep_example.txt
gzip -k grep_example.txt
dir

The compressed file will have the extension “.gz” added to its name, e.g., “grep_example.txt.gz”.

dir
35-gzip

Decompressing files with “gunzip”

The “gunzip” command is used to decompress files that were compressed with “gzip”.

To decompress a file, type “gunzip” followed by the file name. 

For example, to decompress a file named “grep_example.txt.gz”:

gunzip -k grep_example.txt.gz

The decompressed file will have the “.gz” extension removed from its name.

36-gunzip

Archiving and extracting files with “tar”

The “tar” command is used to create and extract archive files, which are collections of multiple files and directories combined into a single file.

For example, to create an archive named “archive.tar” containing the files “file1.txt” and “file2.txt”:

touch tar_example_file1.txt tar_example_file2.txt
tar cf archive.tar tar_example_file1.txt tar_example_file2.txt
dir
37-tar

Now remove the files:

rm tar_example_file1.txt tar_example_file2.txt 

To extract the contents of a tar archive, type “tar” followed by the “xf” options and the archive file name. 

For example, to extract the contents of an archive named “archive.tar”:

tar xf archive.tar

The files and directories will be extracted into the current directory.

Building and executing commands with “xargs”

The “xargs” command is used to build and execute commands from standard input.

A common use case for “xargs” is to pass the output of one command as arguments to another command. 

Let’s create a test environment for this command:

mkdir xargs_test && cd xargs_test
touch file1.txt file2.txt file3.txt

Use xargs to list file contents:

echo file1.txt file2.txt file3.txt | xargs cat

Add content to files:

echo "Hello" > file1.txt
echo "World" > file2.txt
echo "Xargs" > file3.txt

Run the command again:

echo file1.txt file2.txt file3.txt | xargs cat
38-xargs

This basic demonstrates how xargs takes input from one command and uses it as arguments for another. 

Now let’s go back to the previous directory.

cd ..

Creating symbolic links with “ln”

The “ln” command is used to create links between files. There are two types of links: hard links and symbolic (soft) links.

To create a symbolic link, type “ln” with the “-s” option, followed by the source file and the link name. 

For example:

touch symbolic_link_example.txt
ln -s symbolic_link_example.txt my_test_link

The symbolic link “my_test_link” will point to “symbolic_link_example.txt”. 

When you access “my_test_link”, it will redirect you to the contents of “symbolic_link_example.txt”.

Symbolic links can point to files or directories on different filesystems, and they will continue to work even if the source file is moved or deleted.

Now let’s test this symbolic link by adding some text to the original file:

echo "Hello, World!" > symbolic_link_example.txt
cat my_test_link
39-symbolic-link

Replacing Words with “sed”

The “sed” command is used to modify text in a file or input stream. You can use “sed” to replace occurrences of a word or phrase with another:

cd ~/Documents/linux_tutorial
echo "The old_word is here. Another old_word is there." > test.txt
cat test.txt
sed -i 's/old_word/new_word/g' test.txt
cat test.txt
40-sed

Executing commands with superuser privileges with “sudo”

The “sudo” command is used to execute commands with superuser (root) privileges.

To execute a command with superuser privileges, type “sudo” followed by the command. 

For example, to update the package list on an Ubuntu system:

sudo apt-get update

You will be prompted to enter your user password. Once authenticated, the command will run with superuser privileges.

The “sudo” command grants temporary superuser privileges for a single command, without the need to switch to the root account.

Changing user password with “passwd”

The “passwd” command is used to change a user’s password.

To change your own password, simply type “passwd”:

passwd

You will be prompted to enter your current password, then prompted to enter and confirm the new password.

Modifying file ownership with “chown”

To demonstrate the use of chown, let’s create a test file:

cd ~/Documents/linux_tutorial
touch chown_example.txt

To see the current owner of the file, use the ls command with the -l option:

ls -l chown_example.txt

To change the owner of a file, use “chown” followed by the new owner and the file name. 

For example, to change the owner of “chown_example.txt” to root:

sudo chown root chown_example.txt

You’ll be prompted for your password. After entering it, check the new ownership:

ls -l chown_example.txt
41-chown

We’ve learned many important Linux commands for robotics in this tutorial.

I hope this guide helps you feel more confident using Linux, and remember, all great roboticists started as beginners too – so keep practicing, stay curious, and enjoy your robotics journey.

Keep building!