Input, output and redirection
echo, read and command substitution — then the three file descriptors every program has, and how > , 2>&1 and | rewire them.
- Read user input and substitute command output into a string
- Quote variables so paths with spaces survive
- Redirect stdout and stderr, and predict the effect of their order
#!/bin/bash
echo "Today is " `date`
echo -e "\nEnter the path to directory"
read the_path
echo -e "\nYour path has the following files and folders: "
ls ${HOME}/$the_path
The first line, the shebang, tells the system which interpreter runs the file when it is executed directly. `date` is command substitution: the command runs and its output is pasted in. The modern spelling $(date) does the same and nests cleanly, so prefer it. read the_path stores one line of input in a variable, and echo -e interprets the \n escapes.
Quote your variables
The last line has a quiet bug. Bash expands $the_path and then splits the result on spaces. Entering My Docs makes ls receive two arguments:
ls: cannot access '/home/…/My': No such file or directory
ls: cannot access 'Docs': No such file or directory
Double quotes keep an expansion as one word: ls "${HOME}/${the_path}". The rule of thumb is to quote every expansion unless you specifically want splitting — it fixes the most common class of shell bugs.
Three file descriptors
Every process starts with three open files: 0, standard input (the keyboard, where read gets its line), 1, standard output (where echo writes) and 2, standard error (where error messages go). Both outputs start on the terminal, which is why they look alike, but they are separate and can be sent to different places. The repository’s file.txt and output.txt look like directory listings captured with ls > file.txt: each one lists its own name, because the shell creates the output file before ls even starts.
Bash applies redirections left to right, and 2>&1 means “make fd 2 point where fd 1 points right now”. So the two orders differ, as running them confirms:
| Command | Terminal | out.txt |
|---|---|---|
f > out.txt 2>&1 | — | out, err |
f 2>&1 > out.txt | err | out |
f &> out.txt | — | out, err |
f 2> /dev/null | out | — |
f piped into tr a-z A-Z | err, OUT | — |
A pipe | connects only stdout to the next command’s stdin; error messages still reach the terminal untouched. |& (or 2>&1 |) sends both. Use >> instead of > to append rather than overwrite.
Try it yourself. Fix the quoting in input_output.sh and test it with a folder whose name contains a space. Then run ls /etc /nonexistent > ok.txt 2> err.txt and check which file got which line. Finally, predict and check the output of ls /nonexistent 2>&1 | wc -l against ls /nonexistent | wc -l.