However, in some instances, you may encounter a scenario where you have a long command. In bash, long commands do not affect the functionality of the tool. However, they are not easy to read.
In this quick tutorial, we shall discuss how to format a long command to span multiple lines. Splitting a long command into multiple lines makes the commands more readable and easy to edit.
How to Use Bash Backslash To Split Long Commands
To split long commands into readable commands that span multiple lines, we need to use the backslash character (\). The backslash character instructs bash to read the commands that follow line by line until it encounters an EOL.
The example below shows how to write a long command into multiple lines making it easier to read.
> awk ‘{print $6}’ | \
> sort -u
In the command above, we split multiple commands into individual lines. This way, we can see what each command is doing and modify it quickly if the need arises.
It is good to note that you can also use pipelines to split commands in the example above. However, this is not universally applicable as the following commands might not support input from pipes.
NOTE: Do not enclose the backslash in quotes or include whitespaces before it.
We can also apply the method above to a bash script. Using backslash, we can span a command into multiple lines making it more readable.
Here’s is an example use case:
zstd -z \
--ultra \
-r --rm \
--format=zstd *
exit_code=$?
if [$exit_code -eq 0]; then
echo “Success”
else
echo “Fail”
fi
In the example above, we use backslash characters to span the options of the zstd command to multiple lines.
Conclusion
In this short tutorial, we discussed the basics of the backlash characters in bash and how we can span long commands into multiple lines. To learn more about bash and bash scripting, consider the documentation.