I/O Handling in Shell Script - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

I/O Handling in Shell Script

Share This

Input

To take an input from the user, read function is used. In the following script, the value of name variable is taken from standard input device (keyboard) using the line read name

#!/bin/bash echo "Enter your name:" read name echo "Welcome $name"

Output

To print messages to the terminal, the commonly used commands are printf and echo. The command echo is generally used to print a string with very simple formatting, whereas printf provides the scope of printing highly formatted output in flexible way.

Printing a String using echo

First, we will discuss different ways of use of echo command.


#!/bin/bash echo This a program. echo 'This a program. Do you want to Test?' echo "This a program. 'Let us Test the code'"

If you have a string in one line, you can put the string just after an echo. You may or may not include it in a single or double quote.

But if you have a string written in multiple lines, you must include it in a single or double quote.

Embedding Variables

In the following example, we will discuss how to embed variables.


#!/bin/bash echo Hi $LOGNAME, your home directory is $HOME .

Including Escape Sequence

Similar to C programming language, in shell script escape sequences can be used. In the following example, we have shown how to use escape sequences in a script.


#!/bin/bash echo "Hi $LOGNAME, \nyour home directory is \t$HOME."

A Script to print files in the current directory and their types using echo


#!/bin/bash echo "File Name\tType" for i in *; do echo "$i\t\c" if [ -d $i ]; then echo "is a directory." elif [ -h $i ]; then echo "is a symbolic link." elif [ -f $i ]; then echo "is a file." else echo "is unknown." fi done

A Script to print files in the current directory and their types using printf


#!/bin/bash printf "%-32s %s\n" "File Name" "File Type" for i in *; do printf "%-32s " "$i" if [ -d "$i" ]; then echo "is a directory." elif [ -h "$i" ]; then echo "is a symbolic link." elif [ -f "$i" ]; then echo "is a file." else echo "is unknown." fi; done

Output Redirection

#!/bin/bash ls -l >> list_of_files

#!/bin/bash { uptime; date; who; } >> users_log


Redirecting to Terminal and Screen

Command tee is used to redirect output to the screen as well as the file.

#!/bin/bash { uptime; date; who; } | tee users_log


Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.