Bash Script Example

Bash Script Example – In this Bash Tutorial, we shall look into an example Bash Script file and how to run it in bash shell.

About Bash Script File

  1. Bash Script file is a program that contains bash commands to be executed in sequence.
  2. For a file to be a bash script file, either the extension of it should be sh or the first line in the file should be #!/bin/bash. Look into Bash Extension for further details.
  3. For the bash script file to be executed, the user should have permissions to execute the script.
  4. If a command fails to get executed due to an error in its syntax or a run-time error, the execution is stopped there, and no further commands are executed.
  5. Bash Script file can have comments in between commands for improving the understandability.
  6. Bash Scripting, like other programming languages, has conditional statements, looping statements and many other commands which we shall learn in detail in due course of this tutorial.

Example Bash Script File

Following is an example bash script file.

Bash Script File

</>
Copy
#! /bin/bash

echo Welcome to learn Bash Scripting.

echo For an example we shall list files in the current directory

# this is a comment and ignored while execution

i=0
array=()
while read -r line
do
    array[ $i ]="$line"        
    (( i++ ))
done < <(ls -lt)

for fn in "${array[@]}"
do
    echo $fn
done

File permissions

~/workspace/bash$ ls -l bash-example
-rwxrwxrwx 1 tutorialkart tutorialkart 312 Dec  5 10:02 bash-example

Please observe that the file has permissions to be executed at user, group and administrator levels. You may modify those permissions according to your need using ‘chmod’ command.

To execute the Bash Script File, you may open a terminal in Ubuntu or Mac OS (which by default runs bash shell) or Bash Program in Windows, and execute the file as shown below (with ./ preceding the file name) :

~/workspace/bash$ ./bash-example 
Welcome to learn Bash Scripting.
For an example we shall list files in the current directory
total 168
-rwxrwxrwx 1 arjun arjun 312 Dec 5 10:02 bash-example
-rwxrwxrwx 1 arjun arjun 65 Dec 4 17:07 bash-substring-example
drwxrwxr-x 2 arjun arjun 4096 Dec 4 12:50 file

Conclusion

In this Bash Tutorial, we have written a Bash Script and learnt about the file permissions that it should have, to execute it.