07. Shell Script Input and Output
🚀 Master shell scripting I/O! Learn to handle user input, manage standard streams, work with command-line arguments, and perform file I/O operations. Become a shell scripting pro! 🥇
What we will learn in this post?
- 👉 Reading User Input in Shell
- 👉 Standard Input, Output, and Error in Shell
- 👉 Working with Command-Line Arguments
- 👉 Handling Output in Shell Scripts
- 👉 File Input and Output Operations
- 👉 Conclusion!
Reading User Input with read
🗣️
Understanding the read
Command
The read
command is your friend when building interactive shell scripts. It pauses your script, waits for the user to type something, and stores that input into a variable.
Basic Usage
1
2
read name
echo "Hello, $name!"
This simple script prompts the user to type something and then prints a greeting using the input.
Input Validation 🛡️
Let’s make it smarter! We can check if the user entered something valid:
1
2
3
4
5
6
read -p "Enter your age: " age
if [[ "$age" =~ ^[0-9]+$ ]]; then
echo "You are $age years old."
else
echo "Invalid input. Please enter a number."
fi
This uses a regular expression (^[0-9]+$
) to ensure the input is only numbers.
Flowchart
graph TD
A["🚀 Start"] --> B{"⌨️ Read User Input"};
B -- "✅ Valid Input" --> C["🔄 Process Input"];
B -- "❌ Invalid Input" --> D["⚠️ Error Message"];
C --> E["🏁 End"];
D --> B;
%% Custom Styles
classDef startStyle fill:#FFD700,stroke:#B8860B,color:#000000,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
classDef decisionStyle fill:#1E90FF,stroke:#00008B,color:#FFFFFF,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
classDef processStyle fill:#32CD32,stroke:#006400,color:#FFFFFF,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
classDef errorStyle fill:#FF6347,stroke:#B22222,color:#FFFFFF,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
classDef endStyle fill:#20B2AA,stroke:#008B8B,color:#FFFFFF,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
%% Apply Classes
class A startStyle;
class B decisionStyle;
class C processStyle;
class D errorStyle;
class E endStyle;
Key Points:
read
stores input in a variable.- Use
-p
for a prompt message. - Combine
read
with conditional statements (if
,while
) for validation.
For more information on Bash scripting and regular expressions, check out:
Remember to always test your scripts thoroughly! 😊
Standard Input/Output/Error Streams 🎉
Programs communicate using three streams:
Standard Input (stdin) ➡️
stdin
is where a program receives data. Think of it as the program’s “inbox”. By default, it’s your keyboard.
Standard Output (stdout) ➡️
stdout
is where a program sends its normal output. It’s the program’s “reply”. By default, it’s your terminal screen.
Standard Error (stderr) ⚠️
stderr
is for error messages and diagnostics. It’s like a separate “error report”. Also displayed on your terminal by default.
Redirection 🔄
We can change where these streams go using redirection:
Output Redirection
>
: Overwrites a file.command > output.txt
sendsstdout
tooutput.txt
.>>
: Appends to a file.command >> output.txt
addsstdout
tooutput.txt
.
Error Redirection
2>
: Redirectsstderr
.command 2> error.txt
sendsstderr
toerror.txt
.2>>
: Appendsstderr
.&>
: Redirects bothstdout
andstderr
to the same place.command &> output.txt
sends both tooutput.txt
.
Example:
1
2
ls nonexistantfile 2> error.log # sends error about missing file to error.log
myprogram > output.txt 2>&1 #send both stdout and stderr to output.txt
For more info: Learn more about I/O redirection (GNU Bash manual)
Handling Command-Line Arguments in Shell Scripting 🎉
Understanding the Special Variables
Shell scripts access command-line arguments using special variables:
$1
,$2
,$3
… represent the first, second, third arguments, and so on.$@
holds all arguments as separate words.$#
gives the total number of arguments.
Example: Simple Argument Processing
1
2
3
4
#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"
echo "Total arguments: $# "
This script prints the first two arguments and the total number of arguments.
Using shift
for Dynamic Processing
The shift
command removes the first argument and shifts the remaining arguments to the left. This enables processing arguments dynamically.
Example: Iterating Through Arguments
1
2
3
4
5
#!/bin/bash
while [ $# -gt 0 ]; do
echo "Processing argument: $1"
shift
done
This script iterates through all arguments, printing each one.
Example using $@
1
2
#!/bin/bash
echo "All arguments: $@"
This script prints all arguments as a single line. Note the difference in output between $@
and $*
.
Remember: Always check for the correct number of arguments using $#
to avoid errors.
For more information:
[Further exploration of advanced shell scripting techniques is encouraged. This will greatly enhance your skills!]
Formatting Output in Shell Scripts 💻
Using echo
, printf
, and tput
We can jazz up our shell script output using these three commands!
echo
for basic output
echo
is simple for printing text: echo "Hello, world!"
printf
for formatted output
printf
offers more control. For example, printf "%s is %d years old\n", "Alice", 30
prints “Alice is 30 years old”. \n
adds a newline.
tput
for terminal manipulation
tput
lets us control the terminal’s appearance. For color, we can use codes like tput setaf 1
(red) and tput sgr0
(reset). Example: tput setaf 1; echo "Error!"; tput sgr0
Example: Color-coded output
1
2
tput setaf 2; echo "This is green!"; tput sgr0
tput setaf 1; echo "This is red!"; tput sgr0
Remember to check your terminal’s color codes!
Learn more: Tput man page Printf format codes
This is a basic overview. Explore further for advanced formatting techniques! ✨
Shell Scripting File I/O 💾
Writing to Files ✍️
To write to a file, use the >
(overwrite) or >>
(append) redirection operators with echo
.
echo "Hello, world!" > myfile.txt
overwritesmyfile.txt
with “Hello, world!”.echo "More text!" >> myfile.txt
appends “More text!” tomyfile.txt
.
Logging Example
1
echo "$(date) - Application started" >> app.log
Reading from Files 👓
Use cat
to display file contents:
cat myfile.txt
displays the content ofmyfile.txt
on the terminal.
Configuration File Example
1
2
config_value=$(cat config.txt)
echo "The config value is: $config_value"
(Assumes config.txt
contains a single value).
Appending Content ➕
The >>
operator is perfect for adding log entries or updating configuration files without erasing existing data. For example, adding a new user to a user list file.
graph TD
A["📝 echo 'text' > file.txt"] --> B{"⚠️ Overwrites file.txt"};
C["✍️ echo 'more text' >> file.txt"] --> D{"➕ Appends to file.txt"};
E["📖 cat file.txt"] --> F{"👀 Displays file contents"};
%% Custom Styles
classDef commandStyle fill:#FFD700,stroke:#B8860B,color:#000000,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
classDef warningStyle fill:#FF6347,stroke:#B22222,color:#FFFFFF,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
classDef appendStyle fill:#32CD32,stroke:#006400,color:#FFFFFF,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
classDef displayStyle fill:#1E90FF,stroke:#00008B,color:#FFFFFF,font-size:14px,stroke-width:3px,rx:15px,shadow:5px;
%% Apply Classes
class A commandStyle;
class B warningStyle;
class C commandStyle;
class D appendStyle;
class E commandStyle;
class F displayStyle;
Conclusion
Hope this helped! This was fun to write, and I hope it was fun to read! What do you want to read next? Drop your ideas below! ✍️💡