Working with Paths and Command Substitution
In this step, you will learn how to use the echo
command with command substitution to display the output of other commands.
Command Substitution in Echo
Command substitution allows you to replace a command with its output. This is done using the syntax $(command)
. When the shell encounters this structure, it executes the command inside the parentheses and replaces the entire $(command)
with the output of the command.
Let's use command substitution to display your current working directory:
echo "Current directory: $(pwd)"
When you run this command, you should see output similar to:
Current directory: /home/labex/project
In this example, $(pwd)
is replaced with the output of the pwd
command, which displays your current working directory.
Saving Output to a File
You can also redirect the output of the echo
command to a file instead of displaying it on the screen. This is done using the redirection operator >
.
Let's create a file called path_info.txt
in your project directory that contains information about your current location:
cd ~/project
echo "Current path: $(pwd)" > path_info.txt
This command will create a file named path_info.txt
in your project directory with the content "Current path: /home/labex/project" (or whatever your current path is).
To verify the content of the file, you can use the cat
command:
cat path_info.txt
You should see output similar to:
Current path: /home/labex/project
The >
operator redirects the output of the echo
command to the specified file. If the file already exists, it will be overwritten. If you want to append to an existing file instead of overwriting it, you can use the >>
operator.
For example, let's add the date and time to our file:
echo "Current date and time: $(date)" >> path_info.txt
Now check the content of the file again:
cat path_info.txt
You should see both lines:
Current path: /home/labex/project
Current date and time: Wed Jan 5 10:15:30 UTC 2023
(The actual date and time will reflect your system's current date and time.)