Bash Script Code Snippets

Below are some useful Bash Script code snippets for use in everyday projects.

Sometimes it may be necessary to accept input from the user so that it can be utilised within a script. This can be achieved using the 'read' function. Here, the input is placed into a variable called 'USER' and then displayed as part of a greeting.

#!/bin/bash

GREETING="Hello"

echo "Please enter your name:"
read USER

echo "$GREETING $USER!"

If desired, it is possible to send output to a text file. Here, the results of the list (ls) command are output to a text file. Using one greater than symbol will create the file if it doesn't already exist, or clear its contents if it does, before writing the output to it. Using two greater than symbols will create the file if it doesn't already exist or append the output to the end of the file if it does exist.

#!/bin/bash

# Output a list of script files to 'files.txt'.
ls -al *.sh > files.txt

# Append a list of text files to 'files.txt'.
ls -al *.txt >> files.txt