diff --git a/src/rhcsa.md b/src/rhcsa.md index b6c6a14..8e60786 100644 --- a/src/rhcsa.md +++ b/src/rhcsa.md @@ -302,17 +302,58 @@ nano myscript.sh ```bash #!/bin/bash echo "Hello, World!" + +### Variables ### +myvar="Hello, World!" +echo $myvar + +### Conditionals ### +if [ -f /etc/passwd ]; then + echo "File exists" +else + echo "File does not exist" +fi ``` +### Script to create a directory +> NOTE: When creating bash scripts you can use particular operators to check for the existence of a file (-f) or directory (-d). The +> following example uses the -d operator to check for the existence of a directory. Using conditional logic, if the script detects +> that the directory does not exist, the script will go ahead and create it. +```bash +#!/bin/bash +# Ask the user to enter a directory name +echo "Enter a directory name: " +# Read the user's input +read user_dir +# Check if the user_dir exists +if [ -d "$user_dir" ]; then + echo "The directory '$user_dir' already exists." +else + # Create the user_dir directory if it doesn't exist + mkdir "$user_dir" + echo "The directory '$user_dir' has been created." +fi +``` +> In a similar vein, you can check for the existence of a regular file using the -f operator. +```bash +#!/bin/bash +# Ask the user to enter a filename +echo "Enter a filename: " +# Read the user's input +read user_file - - - +# Check if the file exists +if [ -f "$user_file" ]; then + echo "The file '$user_file' exists." +else + echo "The file '$user_file' does not exist." +fi +```