Making an Interactive Script

Currently, the script uses the hardcoded value of mysite for the name of the new website. All of our websites won’t have the same name, so we can make the script more flexible by having it prompt us for the directory we want to create.

Using the $ operator

Let’s modify the variable declaration in our script so it uses the read command to prompt for the directory and assign the value for the directory variable. Then, we wrap each use of ${directory} with double quotes so we can support situations where a user might enter a directory name with spaces.

#!/usr/bin/env bash
set -e
read -p "Enter the name of the directory to create: " directory
mkdir -p "${directory}"/{images,scripts,styles}
touch "${directory}"/styles/style.css
cat << 'EOF' > "${directory}"/index.html

The read command displays the prompt and pauses the script’s execution. The user can then type the directory they want to create. When they press the “Enter” key, the value gets stored in the directory variable, and the script continues.

Why don’t we just wrap the whole line with double quotes like we’ve done in previous examples? The reason here is that the brace expansion on the mkdir line wouldn’t work. We could use double quotes around the other lines without issue, but it’s best to be consistent. We’re using the double quotes so that we support situations where the variable has spaces in its value, and we control the rest of the path.

Let’s execute the script. When prompted for a value, we enter mysite2:

./new_site.sh

We verify the new structure was created:

tree mysite2

Run the complete code on the terminal below for practice.

cat << "END" > new_site.sh
set -e
read -p "Enter the name of the directory to create: " directory
mkdir -p "${directory}"/{images,scripts,styles}
touch "${directory}"/styles/style.css
cat << 'EOF' > "${directory}"/index.html
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <title>My Website</title>
    <link rel="stylesheet" href="styles/style.css">
  </head>
  <body>
  </body>
</html>
EOF
END
chmod +x new_site.sh
./new_site.sh

Get hands-on with 1400+ tech skills courses.