Bash functions

Like many programming languages, we can create functions on the shell to execute as a program. In this example, we look at a simple bash function that does the following:

  • create a directory called sample_directory
  • navigate into that directory
  • create a file called sample_file.txt
  • Add some text into that sample file

To create this function, create a bash file using vi

$ vi
create_sample_file() {
    echo "Creating sample_directory"
    mkdir sample_directory
    cd sample_directory
    echo "Creating sample_file.txt"
    touch sample_file.txt 
    echo "This is a sample file" >> sample_file.txt        
Bash Function 1

In order to use the function as a command, we need to source the file that contains the functions.

$ source
$ create_sample_file
Bash Function 2

In the above example, I use cat and pwd to check if the file has been created.