본문 바로가기

OS/Linux

Redirection; Piping; File Name Expansion

Redirection

Standard Input, Output, and Error

  • standard input, output, and error for commands are sent to your terminal, unless they are redirected
    • cat - (by itself) will take input from terminal (use control-d to end input), send output and error messages to terminal
  • > will redirect standard output to a file, deleting any existing contents of the file
    • cat > temp - will redirect output to a file called temp
  • >> will redirect standard output to a file, but will append (add to) the end of the file
    • cat temp >> temp2 will append the contents of temp to the contents of temp2
  • 2> will redirect standard error to a file (note that > is the same as 1>)
  • >&2 (or 1>&2) will redirect standard output to standard error
  • >/dev/null will redirect output to a null file
    • find / -name *.tmp 2>/dev/null
  • < will redirect standard input from a file
    • mail user < temp will redirect input from a file called temp
  • << will redirect following lines to standard input, also called a "Here document"
    • cat << + will take the following lines as input, until + appears on a line by itself. + can be any combination of unique characters

Piping

  • | (pipe) will connect the standard output of the command to its left, to the standard input of the command to its right
    • ls -al | more
    • ls -al | grep "temp" | sort -rnk5
  • tee will take standard input from a pipe, and send it as output to one or more files and to its standard output
    • ls -al | tee file1 file2
  • can redirect (or tee) to the file that represents the display unit
    • ls -al | tee /dev/tty | wc -l

File Name Expansion

  • also called ambiguous file references, metacharacters, wild card characters, and filename generation characters
  • used to find filenames that match a pattern
  • ? matches any single character, eg. echo temp?2
  • * matches any number (including none) of characters, eg. ls temp*
  • a leading period (hidden file) must be explicitly specified, eg. echo * - will not show hidden files
  • [ ] matches any single character in included list, eg. ls temp[12]*
  • - within [ ] between two characters represents a range, eg. ls temp[1-58] is the same as ls temp[123458]
  • if ! is first character within [ ], then any character not in list is matched