Showing posts with label Bash Scripting. Show all posts
Showing posts with label Bash Scripting. Show all posts

Bash Scripts : Arithmetic Expressions Examples

Although Bash is a scripting language, it has pretty much all the capabilities of a general purpose programming language. This includes arithmetic functions. There are a number of syntax options you can use to evoke arithmetic evaluation of an expression. Perhaps the most readable one is the let command. For example
let "m = 4 * 1024"
will compute 4 times 1024 and assign the result to the variable "m". You can print out the result by adding an echo statement:
let "m = 4 * 1024"
echo $m
You can test this from the command line by entering the following code:
let "m = 4 * 1024"; echo $m
You can also create a file containing the Bash commands, in which case you should add a line at the top of the file that specifies the program that is supposed to execute the code. For example:
#!/bin/bash

let "m = 4 * 1024"
echo $m
assuming the Bash executable is located in /bin/bash. You also need to set the permissions of your script file so that it is executable. Assuming the script file name is script1.sh, you can set the permissions to make the file executable with the command:
chmod 777 script1.sh
After that you can execute it with the command:
./script1.sh
The available arithmetic operations are similar to those in standard programming languages like Java and C. Besides multiplication, as illustrated above, you use addition:
let "m = a + 7"
or subtraction:
let "m = a - 7"
or division:
let "m = a / 2"
or modulo (the remainder after an integer division):
let "m = a % 100"
When an operation is applied to the same variable to which the result is assigned you can use the standard arithmetic shorthand assignment operators, also referred to as compound assignment operators. For example, for addition we have:
let "m += 15"
which is equivalent to "m = m + 15". For subtraction we have:
let "m -= 3"
which is equivalent to "m = m - 3". For division we have:
let "m /= 5"
which is equivalent to "m = m / 5". And for modulo, we have:
let "m %= 10"
which is equivalent to "m = m % 10". Additionally, you can use the increment and decrement operators:
let "m++"
is equivalent to "m = m + 1". And
let "m--"
is equivalent to "m = m - 1". And then there is the ternary "question mark-colon" operator, which returns one of two values depending on whether the specified condition is true or false. For example
let "k = (m < 9) ? 0 : 1"
The right hand side of this assignment statement evaluates to "0" if the variable "m" is less than 9. Otherwise it evaluates to 1. This means the variable "k" is assigned "0" if "m" is less than 9 and "1" otherwise. The general form of the question mark-colon operator is:
condition ? value-if-true : value-if-false

Floating Point Arithmetic in Bash

The let operator only works for integer arithmetic. For floating point arithmetic you can use for example the GNU bc calculator as illustrate in this example:
echo "32.0 + 1.4" | bc 
The "pipe" operator "|" passes the arithmetic expression "32.0 + 1.4" to the bc calculator, which returns the real number. The echo command prints the result to the standard output.

Alternative Syntax for Arithmetic

Backticks (back single quotes) can be used to evaluate an arithmetic expression as in this example:
echo `expr $m + 18`
This will add 18 to the value of the variable "m" and then print out the result. To assign the compute value to a variable you can use the equal sign without spaces around it:
m=`expr $m + 18`
Another way to evaluate arithmetic expressions is to use double parenthesis. For example:
(( m *= 4 ))
This will quadruple the value of the variable "m". Besides arithmetic evaluation, the Bash shell provides other programming constructs, such as for-loops, while-loops, conditionals, and functions and subroutines.

Bash Scripts : How to write IF-Statements Examples

With an if-statement, which is a type of conditional statement, you can perform different actions depending on specified conditions. It effectively gives the system the ability to make decisions.
An example of the simplest form of an if-statement would be:
count=5
if [ $count == 5 ]
then 
   echo "$count"
fi
In this example the variable "count" is used to specify a condition that is used as part of the if-statement. Before the if-statement is execute, the variable "count" is assigned the value "5". The if-statement then checks whether the value of "count" is "5". If that is the case the statement between the keywords "then" and "fi" are executed, otherwise any statements following the if-statement are executed.

The keyword "fi" is "if" spelled backwards. The bash scripting language uses this convention to mark the end of a complex expression, such an if-statement or case-statements. The "echo" statement prints its argument, in this case the value of the variable "count", to the terminal window. Indentation of the code between the keywords of the if-statement improves readability, but is not necessary.

If you have a situation where a piece of code should be executed only if a condition is not true, you can use the keyword "else" in a if-statement, as in this example:
count=5
if [ $count == 5 ]
then 
   echo "$count"
else
   echo "count is not 5"
fi
If the condition "$count == 5" is true, the system prints the value of the variable "count", otherwise it prints the string "count is not 5". If you want to differentiate between multiple conditions, you can use the keyword "elif", which is derived from "else if", as in this example:
if [ $count == 5 ]
then 
   echo "count is five"
elif [ $count == 6 ]
then
   echo "count is six"
else
   echo "none of the above"
fi
If "count" is "5", the system prints out "count is five". If "count" is not "5" but "6", the system prints "count is six". If it is neither "5" nor "6", the system prints "none of the above". As you may have guessed, you can have any number of "elif" clauses. An example with multiple "elif" conditions would be:
if [ $count == 5 ]
then 
   echo "count is five"
elif [ $count == 6 ]
then
   echo "count is six"
elif [ $count == 7 ]
then
   echo "count is seven"
elif [ $count == 8 ]
then
   echo "count is eight"
elif [ $count == 9 ]
then
   echo "count is nine"
else
   echo "none of the above"
fi
A more compact way to write such statements with multiple conditions is the case method. It functions similar to the if-statement with multiple "elif" clauses, but is more concise. For example, the above piece of code can be re-written with the "case" statement as follows:
case "$count" in
     5) 
        echo "count is five"
        ;;
     6) 
        echo "count is six"
        ;;
     7) 
        echo "count is seven"
        ;;
     8) 
        echo "count is eight"
        ;;
     9) 
        echo "count is nine"
        ;;
     *)
        echo "none of the above"
esac
If-statements are often used inside for-loops or while-loops as in this example:
count=1
done=0
while [ $count -le 9 ]
do
    sleep 1
    (( count++ ))
    if [ $count == 5 ]
    then 
        continue
    fi
    echo "$count"
done
echo Finished
You can also have nested if statements. Simplest nested if statement is of the form: if...then...else...if...then...fi...fi. However, if-statement can nested with arbitrary complexity. See also the section on How to Pass Arguments to a Bash Script, which shows how to use conditionals to process parameters passed from the command line.
The Bash shell provides other programming constructs, such as for-loops, while-loops, and arithmetic expressions.

Bash Scripts : How to Passing Arguments Examples

You can write a bash script such that it receives arguments specified when the script is called from the command line. This method is used when a script has to perform a slightly different function depending on the values of input parameters (the arguments).

For example, you may have a script called "stats.sh" that performs a particular operation on a file, such as counting its words. If you want to be able to use that script on many files, it is best to pass the file name as an argument, so that you can use the same script for all the files to be processed. For example, if the name of the file to be processed is "songlist", you would enter the following command line:
sh stats.sh songlist
Arguments are accessed inside a script using the variables $1, $2, $3, etc., where $1 refers to the first argument, $2 to the second argument, and so on. This is illustrated in the following example:
FILE1=$1
wc $FILE1
For readability we assign a variable with a descriptive name to the value of the first argument ($1), and then call the word count utility (wc) on this variable ($FILE1). If you have a variable number of arguments, you can use the "$@" variable, which is an array of all the input parameters. This means you can use a for-loop to iteratively process each one, as illustrated in the following example:
for FILE1 in "$@"
do
   wc $FILE1
done
Here is an example of how to call this script with arguments from the command line:
sh stats.sh songlist1 songlist2 songlist3
If an argument has spaces, you need to enclose it with single quotes. For example:
sh stats.sh 'songlist 1' 'songlist 2' 'songlist 3'
Frequently a script is written such that the user can pass in arguments in any order using "flags". With this flags method you can also make some of the arguments optional. Let say you have a script that retrieves information from a database based on specified parameters, such as "username", "date", and "product", and generates a report in a specified "format". Now you want to write your script such that you can pass in these parameters when the script is called. For example, like this:
makereport -u jsmith -p notebooks -d 10-20-2011 -f pdf
Bash enables this functionality with the "getopts" function. For the above example, you could use getopts as follows:

while getopts u:d:p:f: option
do
        case "${option}"
        in
                u) USER=${OPTARG};;
                d) DATE=${OPTARG};;
                p) PRODUCT=${OPTARG};;
                f) FORMAT=$OPTARG;;
        esac
done

This is a while-loop that uses the "getopts" function and a so-called "optstring", in this case "u:d:p:f:", to iterate through the arguments. The while-loop walks through the optstring, which contains the flags that can be used to pass arguments, and assigns the argument value provided for that flag to the variable "option". The case-statement then assigns the value of the variable "option" to a global variable that can used after all the arguments have been read. The colons in the optstring mean that values are required for the corresponding flags. In the above example all flags are followed by a colon: "u:d:p:f:". This means, all flags need a value. If, for example, the "d" and "f" flags were not expected to have a value, the optstring would be "u:dp:f".

A colon at the beginning of the optstring, for example ":u:d:p:f:", has a completely different meaning. It allows you to handle flags that are not represented in the optstring. In that case the value of the "option" variable is set to "?" and the value of "OPTARG" is set to the unexpected flag. The allows you to display a suitable error message informing the user of the mistake.

Arguments that are not preceded by a flag are ignored by getopts. If flags specified in the optstring are not provided when the script is called, nothing happens, unless you specially handle this case in your code. Any arguments not handled by getops can still be captured with the regular $1, $2, etc. variables.

Bash Scripts : How to write bash WHILE-loops Examples

You can execute a sequence of commands by writing them into a "script file" and then running the script file. A script file is simply a text file that contains a sequence of instructions that could also be executed from the command line (also know as shell). Usually the extension ".sh" is used for script files.
Here is an example of a while loop:
#!/bin/bash
count=1
while [ $count -le 9 ]
do
    echo "$count"
    sleep 1
    (( count++ ))
done
When executed, this script file will print the numbers 1 through 9 on the screen. The while-statement gives you more flexibility for specifying the termination condition than the for-loop. For example you can make the previous script an infinite loop by omitting the increment statement "(( count++ ))":
#!/bin/bash
count=1
while [ $count -le 9 ]
do
    echo "$count"
    sleep 1
done
The "sleep 1" statement pauses the execution for 1 second on each iteration. Use "Ctrl-C" to terminate the process. You can also create an infinite loop by putting a colon as the condition:
#!/bin/bash
count=1
while :
do
    echo "$count"
    sleep 1
    (( count++ ))
done
In order to use multiple conditions in the while-loop you need to use the double square bracket notation:
count=1
done=0
while [[ $count -le 9 ] && [ $done == 0 ]]
do
    echo "$count"
    sleep 1
    (( count++ ))
    if [ $count == 5 ]; then  $done=1
    fi
done
In this script the variable "done" is initialized to 0 and then set to 1 when count reaches 5. The loop condition states that the while loop will continue as long as "count" is less than nine and "done" is equal to zero. Therefore the loops exits when count equals 5. The "&&" means logical "and" and "||" means logical "or".
An alternative notation for the conjunctions "and" and "or" in conditions is "-a" and "-o" with single square brackets. The above condition
[[ $count -le 9 ] && [ $done == 0 ]]
could be rewritten as
[ $count -le 9 ] -a [ $done == 0 ]
Reading a text file is typically done with a while loop. In the following example, the bash script reads the contends of a file "inventory.txt" line be line:
FILE=inventory.txt
exec 6
The first line assigns the input file name to the variable "FILE". The second line saves the "standard input" in the file descriptor "6" (it could be any value between 3 and 9). This is done so that "standard input" can be restored to file descriptor "0" at the end of the script (see statement "exec 0 In the 3rd line the input file is assigned to file descriptor "0", which is used for standard input. The "read" statement then reads a line from the file on each iteration and assigns it to the variable "line1". In order to prematurely exit a while-loop you can use the break statement as in the following example:
count=1
done=0
while [ $count -le 9 ]
do
    echo "$count"
    sleep 1
    (( count++ ))
    if [ $count == 5 ]
    then 
        break
    fi
done
echo Finished
The break statement skips program execution to the end while loop and executes any statements following it. In this case the statement "echo Finished". The continue statement on the other hand skips only the rest of the while loop statement of the current iteration and jumps directly to the next iteration:
count=1
done=0
while [ $count -le 9 ]
do
    sleep 1
    (( count++ ))
    if [ $count == 5 ]
    then 
        continue
    fi
    echo "$count"
done
echo Finished
In this case the "continue" statement is executed when the variable "count" reaches 5. This means the subsequent statement (echo "$count") is not executed on this iteration (when the value of "count" is 5).

Bash Scripts : How to write bash FOR-loops Examples

A good way to execute a sequence of commands is to write them into a "script file". A script file is simply a text file, typically with the file name extension ".sh", that contains a sequence of statements to be executed. For example, when executed, the following procedure would print the number 1 through 9 on the screen:
#!/bin/bash
for count in 1 2 3 4 5 6 7 8 9
do
    echo "$count"
done
Assuming this code is written to a file called "script1.sh", you can execute it by first making it executable, for example with
chmod 775 script1.sh
And then executing it with:
./script1.sh
The first line in the script (#!/bin/bash) tells the shell which program to use for execution. The structure of the "for" statement is "for ... in ... do ... done". In the above example "count" is a variable which is assigned each of the values in the list "1 2 3 4 5 6 7 8 9". For each value, the statements between "do" an "done" are executed once. The value of the variable is accessed using the notation "$count". That is, the variable name preceded with a dollar sign.
So, on the first iteration the $count has the value "1", on the second iteration it has the value "2", etc. The echo statement means that the string to the right (its "argument") is printed on the next line on the shell window. Therefore the output of the above bash program would be:
1
2
3
4
5
6
7
8
9
Bash for-loops are frequently used to perform an operation on a set of files. For example, if you wanted to uncompress all files with extension "bz2" in the directory /home/jdoe/data/ using the utility bunzip2 you could use the following bash script:
#!/bin/bash
FILES=/home/jdoe/data/*.bz2
for file in $FILES
do
    bunzip2 $file
done
In the statement "FILES=/home/jdoe/data/*.bz2" the variable "FILES" is assigned the list of files in directory (folder) "/home/jdoe/data/", whose name ends with ".bz2". The "*" (wild card character) stands for any sequence of characters. In the for-statement "file" is used as the name of the loop variable, which is assigned each of the file names in the list assigned to "FILES". The body of the for-loop (the statements between the "do" and the "done") is executed once for each file name.
The following example illustrates the use of "ranges" in a for-loop:
#!/bin/bash
for count in {1..9}
do
    echo "$count"
done
The expression "{1..9}" is a shorthand for the list "1 2 3 4 5 6 7 8 9". So this program does essentially the same the one above. The range notation has a variant that allows you to specify the step size. In the following example the loop variable is increased by 3 on each iteration:
#!/bin/bash
for count in {1..10..3}
do
    echo "$count"
done
So the output would be:
1
4
7
10
In some cases it is more suitable to use a while-loop instead of a for-loop. The following example does essentially the same the for-loop above:
#!/bin/bash
count=1
while [[ $count -le 9 ]]
do
    echo "$count"
    (( count++ ))
done
Although the while-statement is not quite as elegant as a for-loop, it gives you more flexibility for specifying the termination condition. For example you can make the previous script an infinite loop by omitting the increment statement "(( count++ ))":
#!/bin/bash
count=1
while [[ $count -le 9 ]]
do
    echo "$count"
    sleep 1
done
The sleep 1 statement pauses the execution for 1 second on each iteration. Use "Ctrl-C" to terminate the process.

Bash Scripts : Functions and Subroutines Examples

Even though Bash is a Linux shell it has many of the capabilities needed to be a general purpose programming language, such as loops and conditional expressions. While-loops and For-loops are ways to execute a sequence of instructions multiple times. Functions are another method to save you from duplicating code.

Functions are separate blocks of code that can be called any number of times from any other location of a Bash script, including from within a function. In other programming languages functions are also called subroutines.

Let start with simple example:

#!/bin/bash

function print_bold {
   echo "<b>$1</b>"
}

print_bold "batman"
In this script we first define a function print_bold, which takes the first pararmeter ($1) and prints it out enclosed with the html tags for bold.
After the function is defined, we call it with the statement:
print_bold "batman"
where batman is the argument (parameter) passed to the function.
You can run this script in the usual way with:
./test_script.sh
Assuming the filename of the script is test_script.sh and the current directory is the directory where the script is saved.
Note that the definition of a function has to come before it is used.
As in other places of a bash script you can have comments inside a function definition by starting the line with a "hash" (#), as in this example:
#!/bin/bash

function print_bold {
   # This function prints a string
   # bold tags around it.
   echo "<b>$1</b>"
}

print_bold "batman"
The line that starts with '#!' specifies which program should execute this script.
There is an alternative syntax to define a bash function:
print_bold() {
   # This function prints a string
   # bold tags around it.
   echo "<b>$1</b>"
}
Instead of using the function key word, you can define a function using parentheses () after the function name similar to the way functions are defined in Java or C++ code.
You can check if a parameter passed to a function is non-empty using the -z test:
print_bold() {
   if [ -z "$1" ]
   then
      echo "Argument is empty"
   else
      echo "<b>$1</b>"
   fi
}
You can define global variables and access them from within a function definition as illustrated in this example:
PARAM1="em"

function print_bold {
   echo "<$PARAM1>$1</$PARAM1>"
}
The variable PARAM1 is assigned the value "em" before the function is defined. Then it used as part of the output string generated by the function.
However, you cannot directly access parameters passed from the command line If you want to access command line arguments inside a function you have to explicitly pass it in:
#!/bin/bash

PARAM1=$2
PARAM2=$1

function print_bold {
   echo "<$PARAM1>$1</$PARAM1>"
   echo "<$PARAM2>$1</$PARAM2>"
   echo "<$2>$1</$2>"
}

print_bold "batman" $3
When the subroutine (function) print_bold is called it receives two parameters: "batman" and "$3", which is the third command line argument. This value is then accessed from inside the function also with "$2" since it is the second argument pass to the function.
So if you call the script with:
./test_function02.sh b em it
You should the following output:
<em>batman</em>
<b>batman</b>
<it>batman</it>

Bash Shell : Check File Exists or Not

How do I test existence of a text file in bash running under Unix like operating systems?

You need to use the test command to check file types and compare values. The same command can be used to see if a file exist of not. The syntax is as follows:
 
test -e filename
[ -e filename ]
 
test -f filename
[ -f filename ]
 
The following command will tell if a text file called /etc/hosts exists or not using bash conditional execution :
 
[ -f /etc/hosts ] && echo "Found" || echo "Not found"
 
Sample outputs:
Found
The same code can be converted to use with if..else..fi which allows to make choice based on the success or failure of a test command:
 
#!/bin/bash
file="/etc/hosts"
if [ -f "$file" ]
then
 echo "$file found."
else
 echo "$file not found."
fi
 

File test operators

The following operators returns true if file exists:
       -b FILE
              FILE exists and is block special
       -c FILE
              FILE exists and is character special
       -d FILE
              FILE exists and is a directory
       -e FILE
              FILE exists
       -f FILE
              FILE exists and is a regular file
       -g FILE
              FILE exists and is set-group-ID
       -G FILE
              FILE exists and is owned by the effective group ID
       -h FILE
              FILE exists and is a symbolic link (same as -L)
       -k FILE
              FILE exists and has its sticky bit set
       -L FILE
              FILE exists and is a symbolic link (same as -h)
       -O FILE
              FILE exists and is owned by the effective user ID
       -p FILE
              FILE exists and is a named pipe
       -r FILE
              FILE exists and read permission is granted
       -s FILE
              FILE exists and has a size greater than zero
       -S FILE
              FILE exists and is a socket
       -t FD  file descriptor FD is opened on a terminal
       -u FILE
              FILE exists and its set-user-ID bit is set
       -w FILE
              FILE exists and write permission is granted
       -x FILE
              FILE exists and execute (or search) permission is granted
 
(Fig.01: File test operators taken from bash man page)
 
if [ operator FileName ] then echo "FileName - Found, take some action here" else echo "FileName - Not found, take some action here" fi

With the help of BASH shell and IF command it is possible to find out if file exists or not. Generally, this is known as conditional expressions. Conditional expressions are used by the [[ compound command and the test and [ builtin commands to test file attributes and perform string and arithmetic comparisons. General syntax:

[ parameter FILE ]
OR
test parameter FILE
Where parameter can be any one of the following:
  • -e: Returns true value if file exists
  • -f: Return true value if file exists and regular file
  • -r: Return true value if file exists and is readable
  • -w: Return true value if file exists and is writable
  • -x: Return true value if file exists and is executable
  • -d: Return true value if exists and is a directory
Examples

Find out if file /etc/passwd file exists or not

Type the following commands:
$ [ -f /etc/passwd ] && echo "File exists" || echo "File does not exists"
$ [ -f /tmp/fileonetwo ] && echo "File exists" || echo "File does not exists"

Find out if directory /var/logs exists or not

Type the following commands:
$ [ -d /var/logs ] && echo "Directory exists" || echo "Directory does not exists"
$ [ -d /dumper/fack ] && echo "Directory exists" || echo "Directory does not exists"

You can use conditional expressions in a shell script:
#!/bin/bash
FILE=$1
 
if [ -f $FILE ];
then
   echo "File $FILE exists"
else
   echo "File $FILE does not exists"
fi
 
Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf

Bash Shell Scripts Examples

A simple shell script

A shell script is little more than a list of commands that are run in sequence. Conventionally, a shellscript should start with a line such as the following:
#!/bin/bash
THis indicates that the script should be run in the bash shell regardless of which interactive shell the user has chosen. This is very important, since the syntax of different shells can vary greatly.

A simple example

Here's a very simple example of a shell script. It just runs a few simple commands

#!/bin/bash
echo "hello, $USER. I wish to list some files of yours"
echo "listing files in the current directory, $PWD"
ls  # list files
Firstly, notice the comment on line 4. In a bash script, anything following a pound sign # (besides the shell name on the first line) is treated as a comment. ie the shell ignores it. It is there for the benifit of people reading the script.
$USER and $PWD are variables. These are standard variables defined by the bash shell itself, they needn't be defined in the script. Note that the variables are expanded when the variable name is inside double quotes. Expanded is a very appropriate word: the shell basically sees the string $USER and replaces it with the variable's value then executes the command.
We continue the discussion on variables below ...

Variables

Any programming language needs variables. You define a variable as follows:
X="hello"
and refer to it as follows:
$X
More specifically, $X is used to denote the value of the variable X. Some things to take note of regarding semantics:
  • bash gets unhappy if you leave a space on either side of the = sign. For example, the following gives an error message:
    X = hello
  • while I have quotes in my example, they are not always necessary. where you need quotes is when your variable names include spaces. For example,
    X=hello world # error
    X="hello world" # OK
This is because the shell essentially sees the command line as a pile of commands and command arguments seperated by spaces. foo=baris considered a command. The problem with foo = bar is the shell sees the word foo seperated by spaces and interprets it as a command. Likewise, the problem with the command X=hello world is that the shell interprets X=hello as a command, and the word "world" does not make any sense (since the assignment command doesn't take arguments).

Single Quotes versus double quotes

Basically, variable names are exapnded within double quotes, but not single quotes. If you do not need to refer to variables, single quotes are good to use as the results are more predictable.
An example

#!/bin/bash
echo -n '$USER=' # -n option stops echo from breaking the line
echo "$USER"
echo "\$USER=$USER"  # this does the same thing as the first two lines
The output looks like this (assuming your username is elflord)

$USER=elflord

$USER=elflord
so the double quotes still have a work around. Double quotes are more flexible, but less predictable. Given the choice between single quotes and double quotes, use single quotes.

Using Quotes to enclose your variables

Sometimes, it is a good idea to protect variable names in double quotes. This is usually the most important if your variables value either (a) contains spaces or (b) is the empty string. An example is as follows:

#!/bin/bash
X=""
if [ -n $X ]; then  # -n tests to see if the argument is non empty
 echo "the variable X is not the empty string"
fi

This script will give the following output:
the variable X is not the empty string
Why ? because the shell expands $X to the empty string. The expression [ -n ] returns true (since it is not provided with an argument). A better script would have been:

#!/bin/bash
X=""
if [ -n "$X" ]; then  # -n tests to see if the argument is non empty
 echo "the variable X is not the empty string"
fi

In this example, the expression expands to [ -n "" ] which returns false, since the string enclosed in inverted commas is clearly empty.

Variable Expansion in action

Just to convince you that the shell really does "expand" variables in the sense I mentioned before, here is an example:

#!/bin/bash
LS="ls"
LS_FLAGS="-al"

$LS $LS_FLAGS $HOME

This looks a little enigmatic. What happens with the last line is that it actually executes the command
ls -al /home/elflord
(assuming that /home/elflord is your home directory). That is, the shell simply replaces the variables with their values, and then executes the command.

Using Braces to Protect Your Variables

OK. Here's a potential problem situation. Suppose you want to echo the value of the variable X, followed immediately by the letters "abc". Question: how do you do this ? Let's have a try :

#!/bin/bash
X=ABC
echo "$Xabc"
THis gives no output. What went wrong ? The answer is that the shell thought that we were asking for the variable Xabc, which is uninitialised. The way to deal with this is to put braces around X to seperate it from the other characters. The following gives the desired result:

#!/bin/bash
X=ABC
echo "${X}abc"

Conditionals, if/then/elif

Sometimes, it's necessary to check for certain conditions. Does a string have 0 length ? does the file "foo" exist, and is it a symbolic link , or a real file ? Firstly, we use the if command to run a test. The syntax is as follows:

if condition
then
 statement1
 statement2
 ..........
fi
Sometimes, you may wish to specify an alternate action when the condition fails. Here's how it's done.

if condition
then
 statement1
 statement2
 ..........
else
 statement3
fi
alternatively, it is possible to test for another condition if the first "if" fails. Note that any number of elifs can be added.

if condition1
then
 statement1
 statement2
 ..........
elif condition2
then
 statement3
 statement4
 ........    
elif condition3
then
 statement5
 statement6
 ........    


fi
The statements inside the block between if/elif and the next elif or fi are executed if the corresponding condition is true. Actually, any command can go in place of the conditions, and the block will be executed if and only if the command returns an exit status of 0 (in other words, if the command exits "succesfully" ). However, in the course of this document, we will be only interested in using "test" or "[ ]" to evaluate conditions.

The Test Command and Operators

The command used in conditionals nearly all the time is the test command. Test returns true or false (more accurately, exits with 0 or non zero status) depending respectively on whether the test is passed or failed. It works like this:
test operand1 operator operand2
for some tests, there need be only one operand (operand2) The test command is typically abbreviated in this form:
[ operand1 operator operand2 ]
To bring this discussion back down to earth, we give a few examples:

#!/bin/bash
X=3
Y=4
empty_string=""
if [ $X -lt $Y ] # is $X less than $Y ? 
then
 echo "\$X=${X}, which is smaller than \$Y=${Y}"
fi

if [ -n "$empty_string" ]; then
 echo "empty string is non_empty"
fi

if [ -e "${HOME}/.fvwmrc" ]; then    # test to see if ~/.fvwmrc exists
 echo "you have a .fvwmrc file"
 if [ -L "${HOME}/.fvwmrc" ]; then   # is it a symlink ?  
  echo "it's a symbolic link
 elif [ -f "${HOME}/.fvwmrc" ]; then  # is it a regular file ?
  echo "it's a regular file"
 fi
else
 echo "you have no .fvwmrc file"
fi

Some pitfalls to be wary of

The test command needs to be in the form "operand1<space>operator<space>operand2" or operator<space>operand2 , in other words you really need these spaces, since the shell considers the first block containing no spaces to be either an operator (if it begins with a '-') or an operand (if it doesn't). So for example; this

if [ 1=2 ]; then 
 echo "hello"
fi
gives exactly the "wrong" output (ie it echos "hello", since it sees an operand but no operator.) Another potential trap comes from not protecting variables in quotes. We have already given an example as to why you must wrap anything you wish to use for a -n test with quotes. However, there are a lot of good reasons for using quotes all the time, or almost all of the time. Failing to do this when you have variables expanded inside tests can result in very wierd bugs. Here's an example: For example,

#!/bin/bash
X="-n"
Y=""
if [ $X = $Y ] ; then
 echo "X=Y"
fi
This will give misleading output since the shell expands our expression to
[ -n = ]
and the string "=" has non zero length.

A brief summary of test operators

Here's a quick list of test operators. It's by no means comprehensive, but its likely to be all you'll need to remember (if you need anything else, you can always check the bash manpage ... )
operatorproduces true if... number of operands
-noperand non zero length1
-zoperand has zero length1
-dthere exists a directory whose name is operand1
-fthere exists a file whose name is operand1
-eqthe operands are integers and they are equal2
-neqthe opposite of -eq2
=the operands are equal (as strings)2
!=opposite of = 2
-ltoperand1 is strictly less than operand2 (both operands should be integers)2
-gtoperand1 is strictly greater than operand2 (both operands should be integers)2
-geoperand1 is greater than or equal to operand2 (both operands should be integers)2
-leoperand1 is less than or equal to operand2 (both operands should be integers)2

Loops

Loops are constructions that enable one to reiterate a procedure or perform the same procedure on several different items. There are the following kinds of loops available in bash
  • for loops
  • while loops

For loops

The syntax for the for loops is best demonstrated by example.

#!/bin/bash
for X in red green blue
do
 echo $X
done
THe for loop iterates the loop over the space seperated items. Note that if some of the items have embedded spaces, you need to protect them with quotes. Here's an example:

#!/bin/bash
colour1="red"
colour2="light blue"
colour3="dark green"
for X in "$colour1" $colour2" $colour3"
do
 echo $X
done
Can you guess what would happen if we left out the quotes in the for statement ? This indicates that variable names should be protected with quotes unless you are pretty sure that they do not contain any spaces.

Globbing in for loops

The shell expands a string containing a * to all filenames that "match". A filename matches if and only if it is identical to the match string after replacing the stars * with arbitrary strings. For example, the character "*" by itself expands to a space seperated list of all files in the working directory (excluding those that start with a dot "." ) So
echo *
lists all the files and directories in the current directory.
echo *.jpg
lists all the jpeg files.
echo ${HOME}/public_html/*.jpg
lists all jpeg files in your public_html directory. As it happens, this turns out to be very useful for performing operations on the files in a directory, especially used in conjunction with a for loop. For example:

#!/bin/bash
for X in *.html
do
  grep -L '<UL>' "$X"
done

While Loops

While loops iterate "while" a given condition is true. An example of this:

#!/bin/bash
X=0
while [ $X -le 20 ]
do
 echo $X
 X=$((X+1))
done
This raises a natural question: why doesn't bash allow the C like for loops
for (X=1,X<10; X++)
As it happens, this is discouraged for a reason: bash is an interpreted language, and a rather slow one for that matter. For this reason, heavy iteration is discouraged.

Command Substitution

Command Substitution is a very handy feature of the bash shell. It enables you to take the output of a command and treat it as though it was written on the command line. For example, if you want to set the variable X to the output of a command, the way you do this is via command substitution.
There are two means of command substitution: brace expansion and backtick expansion.
Brace expansion workls as follows: $(commands) expands to the output of commands This permits nesting, so commands can include brace expansions
Backtick expansion expands `commands` to the output of commands
An example is given;:

#!/bin/bash
files="$(ls)"
web_files=`ls public_html`
echo "$files"      # we need the quotes to preserve embedded newlines in $files
echo "$web_files"  # we need the quotes to preserve newlines 
X=`expr 3 \* 2 + 4` # expr evaluate arithmatic expressions. man expr for details.
echo "$X"
The advantage of the $() substitution method is almost self evident: it is very easy to nest. It is supported by most of the bourne shell varients (the POSIX shell or better is OK). However, the backtick substitution is slightly more readable, and is supported by even the most basic shells (any #!/bin/sh version is just fine)
Note that if strings are not quote-protected in the above echo statement, new lines are replaced by spaces in the output.

Bash Scripting Tutorial

Lets begin this bash scripting tutorial with a simple "Hello World" script. Let's start with Learning the bash Shell: Unix Shell Programming.

1. Hello World Bash Shell Script

First you need to find out where is your bash interpreter located. Enter the following into your command line:

$ which bash
bash interpreter location: /bin/bash
Open up you favorite text editor and a create file called hello_world.sh. Insert the following lines to a file:
NOTE:Every bash shell script in this tutorial starts with shebang:"#!" which is not read as a comment. First line is also a place where you put your interpreter which is in this case: /bin/bash.
Here is our first bash shell script example:
#!/bin/bash
# declare STRING variable
STRING="Hello World"
#print variable on a screen
echo $STRING

Navigate to a directory where your hello_world.sh is located and make the file executable:
$ chmod +x hello_world.sh 
Make bash shell script executable
Now you are ready to execute your first bash script:
./hello_world.sh 
Example of simple bash shell script

2. Simple Backup bash shell script

#!/bin/bash
tar -czf myhome_directory.tar.gz /home/linuxconfig


Simple Backup bash script

3. Variables

In this example we declare simple bash variable and print it on the screen ( stdout ) with echo command.
#!/bin/bash
 STRING="HELLO WORLD!!!"
 echo $STRING 
Bash string Variables in bash script
Your backup script and variables:
#!/bin/bash
 OF=myhome_directory_$(date +%Y%m%d).tar.gz
 tar -czf $OF /home/linuxconfig 
Bash backup Script with bash Variables

3.1. Global vs. Local variables

#!/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 $VAR
bash
# Note the bash global variable did not change
# "local" is bash reserved word
echo $VAR
Global vs. Local Bash variables in bash script

4. Passing arguments to the bash script

#!/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 
Passing arguments to the bash script

5. Executing shell commands with bash

#!/bin/bash
# use backticks " ` ` " to execute shell command
echo `uname -o`
# executing bash command without backticks
echo uname -o 
Executing shell commands with bash

6. Reading User Input

#!/bin/bash
 
echo -e "Hi, please type the word: \c "
read  word
echo "The word you entered is: $word"
echo -e "Can you please enter two words? "
read word1 word2
echo "Here is your input: \"$word1\" \"$word2\""
echo -e "How do you feel about bash scripting? "
# read command now stores a reply into the default build-in variable $REPLY
read
echo "You said $REPLY, I'm glad to hear that! "
echo -e "What are your favorite colours ? "
# -a makes read command to read into an array
read -a colours
echo "My favorite colours are also ${colours[0]}, ${colours[1]} and ${colours[2]}:-)" 
Reading User Input with bash

7. Bash Trap Command

#!/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!!!" 

8. Arrays

8.1. Declare simple bash 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}]}
done 
Declare simple bash array

8.2. Read file into bash array

#!/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
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<&-
Bash script execution with an output:
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 the [ and ] brackets! Without the spaces, it won't work!
#!/bin/bash
directory="./BashScripting"

# bash check if directory exists
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]? "
# 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 
Nested Bash if else statement

10. Bash Comparisons

10.1. Arithmetic Comparisons

-lt <
-gt >
-le <=
-ge >=
-eq ==
-ne !=
#!/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 s1 string s1 is not empty
-z s1 string s1 is empty
#!/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 filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check 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
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 

12. Loops

12.1. Bash for loop

#!/bin/bash

# bash for loop
for f in $( ls /var/ ); do
 echo $f
done 
Running for loop from bash shell command line:
$ for f in $( ls /var/ ); do echo $f; done 
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 
Bash while loop

12.3. Bash until loop

#!/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
# 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.
}
function function_A {
        echo $1
}
function function_D {
        echo Function D.
}
function function_C {
        echo $1
}
# FUNCTION CALLS
# Pass parameter to function A
function_A "Function A."
function_B
# Pass parameter to function C
function_C "Function C."
function_D 
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, otherwise endless loop
  break  
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
    1) echo "You selected bash";;
    2) echo "You selected perl";;
    3) echo "You selected phyton";;
    4) echo "You selected c++";;
    5) exit
esac 
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 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"' 
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`" 
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.
\a alert (bell) \b backspace
\e an escape character \f form feed
\n newline \r carriage return
\t horizontal tab \v vertical tab
\\ backslash \` single quote
\nnn octal value of characters ( see [http://www.asciitable.com/ ASCII table] ) \xnn hexadecimal 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

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))' 
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
echo "2 ^ 2 =" $POWEROFTWO


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

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
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

HowTo Create Files in Linux From a Bash Shell Prompt

I'm a new to CentOS Linux user. How do I create a file from bash prompt without using GUI tools?

Linux / UNIX like operating system offers many command line tools and text editors for creating text files. You can use vi or joe text editor. It is a terminal-based text editor for Linux/Unix like systems, available under the GPL. It is designed to be easy to use. In short, you can use any one of the following tool:










  1. cat command
  2. echo or printf command
  3. vi text editor
  4. joe text editor
  5. Any other console based text editor

Create a Text File using cat command

To create a text file called foo.txt, enter:

$ cat > foo.txt

Output:

This is a test.
Hello world!
press CTRL+D to save file
 
To display file contents, type:

$ cat foo.txt

Create a text file using echo or printf

To create a file called foo.txt, enter:
 
echo 'This is a test' > foo.txt
 
OR
 
printf 'This is a test\n' > foo.txt
 
OR
 
printf 'This is a test\n Another line' > foo.txt
 
To display file contents, type:

 $ cat foo.txt

Create a Text File using joe text editor

JOE is text editor. To create a file called foo.txt, type:

 $ joe -help foo.txt


You will see help menu on screen. Next type something. To save the file and leave joe, by typing ^KX (press CTRL+K+X).

Create a Text File using vi / vim text editor

vi / vim is another text editor. To create a file called bar.txt, type:

$ vi bar.txt

Press 'i' to insert new text. To save the file and leave vi, type ESC+:+x (press ESC key, type : followed by x and [enter] key).