Master Bash Scripting Exercises with Environment Variables
1.
Environment Variable Basics:
Write a Bash script to set an environment variable named TEMP_VAR to store your name. Print its value to confirm it's set correctly.
Code:
#!/bin/bash
# Set the TEMP_VAR environment variable to store your name
export TEMP_VAR="Jennifer Maryse"
# Print the value of TEMP_VAR to confirm it's set correctly
echo "The value of TEMP_VAR is: $TEMP_VAR"
Output:
ad@DESKTOP-3KE0KU4:~$ ./test1.sh The value of TEMP_VAR is: Jennifer Maryse
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Set Environment Variable: export TEMP_VAR="YourName"
- Sets the environment variable 'TEMP_VAR' to the specified name (YourName).
- The "export" command ensures the variable is available to any child processes started from the script.
- Print the Value: echo "The value of TEMP_VAR is: $TEMP_VAR"
- Prints the value of the 'TEMP_VAR' to the terminal to confirm it has been set correctly.
- The '$TEMP_VAR' syntax is used to access.
2.
Exporting Variables:
Write a Bash script that exports MY_VAR so that it's available to child processes. Check its availability in a new terminal window.
Code:
#!/bin/bash
# Set the MY_VAR environment variable to a specified value
export MY_VAR="Exported_Value"
# Print the value of MY_VAR to confirm it's set and exported
echo "The value of MY_VAR is: $MY_VAR"
# Start a new Bash shell to act as a child process and print the value of MY_VAR
bash -c 'echo "The value of MY_VAR in the child process is: $MY_VAR"'
Output:
ad@DESKTOP-3KE0KU4:~$ ./test1.sh The value of MY_VAR is: Exported_Value The value of MY_VAR in the child process is: Exported_Value
Explanation:
In the exercise above,
- Script:
- The script sets and exports 'MY_VAR' to ensure it is available to child processes.
- It then starts a new Bash shell to act as a child process and checks if 'MY_VAR' is accessible in this child process.
- Checking in a New Terminal:
- Opening a new terminal and running echo $MY_VAR verifies whether 'MY_VAR' is available outside the script's scope.
- Adding the export command to ~/.bashrc or ~/.bash_profile ensures 'MY_VAR' is available in all new terminal sessions.
3.
Path Manipulation:
Write a Bash script to add a directory to the PATH variable, allowing you to execute scripts or binaries from that directory without specifying the full path.
Code:
#!/bin/bash
# Specify the directory you want to add to the PATH
NEW_DIR="/path/to/directory"
# Add the directory to the PATH variable
export PATH="$PATH:$NEW_DIR"
# Print the new PATH to confirm the directory was added
echo "The updated PATH is: $PATH"
Output:
dt@DESKTOP-3KE0KU4:~$ ./test1.sh The updated PATH is: /home/dt/bin:/home/dt/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/mnt/c/Program Files/Common Files/Oracle/Java/javapath:/mnt/c/Windows/system32:/mnt/c/Windows:/mnt/c/Windows/System32/Wbem:/mnt/c/Windows/System32/WindowsPowerShell/v1.0/:/mnt/c/Windows/System32/OpenSSH/:/mnt/c/Program Files (x86)/NVIDIA Corporation/PhysX/Common:/mnt/c/Program Files/NVIDIA Corporation/NVIDIA NvDLISR:/mnt/c/Program Files (x86)/Intel/Intel(R) Management Engine Components/DAL:/mnt/c/Program Files/Intel/Intel(R) Management Engine Components/DAL:/mnt/h/bin:/mnt/c/Program Files/dotnet/:/mnt/c/Program Files/Graphviz/bin:/mnt/c/WINDOWS/system32:/mnt/c/WINDOWS:/mnt/c/WINDOWS/System32/Wbem:/mnt/c/WINDOWS/System32/WindowsPowerShell/v1.0/:/mnt/c/WINDOWS/System32/OpenSSH/:/mnt/c/Program Files (x86)/dotnet/:/mnt/c/Program Files/nodejs/:/mnt/c/Users/ME/poppler-23.08.0/Library/bin:/mnt/c/Program Files/Java/jre:/mnt/c/Program Files/Java/javafx-sdk-21/lib:/mnt/c/Program Files/PuTTY/:/mnt/c/Users/ME/.cadto/bin:/mnt/c/Users/ME/AppData/Local/Microsoft/WindowsApps:/mnt/c/Users/ME/.dotnet/tools:/mnt/c/Users/ME/AppData/Roaming/npm:/mnt/i/python:/mnt/c/Program Files/Java/javafx-sdk-21/lib:/snap/bin:/path/to/directory
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Specify Directory: NEW_DIR="/path/to/directory"
- Defines the directory you want to add to the "PATH" variable. Replace /path/to/directory with the actual path.
- Add to PATH: export PATH="$PATH:$NEW_DIR"
- Appends the specified directory to the current "PATH" variable using 'export' to ensure it is available to any child processes.
- Print PATH: echo "The updated PATH is: $PATH"
- Prints the updated "PATH" variable to confirm the directory has been added.
4.
Using Environment Variables in Scripts:
Write a Bash script that greets the user using the value of MY_VAR. Run the script to ensure it displays the expected greeting.
Code:
#!/bin/bash
# Check if MY_VAR is set
if [ -z "$MY_VAR" ]; then
echo "MY_VAR is not set. Please set it and try again."
exit 1
fi
# Greet the user using the value of MY_VAR
echo "Hello, $MY_VAR! Welcome to the system."
Output:
rg@DESKTOP-3KE0KU4:~$ ./test1.sh MY_VAR is not set. Please set it and try again.
rg@DESKTOP-3KE0KU4:~$ export MY_VAR="Jennifer Maryse" rg@DESKTOP-3KE0KU4:~$ ./test1.sh Hello, Jennifer Maryse! Welcome to the system.
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Check if MY_VAR is set:
- if [ -z "$MY_VAR" ]; then: Checks if 'MY_VAR' is empty or not set. The -z flag returns true if the string is null (empty).
- echo "MY_VAR is not set. Please set it and try again.": Prints an error message if 'MY_VAR' is not set.
- exit 1: Exits the script with a non-zero status code, indicating an error.
- Greet the user:
- echo "Hello, $MY_VAR! Welcome to the system.": Prints a greeting message using the value of 'MY_VAR'.
5.
Conditional Scripting:
Write a Bash script that checks if MY_VAR is set. If it's set, display a personalized message; otherwise, prompt the user to set it.
Code:
#!/bin/bash
# Check if MY_VAR is set
if [ -z "$TEMP_VAR" ]; then
# If MY_VAR is not set, prompt the user to set it
echo "TEMP_VAR is not set. Please set it using the following command:"
echo "export TEMP_VAR=\"YourName\""
else
# If MY_VAR is set, display a personalized message
echo "Hello, $TEMP_VAR! Welcome to the system."
fi
Output:
dt@DESKTOP-3KE0KU4:~$ ./test1.sh TEMP_VAR is not set. Please set it using the following command: export TEMP_VAR="YourName"
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Check if MY_VAR is Set:
- if [ -z "$MY_VAR" ]; then: Checks if 'MY_VAR' is empty or not set. The -z flag returns true if the string is null (empty).
- Prompt to set MY_VAR:
- echo "MY_VAR is not set. Please set it using the following command:": Prints a message indicating that 'MY_VAR' is not set.
- echo "export MY_VAR=\"YourName\"": Provides a command for the user to set 'MY_VAR'.
- Display a Personalized message:
- else: Executes this block if 'MY_VAR' is set.
- o echo "Hello, $MY_VAR! Welcome to the system.": Prints a personalized greeting using the value of 'MY_VAR'.
6.
Script Parameterization:
Write a Bash script that modify the greeting script to accept a parameter. If the parameter is provided, use it as the name to greet; otherwise, default to MY_VAR.
Code:
#!/bin/bash
# Check if a parameter is provided
if [ -n "$1" ]; then
# If a parameter is provided, use it as the name
NAME="$1"
else
# If no parameter is provided, check if MY_VAR is set
if [ -z "$MY_VAR" ]; then
# If MY_VAR is not set, prompt the user to set it
echo "MY_VAR is not set and no parameter provided. Please set MY_VAR using the following command:"
echo "export MY_VAR=\"YourName\""
exit 1
else
# If MY_VAR is set, use it as the name
NAME="$MY_VAR"
fi
fi
# Greet the user with the determined name
echo "Hello, $NAME! Welcome to the system."
Output:
rg@DESKTOP-3KE0KU4:~$ ./test1.sh Hello, Jennifer Maryse! Welcome to the system. rg@DESKTOP-3KE0KU4:~$ ./test1.sh Zuberi Hello, Zuberi! Welcome to the system. rg@DESKTOP-3KE0KU4:~$
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Check for parameter:
- if [ -n "$1" ]; then: Checks if the first positional parameter ('$1') is provided. The -n flag returns true if the string is not null (non-empty).
- Use the parameter as a Name:
- NAME="$1": If a parameter is provided, it assigns the parameter value to the NAME variable.|
- Check for MY_VAR:
- if [ -z "$MY_VAR" ]; then: Checks if 'MY_VAR' is empty or not set. The -z flag returns true if the string is null (empty).
- If 'MY_VAR' is not set and no parameter is provided, the script prompts the user to set 'MY_VAR' and exits with a non-zero status code (exit 1).
- Use MY_VAR as a Name:
- NAME="$MY_VAR": If no parameter is provided but 'MY_VAR' is set, it assigns the value of 'MY_VAR' to the 'NAME' variable.
- Greet the User:
- echo "Hello, $NAME! Welcome to the system.": Prints a greeting message using the determined name.
7.
Environment Variable Substitution:
Write a Bash script that uses the value of HOME environment variable to create a backup script that automatically backs up specific directories to your home directory.
Code:
#!/bin/bash
# Define the directories to back up
DIRECTORIES_TO_BACKUP=("/path/to/directory1" "/path/to/directory2")
# Define the backup destination directory using the HOME environment variable
BACKUP_DESTINATION="$HOME/backup"
# Create the backup destination directory if it doesn't exist
mkdir -p "$BACKUP_DESTINATION"
# Loop through each directory and back it up
for DIR in "${DIRECTORIES_TO_BACKUP[@]}"; do
# Get the base name of the directory (e.g., directory1 from /path/to/directory1)
DIR_BASENAME=$(basename "$DIR")
# Create a tar.gz archive of the directory and save it to the backup destination
tar -czf "$BACKUP_DESTINATION/$DIR_BASENAME-$(date +%Y%m%d).tar.gz" -C "$(dirname "$DIR")" "$DIR_BASENAME"
done
# Print a message indicating the backup is complete
echo "Backup completed successfully to $BACKUP_DESTINATION"
Output:
dt@DESKTOP-3KE0KU4:~$ ./test1.sh Backup completed successfully to /home/dt/backup
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Define Directories to Back Up:
- DIRECTORIES_TO_BACKUP=("/path/to/directory1" "/path/to/directory2")
- An array of directories you want to back up. Replace /path/to/directory1 and /path/to/directory2 with the actual directories.
- Define Backup Destination:
- BACKUP_DESTINATION="$HOME/backup"
- Uses the HOME environment variable to set the backup destination to a backup directory within your home directory.
- Create Backup Destination Directory:
- mkdir -p "$BACKUP_DESTINATION"
- Creates the backup destination directory if it doesn't exist. The -p option ensures that no error is thrown if the directory already exists.
- Loop Through Each Directory:
- for DIR in "${DIRECTORIES_TO_BACKUP[@]}"; do ... done
- Loops through each directory in the DIRECTORIES_TO_BACKUP array.
- Get Base Name of Directory:
- DIR_BASENAME=$(basename "$DIR")
- Extracts the base name of the directory (e.g., 'directory1' from /path/to/directory1).
- Create Tar.gz Archive:
- tar -czf "$BACKUP_DESTINATION/$DIR_BASENAME-$(date +%Y%m%d).tar.gz" -C "$(dirname "$DIR")" "$DIR_BASENAME"
- Creates a compressed tarball of the directory and saves it to the backup destination. The tarball is named with the directory base name and the current date (YYYYMMDD format).
- Print Completion Message:
- echo "Backup completed successfully to $BACKUP_DESTINATION"
- Prints a message indicating the backup has been completed.
8.
Scripting with Environment Variables:
Write a Bash script that creates a new directory using the value of 'TMPDIR' environment variable. If 'TMPDIR' is not set, default to /tmp.
Code:
#!/bin/bash
# Check if TMPDIR is set; if not, default to /tmp
TARGET_DIR="${TMPDIR:-/tmp}"
# Define the name of the new directory
NEW_DIR_NAME="my_temp_directory"
# Create the new directory inside the target directory
NEW_DIR_PATH="$TARGET_DIR/$NEW_DIR_NAME"
# Create the directory
mkdir -p "$NEW_DIR_PATH"
# Print a message indicating the directory creation status
if [ $? -eq 0 ]; then
echo "Directory created successfully: $NEW_DIR_PATH"
else
echo "Failed to create directory: $NEW_DIR_PATH"
fi
Output:
dt@DESKTOP-3KE0KU4:~$ ./test1.sh Directory created successfully: /tmp/my_temp_directory
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Check TMPDIR and Set Target Directory:
- TARGET_DIR="${TMPDIR:-/tmp}"
- Uses the value of 'TMPDIR' if it is set; otherwise, defaults to /tmp. This is done using the parameter expansion syntax ${VAR:-default}.
- Define New Directory Name:
- NEW_DIR_NAME="my_temp_directory"
- Sets the name of the new directory to be created.
- Construct New Directory Path:
- NEW_DIR_PATH="$TARGET_DIR/$NEW_DIR_NAME"
- Constructs the full path of the new directory by combining the target directory and the new directory name.
- Create the Directory:
- mkdir -p "$NEW_DIR_PATH"
- Creates the new directory using the "mkdir" command. The -p option ensures that parent directories are created if they don't exist and prevents errors if the directory already exists.
- Print Creation Status:
- Checks the exit status of the "mkdir" command using "$?".
- If the exit status is 0 (success), it prints a success message.
- Otherwise, it prints a failure message.
9.
Error Handling:
Write a Bash script that checks if a required environment variable is set. If not, print an error message and exit with a non-zero status code.
Code:
#!/bin/bash
# Define the required environment variable
TEMP_VAR="TEMP_VARIABLE"
# Check if the required environment variable is set
if [ -z "${!TEMP_VAR}" ]; then
# If the required environment variable is not set, print an error message
echo "Error: The environment variable $TEMP_VAR is not set."
# Exit with a non-zero status code
exit 1
fi
# If the required environment variable is set, proceed with the rest of the script
echo "The environment variable $TEMP_VAR is set to: ${!TEMP_VAR}"
# Continue with the rest of the script
# (Add your additional script logic here)
Output:
rg@DESKTOP-3KE0KU4:~$ ./test1.sh Error: The environment variable TEMP_VARIABLE is not set.
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Define Required Environment Variable Name:
- TEMP_VAR="TEMP_VARIABLE"
- Specifies the name of the required environment variable. You can change this to the name of any required environment variable.
- Check if the Required Environment Variable is Set:
- if [ -z "${!TEMP_VAR}" ]; then: Checks if the environment variable is empty or not set. The ${!VAR} syntax is used to indirectly reference the variable named by TEMP_VAR.
- Print Error Message and Exit:
- echo "Error: The environment variable '$TEMP_VAR' is not set.": Prints an error message indicating that the required environment variable is not set.
- exit 1: Exits the script with a non-zero status code to indicate an error.
- Print Success Message:
- echo "The environment variable $TEMP_VAR is set to: ${!TEMP_VAR}": If the required environment variable is set, prints its value.
- Continue with Additional Script Logic:
- Add any additional script logic that should be executed if the required environment variable is set.
10.
Advanced Scripting with Environment Variables:
Write a Bash script that dynamically generates configuration files based on the values of environment variables. Test it by setting different variables and observing the generated configurations.
Code:
#!/bin/bash
# Define the configuration file path
CONFIG_FILE="app_config.conf"
# Set default values for the environment variables if they are not set
APP_NAME="${APP_NAME:-MyApp}"
APP_ENV="${APP_ENV:-development}"
APP_PORT="${APP_PORT:-8080}"
# Generate the configuration file
cat <<EOF> "$CONFIG_FILE"
# Application Configuration File
# Application Name
app_name = "$APP_NAME"
# Application Environment
app_env = "$APP_ENV"
# Application Port
app_port = "$APP_PORT"
EOF
# Print a message indicating that the configuration file has been generated
echo "Configuration file '$CONFIG_FILE' has been generated with the following content:"
cat "$CONFIG_FILE"
Output:
dt@DESKTOP-3KE0KU4:~$ ./test1.sh Configuration file 'app_config.conf' has been generated with the following content: # Application Configuration File # Application Name app_name = "MyApp" # Application Environment app_env = "development" # Application Port app_port = "8080"
Explanation:
In the exercise above,
- Shebang: #!/bin/bash
- Specifies the script should be run using the Bash shell.
- Define Configuration File Path:
- CONFIG_FILE="app_config.conf"
- Sets the path for the generated configuration file.
- Set Default Values for Environment Variables:
- APP_NAME="${APP_NAME:-MyApp}"
- APP_ENV="${APP_ENV:-development}"
- APP_PORT="${APP_PORT:-8080}"
- Uses parameter expansion to set default values for 'APP_NAME', 'APP_ENV', and 'APP_PORT' if they are not already set.
- Generate Configuration File:
- cat <<EOF > "$CONFIG_FILE"
- Uses a here document (<<EOF) to write multiple lines to the configuration file.
- The EOF marker indicates the end of the here document.
- The configuration file includes the values of the environment variables.
- Print Completion Message:
- echo "Configuration file '$CONFIG_FILE' has been generated with the following content:"
- Prints a message indicating that the configuration file has been generated.
- cat "$CONFIG_FILE": Displays the content of the generated configuration file.
Bash Editor:
More to Come !
Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics