Showing posts with label Linux. Show all posts
Showing posts with label Linux. Show all posts

Monday, May 27, 2013

UNIX: Terminal, File System, Users and Editors


1.  Command-line "Terminal"

You can provide additional options to a command; you can pipe the output of one command into another command; you can put a set of commands in a script to automate a task.
bash (Bourne Again Shell)
$ pwd  //print working dir 
.......

2.  Unix File System

Root Directory
Everything in Unix is a file - data files. Files are organized in directories (aka folders). The directories are organized in a hierarchical tree structure, starting from the root directory. 
"/usr/lib/jvm/jdk1.7.0_07/bin/javac". The leading "/" (forward slash) denotes the root directory. The sub-directories are also separated by a "/".
There is only one root directory for the entire Unix's file system.
Notes: Windows use "\" (back slash) as the directory separator, and may contain multiple root directories - one for each drive (e.g., c:\, d:\).
one root dir in UNIX
multiple root dir in Windows, 
Home Directory
Unix is a multi-user operating system. home directory (for each user). The users' home directories are allocated under /home for Ubuntu.  The home directory of the current login user is denoted as "~". It contains sub-directories such as ~/Desktop, ~/Downloads, ~/Documents, ~/Movies,~/Music, and etc.
Pathname and Filename
To reference a file, you need to provide the pathname (directory and sub-directories names) and the filename. For example, in "/usr/lib/jvm/jdk1.7.0_07/bin/javac", the pathname is "/usr/lib/jvm/jdk1.7.0_07/bin/" and the filename is "javac".
The pathname can be specified in two ways:
  1. Absolute Pathname: An absolute path begins from the root directory (starts with "/"), and contains all the sub-directories (separated with "/") leading to the file, e.g., "/usr/lib/jvm/jdk1.7.0_07/bin/" (starting with root). An absolute path can also begin with the current user's home directory (starts with "~"), e.g., "~/Downloads/jdk" (starting with home dir). Suppose the current user is "peter", it maps to "/home/peter/Downloads/jdk" (in Linux).
  2. Relative Pathname: A relative path is relative to the so-called current working directory (pwd). A relative path does not begin with "/" or "~". For example, if the current working directory is "/usr/lib/jvm", then the relative pathname "jdk1.7.0_07/bin" refer to "/usr/lib/jvm/jdk1.7.0_07/bin".
Unix system is case sensitive, a rose is NOT a Rose, and is NOT a ROSE.

3.  Basic Commands

3.1  pwd (Print Current Working Directory)

3.2  cd (Change Working Directory)

To change current working directory, issue command "cd new-pathname" (change directory). You can specify new pathname in two ways: absolute or relative. An absolute path begins with a "/" (root directory) or "~" (home directory). A relative path is relative to the current working directory and does NOT begin with "/" or "~". For example,

3.3  ls (List Directory's Contents)

You can use command ls to list the contents of the current working directory, e.g.,
// List contents of current working directory in short format
$ ls
Desktop    Downloads         Music     Public     Videos
Documents  examples.desktop  Pictures  Templates
 
// List in long format
$ ls -l
total xx
drwxr-xr-x 2 myuser myuser 1024 Mar 22 21:32 Desktop
drwxr-xr-x 2 myuser myuser 1024 Mar 22 21:32 Documents
drwxr-xr-x 2 myuser myuser 1024 Mar 22 21:32 Downloads
-rw-r--r-- 1 myuser myuser 8445 Mar 22 17:30 examples.desktop
......
 
// Append file indicator (e.g., trailing / indicates a directory)
$ ls -F
Desktop/    Downloads/        Music/     Public/     Videos/
Documents/  examples.desktop  Pictures/  Templates/
Wildcard *
You can list selected files using wildcard *, which matches 0 or more (any) characters. For example,
$ ls *.java     // List files ending with ".java" in short format (default)
$ ls -l *.java  // List files ending with ".java" in long format
$ ls -ld my*     // List files and directories beginning with "my" in long format


3.4  cat, less (Viewing File Contents)

You can use commands cat, less or more to display contents of a text file on console. cat shows the entire file, which can be inconvenient for long file. less shows one page of the file. For example,
$ cat /proc/cpuinfo
  // Display the entire file
  // Use window's scroll-bar to scroll
 
$ less /proc/cpuinfo
  // Display one page of the file
  // Use Up|Down|PgUp|PgDown key to scroll, and press "q" to quit


3.5  Shortcut Keys - IMPORTANT

Previous Commands: You can use the up/down arrow keys to retrieve the previous/next command in the command history.
Copy/Paste:
  • Copy: shift+ctrl+c
  • Copy: shift+ctrl+v
  • middle-button: copy, paste, highlight
  • interrupt signial: ctrl+c
  • end of text input: ctrl+d
  • suspending current process: ctrl+z 

3.6  Other Frequently-used Commands

$ clear                // Clear Screen
$ who                  // List all login users
$ whoami               // Show the current login user
$ which program-name   // Show the location of the program, e.g., "which javac"

3.7  Getting Helps

$ help                // Show all the available commands
$ help command-name   // Show help for a specific command, e.g., "help cd"
$ man command-name    // Show the manual page for a specific command, e.g., "man cd"

4.  If you need to Install Software or Perform System tasks...

4.1  Regular Users vs. Superuser


To enable a user to sudo:
  • In Ubuntu: System Settings ⇒ User Accounts ⇒ Select the user ⇒ Unlock ⇒ Set the account type to "Administrator" (instead of "Standard User"), which adds the user to "sudo" group.

4.2  Processes

Unix is a multi-process, multi-user operating system. It can run many processes concurrently.
You can use GUI applications to view all running processes and terminate a particular process (similar to "Task Manager" in Windows).
  • In Mac OS X: launch "Activity Monitor" (Under /Applications/Utilities) and select "All Processes".
On command-line, you can use command ps to list all the processes and kill to terminate a particular process:
$ ps            // Print processes of current user
$ ps -e         // Print all processes
$ ps -ef        // Print all processes in full-listing
$ ps -ef | grep "mysql"  // Print processes containing mysql
$ ps aux | grep "mysql"  // same as above
$ top           // Display resource usage and top processes
 
$ kill pid      // Kill a particular possess with the given processID
$ kill -9 pid   // Force kill
in Windows: taskkill

5.2  Display Text files in Command-line - cat, less, head and tail

If possible, use a graphical text editor to display a text file. Nonetheless, you can use the following commands to display a text file in command-line:
  • cat filename: Concantenate file or print the file to console.
  • less filename: Display the file in pages. You can scroll the display with up, down, pageup, pagedown keys. less replaces the legacy more.
  • head|tail filename: Display the first|last part of the file.
For example, let's display the /proc/cpuinfo file with these commands:
$ cat /proc/cpuinfo
   // Show entire file
   // Use the window's scroll-bar to scroll
 
$ less /proc/cpuinfo
   // Show one page
   // Use the Up|Down|PgUp|PgDown key to scroll
 
$ head /proc/cpuinfo
   // Show first page of the file
 
$ tail /proc/cpuinfo
   // Show last page of the file
More on cat
The command cat has many usages. You can use cat to concatenate (join) a few files. For example,
$ cat file1 file2 file3
   // display file1, file2 and file3 on the console
 
$ cat file1 file2 file3 > file4
   // Concatenate file1, file2 and file3 as file4
You can also use cat command to create a small text file. cat without argument uses standard input as its input. You could use ctrl+D to signal EOF. For example:
$ cat > out.txt
The quick brown fox jumps over the lazy dog[ctrl+D]
$ cat out.txt
The quick brown fox jumps over the lazy dog

done 

Friday, December 7, 2012

bash notes

no space for declare variable




#!/bin/bash
# declare STRING variable
STRING="Hello World"
#print variable on a screen
echo $STRING
date command ?
#!/bin/bash
 OF=myhome_directory_$(date +%Y%m%d).tar.gz
 tar -czf $OF /home/linuxconfig
function
#!/bin/bash
#Define bash global variable
#This variable is global and can be used anywhere in this bash script
VAR="global variable"function bash {
#Define bash local variable
#This variable is local to bash function only
local VAR="local variable"
echo $VAR
}
echo $VARbash
# Note the bash global variable did not change
# "local" is bash reserved word
echo $VAR

passing arguments
#!/bin/bash
# use predefined variables to access passed arguments
#echo arguments to the shell
echo $1 $2 $3 ' -> echo $1 $2 $3'

# We can also store arguments from bash command line in special array
args=("$@")
#echo arguments to the shell
echo ${args[0]} ${args[1]} ${args[2]} ' -> args=("$@"); echo ${args[0]} ${args[1]} ${args[2]}'

#use $@ to print out all arguments at once
echo $@ ' -> echo $@'

# use $# variable to print out
# number of arguments passed to the bash script
echo Number of arguments passed: $# ' -> echo Number of arguments passed: $#' 
/arguments.sh Bash Scripting Tutorial 
Executing Shell Command
echo `some command`  
#use backtick

Bashtrap
#!/bin/bash
# bash trap command
trap bashtrap INT
# bash clear screen command
clear;
# bash trap function is executed when CTRL-C is pressed:
# bash prints message => Executing bash trap subrutine !
bashtrap()
{
    echo "CTRL+C Detected !...executing bash trap !"
}
# for loop from 1/10 to 10/10
for a in `seq 1 10`; do
    echo "$a/10 to Exit." 
    sleep 1;
done
echo "Exit Bash Trap Example!!!" 
why there is ;


Array
#!/bin/bash
#Declare array with 4 elements
ARRAY=( 'Debian Linux' 'Redhat Linux' Ubuntu Linux )
# get number of elements in the array
ELEMENTS=${#ARRAY[@]}

# echo each element in array 
# for loop
for (( i=0;i<$ELEMENTS;i++)); do
    echo ${ARRAY[${i}]}
only bash can support array. 
sh does not support array

bash xxx.sh
sh xxx.sh


$ chmod +x hello_world.sh 
$ chmod -x hello_world.sh 
Read file
Integer valueName
0Standard input (stdin)
1Standard output (stdout)
2Standard error (stderr)
#!/bin/bash
# Declare array
declare -a ARRAY
# Link filedescriptor 10 with stdin
exec 10<&0  
# stdin replaced with a file supplied as a first argument
exec < $1 bash filein.sh XXX.txt
let count=0

while read LINE; do

    ARRAY[$count]=$LINE
    ((count++))
done

echo Number of elements: ${#ARRAY[@]}
# echo array's content
echo ${ARRAY[@]}
# restore stdin from filedescriptor 10
# and close filedescriptor 10
exec 0<&10 10<&-
exec fd<file
exec fd>file

fd< file -- Opens file for input with file descriptor fd.
fd> file -- Opens file for output with file descriptor fd.d
linuxconfig.org $ cat bash.txt 
Bash
Scripting
Tutorial
Guide
linuxconfig.org $ ./bash-script.sh bash.txt 
Number of elements: 4
Bash Scripting Tutorial Guide
linuxconfig.org $ 

9. Bash if / else / fi statements

9.1. Simple Bash if/else statement

Please note the spacing inside and outside the [ and ] brackets! Without the spaces, it won't work!
#!/bin/bash
directory="./BashScripting"

# bash check if directory existsif [ -d $directory ]; then       if_[_-d $directory_]; then           
 echo "Directory exists"
else 
 echo "Directory does not exists"fi 
Bash if else fi statement

9.2. Nested if/else

#!/bin/bash
 
# Declare variable choice and assign value 4
choice=4
# Print to stdout
 echo "1. Bash"
 echo "2. Scripting"
 echo "3. Tutorial"
 echo -n "Please choose a word [1,2 or 3]? " #no /n
# Loop while the variable choice is equal 4
# bash while loop
while [ $choice -eq 4 ]; do
 
# read user input
read choice
# bash nested if/else
if [ $choice -eq 1 ] ; then
 
        echo "You have chosen word: Bash"

else                   

        if [ $choice -eq 2 ] ; then
                 echo "You have chosen word: Scripting"
        else
         
                if [ $choice -eq 3 ] ; then
                        echo "You have chosen word: Tutorial"
                else
                        echo "Please make a choice between 1-3 !"
                        echo "1. Bash"
                        echo "2. Scripting"
                        echo "3. Tutorial"
                        echo -n "Please choose a word [1,2 or 3]? "
                        choice=4
                fi   
        fi
fi
done 
#notice the indentation style
Nested Bash if else statement

10. Bash Comparisons

10.1. Arithmetic Comparisons

-lt<
-gt>
-le<=
-ge>=
-eq==
-ne!=

ARM assembly language
#!/bin/bash
# declare integers
NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
 echo "Both Values are equal"
else 
 echo "Values are NOT equal"
fi 
Bash Arithmetic Comparisons
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
 echo "Both Values are equal"
else 
 echo "Values are NOT equal"
fi 
Bash Arithmetic Comparisons - values are NOT equal
#!/bin/bash
# declare integers
NUM1=2
NUM2=1
if   [ $NUM1 -eq $NUM2 ]; then
 echo "Both Values are equal"
elif [ $NUM1 -gt $NUM2 ]; then
 echo "NUM1 is greater then NUM2"
else 
 echo "NUM2 is greater then NUM1"
fi 
Bash Arithmetic Comparisons - greater then

10.2. String Comparisons

=equal
!=not equal
<less then
>greater then
-n s1string s1 is not empty
-z s1string s1 is empty

no overloading, thus =, !=, >, < are reserved for
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Scripting"
if [ $S1 = $S2 ]; then
 echo "Both Strings are equal"
else 
 echo "Strings are NOT equal"
fi 
Bash String Comparisons - values are NOT equal
#!/bin/bash
#Declare string S1
S1="Bash"
#Declare string S2
S2="Bash"
if [ $S1 = $S2 ]; then
 echo "Both Strings are equal"
else 
 echo "Strings are NOT equal"
fi 
bash interpreter location: /bin/bash

11. Bash File Testing

-b filenameBlock special file
-c filenameSpecial character file
-d directorynameCheck for directory existence
-e filenameCheck for file existence
-f filenameCheck for regular file existence not a directory
-G filenameCheck if file exists and is owned by effective group ID.
-g filenametrue if file exists and is set-group-id.
-k filenameSticky bit
-L filenameSymbolic link
-O filenameTrue if file exists and is owned by the effective user id.
-r filenameCheck if file is a readable
-S filenameCheck if file is socket
-s filenameCheck if file is nonzero size
-u filenameCheck if file set-ser-id bit is set
-w filenameCheck if file is writable
-x filenameCheck if file is executable
#!/bin/bash
file="./file"
if [ -e $file ]; then
 echo "File exists"
else 
 echo "File does not exists"
fi 
Bash File Testing - File does not exist Bash File Testing - File exists

remove a file
rm -f -r {file-name}
Where,
  • -f: Forcefully remove file
  • -r: Remove the contents of directories recursivel

Similarly for example we can use while loop to check if file does not exists. This script will sleep until file does exists. Note bash negator "!" which negates the -e option.
#!/bin/bash
 
while [ ! -e myfile ]; do
# Sleep until file does exists/is created
sleep 1
done 
to quit above sleep: Ctrl+C – halts the current command

12. Loops

12.1. Bash for loop

#!/bin/bash

# bash for loop
for f in $( ls /var/ ); do //pay attention to white space
 echo $f
done 
Running for loop from bash shell command line:
$ for f in $( ls /var/ ); do echo $f; done 
echo -n (without /n)
Bash for loop

12.2. Bash while loop

#!/bin/bash
COUNT=6
# bash while loop
while [ $COUNT -gt 0 ]; do
 echo Value of count is: $COUNT
 let COUNT=COUNT-1
done 
cannot be COUNT=$COUNT-1 
error message: [: 6-1: integer expression expected
Bash while loop

12.3. Bash until loop (I don't preferred)

#!/bin/bash
COUNT=0
# bash until loop
until [ $COUNT -gt 5 ]; do
        echo Value of count is: $COUNT
        let COUNT=COUNT+1
done 
Bash until loop

12.4. Control bash loop with

Here is a example of while loop controlled by standard input. Until the redirection chain from STDOUT to STDIN to the read command exists the while loop continues.
#!/bin/bash
# This bash script will locate and replace spaces
# in the filenames
DIR="."
# Controlling a loop with bash read command by redirecting STDOUT as
# a STDIN to while loop
# find will not truncate filenames containing spaces
find $DIR -type f | while read file; do
# using POSIX class [:space:] to find space in the filename
if [[ "$file" = *[[:space:]]* ]]; then     "$file"_=_*[[:space:]]* ]];"
# substitute space with "_" character and consequently rename the file
mv "$file" `echo $file | tr ' ' '_'`
fi;
# end of while loop
done 
Bash script to replace spaces in the filenames with _

13. Bash Functions

!/bin/bash
# BASH FUNCTIONS CAN BE DECLARED IN ANY ORDER
function function_B {
        echo Function B. //just echo
}
function function_A {
        echo $1
}
function function_D {
        echo Function D.
}
function function_C {
        echo $1 #first parameter
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A."
function_B
# Pass parameter to function C
function_C "Function C."
function_D 
space!!!
function someFunction_{
....
}

function function_a {
 let Sum=$1+S2
 echo $Sum
}
#let will make the evaluation of the value
function function_a {
 Sum=$1+S2
 echo $Sum
}


Bash Functions

14. Bash Select

#!/bin/bash
 
PS3='Choose one word: ' 

# bash select
select word in "linux" "bash" "scripting" "tutorial" 
do
  echo "The word you have selected is: $word"
  break   #Break, otherwise endless loop
done

exit 0 
Bash Select

15. Case statement conditional

#!/bin/bash
echo "What is your preferred programming / scripting language"
echo "1) bash"
echo "2) perl"
echo "3) phyton"
echo "4) c++"
echo "5) I do not know !"
read case;
#simple case bash structure
# note in this case $case is variable and does not have to
# be named case this is just an example
case $case in #$choice
    1) echo "You selected bash";; #end of case ;;
    2) echo "You selected perl";;
    3) echo "You selected phyton";;
    4) echo "You selected c++";;
    5) exit
esac 
read in just number 1 2 3 4 5
bash case statement conditiona

16. Bash quotes and quotations

Quotations and quotes are important part of bash and bash scripting. Here are some bash quotes and quotations basics.

16.1. Escaping Meta characters

Before we start with quotes and quotations we should know something about escaping meta characters. Escaping will suppress a special meaning of meta characters and therefore meta characters will be read by bash literally. To do this we need to use backslash "\" character. Example:
#!/bin/bash
 
#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

#when meta character such us "$" is escaped with "\" it will be read literally
echo \$BASH_VAR 

# backslash has also special meaning and it can be suppressed with yet another "\"
echo "\\" 
escaping character '\'
escaping meta characters in bash

16.2. Single quotes

Single quotes in bash will suppress special meaning of every meta characters. Therefore meta characters will be read literally. It is not possible to use another single quote within two single quotes not even if the single quote is escaped by backslash.
#!/bin/bash
 
 #Declare bash string variable
 BASH_VAR="Bash Script"
 
 # echo variable BASH_VAR
 echo $BASH_VAR
 
 # meta characters special meaning in bash is suppressed when  using single quotes 
 echo '$BASH_VAR  "$BASH_VAR"' 
single quote: escape in bulk; strong escape
Using single quotes in bash

16.3. Double Quotes

Double quotes in bash will suppress special meaning of every meta characters except " $ ", " \ " and " ` ". Any other meta characters will be read literally. It is also possible to use single quote within double quotes. If we need to use double quotes within double quotes bash can read them literally when escaping them with "\". Example:
#!/bin/bash
 
#Declare bash string variable
BASH_VAR="Bash Script"

# echo variable BASH_VAR
echo $BASH_VAR

# meta characters and its special meaning in bash is 
# suppressed when using double quotes except " $ ", "\" and " ` "

echo "It's $BASH_VAR  and \"$BASH_VAR\" using backticks: `date`" 
double quote: weak escape in bulk
Using double quotes in bash

16.4. Bash quoting with ANSI-C style

There is also another type of quoting and that is ANSI-C. In this type of quoting characters escaped with "\" will gain special meaning according to the ANSI-C standard.
\aalert (bell)\bbackspace
\ean escape character\fform feed
\nnewline\rcarriage return
\thorizontal tab\vvertical tab
\\backslash\`single quote
\nnnoctal value of characters ( see [http://www.asciitable.com/ ASCII table] )\xnnhexadecimal value of characters ( see [http://www.asciitable.com/ ASCII table] )
The syntax fo ansi-c bash quoting is: $'' . Here is an example:
#!/bin/bash
 
# as a example we have used \n as a new line, \x40 is hex value for @
# and \56 is octal value for .
echo $'web: www.linuxconfig.org\nemail: web\x40linuxconfig\56org' 
quoting in bash with ansi-c stype
echo $'web: www.linuxconfig.org\nemail: web@linuxconfig.org'

17. Arithmetic Operations

17.1. Bash Addition Calculator Example

#!/bin/bash
 
let RESULT1=$1+$2
echo $1+$2=$RESULT1 ' -> # let RESULT1=$1+$2'
declare -i RESULT2
RESULT2=$1+$2
echo $1+$2=$RESULT2 ' -> # declare -i RESULT2; RESULT2=$1+$2'
echo $1+$2=$(($1 + $2)) ' -> # $(($1 + $2))' 
declare -i RESULT2
declared as integer
declare -a RESULT3
declared as array

if just RESULT=$1+$2
if is string by default (duck typing)
you can try RESULT=$(($1+$2))


$(($1+$2)) double brackets, otherwise $($1+$2) $(1+2) command not found

Bash Addition Calculator

17.2. Bash Arithmetics

#!/bin/bash
 
echo '### let ###'
# bash addition
let ADDITION=3+5
echo "3 + 5 =" $ADDITION

# bash subtraction
let SUBTRACTION=7-8
echo "7 - 8 =" $SUBTRACTION 

# bash multiplication
let MULTIPLICATION=5*8
echo "5 * 8 =" $MULTIPLICATION

# bash division
let DIVISION=4/2
echo "4 / 2 =" $DIVISION

# bash modulus
let MODULUS=9%4
echo "9 % 4 =" $MODULUS

# bash power of two
let POWEROFTWO=2**2  #python
echo "2 ^ 2 =" $POWEROFTWO


echo '### Bash Arithmetic Expansion ###'
# There are two formats for arithmetic expansion: $[ expression ] 
# and $(( expression #)) its your choice which you use!!!space

echo 4 + 5 = $((4 + 5))
echo 7 - 7 = $[ 7 - 7 ]
echo 4 x 6 = $((3 * 2))
echo 6 / 3 = $((6 / 3))
echo 8 % 7 = $((8 % 7))
echo 2 ^ 8 = $[ 2 ** 8 ]


echo '### Declare ###'

echo -e "Please enter two numbers \c"
# read user input
read num1 num2
declare -i result
result=$num1+$num2
echo "Result is:$result "

# bash convert binary number 10001
result=2#10001
echo $result

# bash convert octal number 16
result=8#16
echo $result

# bash convert hex number 0xE6A #convert the hex number to decimal
result=16#E6A
echo $result 
Bash Arithmetic Operations

17.3. Round floating point number

#!/bin/bash
# get floating point number
floating_point_number=3.3446
echo $floating_point_number
# round floating point number with bash
for bash_rounded_number in $(printf %.0f $floating_point_number); do
echo "Rounded number with bash:" $bash_rounded_number
done 
Round floating point number with bash

17.4. Bash floating point calculations

#!/bin/bash
# Simple linux bash calculator 
echo "Enter input:" 
read userinput
echo "Result with 2 digits after decimal point:"
echo "scale=2; ${userinput}" | bc 
echo "Result with 10 digits after decimal point:"
echo "scale=10; ${userinput}" | bc 
echo "Result as rounded integer:"
echo $userinput | bc 
Bash floating point calculations

18. Redirections

18.1. STDOUT from bash script to STDERR

#!/bin/bash
 
 echo "Redirect this STDOUT to STDERR" 1>&2 
To prove that STDOUT is redirected to STDERR we can redirect script's output to file:
STDOUT from bash script to STDERR

18.2. STDERR from bash script to STDOUT

#!/bin/bash
 
 cat $1 2>&1 
To prove that STDERR is redirected to STDOUT we can redirect script's output to file:
STDERR from bash script to STDOUT

18.3. stdout to screen

The simple way to redirect a standard output ( stdout ) is to simply use any command, because by default stdout is automatically redirected to screen. First create a file "file1":
$ touch file1
$ ls file1 
file1
As you can see from the example above execution of ls command produces STDOUT which by default is redirected to screen.

18.4. stdout to file

The override the default behavior of STDOUT we can use ">" to redirect this output to file:
$ ls file1 > STDOUT
$ cat STDOUT 
file1

18.5. stderr to file

By default STDERR is displayed on the screen:
$ ls
file1  STDOUT
$ ls file2
ls: cannot access file2: No such file or directory
In the following example we will redirect the standard error ( stderr ) to a file and stdout to a screen as default. Please note that STDOUT is displayed on the screen, however STDERR is redirected to a file called STDERR:
$ ls
file1  STDOUT
$ ls file1 file2 2> STDERR
file1
$ cat STDERR 
ls: cannot access file2: No such file or directory

18.6. stdout to stderr

It is also possible to redirect STDOUT and STDERR to the same file. In the next example we will redirect STDOUT to the same descriptor as STDERR. Both STDOUT and STDERR will be redirected to file "STDERR_STDOUT".
$ ls
file1  STDERR  STDOUT
$ ls file1 file2 2> STDERR_STDOUT 1>&2
$ cat STDERR_STDOUT
ls: cannot access file2: No such file or directory
file1
File STDERR_STDOUT now contains STDOUT and STDERR.

18.7. stderr to stdout

The above example can be reversed by redirecting STDERR to the same descriptor as SDTOUT:
$ ls
file1  STDERR  STDOUT
$ ls file1 file2 > STDERR_STDOUT 2>&1
$ cat STDERR_STDOUT 
ls: cannot access file2: No such file or directory
file1

18.8. stderr and stdout to file

Previous two examples redirected both STDOUT and STDERR to a file. Another way to achieve the same effect is illustrated below:
$ ls
file1  STDERR  STDOUT
$ ls file1 file2 &> STDERR_STDOUT
$ cat STDERR_STDOUT 
ls: cannot access file2: No such file or directory
file1
or
ls file1 file2 >& STDERR_STDOUT
$ cat STDERR_STDOUT 
ls: cannot access file2: No such file or directory
file1
done