Skip to main content
Engineering LibreTexts

05-D.7: Handling Text Files - echo/printf

  • Page ID
    32211
  • EXAM OBJECTIVES COVERED
    2.3 Given a scenario, create, modify, and redirect files.

    Now that we have learned how to use various commands to manage our files, let's look at how we can process text files in various ways. An introduction to many of the command-line tools for text manipulation is important to those interested in growing in their knowledge and use of Linux.

    The echo Command

    The echo command is used to display a line of text that is passed as an argument. This is a built-in command that is mostly used in shell scripts and batch files to output status text to the screen or a file.

    Syntax :

    echo [ OPTIONS ] [string]
    

    Echo has a few options, but usually it is simply used by itself.

    Linux terminal showing usage of the echo command. Echo simply outputs the arguments back to the display

     

    Figure \(\PageIndex{1}\): Linux echo Command. ("echo command" by Patrick McClanahan is licensed under CC BY-SA 4.0)

    The first line simply repeats what is given on the command line - it "echoes" the text.

    The -e option allows the use of certain special backslash characters. In this example we see the \b, which stand for a backspace - this takes out the space just to the left of the \b.

    The printf Command

    The printf command is very similar to echo. This command is exactly the same as the printf command in the C programming language. It is used at times in Linux shell scripts, but is a bit more complex. However printf does provide some great options for outputting information that needs formatting.

    Linux terminal showing the usage of printf - it is similar to the echo command, but has many more formatting options.
    Figure \(\PageIndex{1}\): The printf Command. ("printf command" by Patrick McClanahan is licensed under CC BY-SA 4.0)

    The example above might be a bit confusing since we have not talked about shell scripts. The variable "name" is assigned a value, then the printf interprets the %s as saying "look at the next variable ($name) and interpret it as a string" (the %s says string - a %d says a decimal integer, %f is a floating point value). There are some good references on the web if you want to learn more about this command.

    • Was this article helpful?