Skip to main content

Variables

As you write more complicated scripts you need to use variables to make it more flexible. The way to do this is to use variables. Can you imagine writing code without use variables? It's possible, I suppose, but certainly not fun. And let's not do it!

Setting a Variable

This is a short section! It's very easy to set a variable. and you've already done it. Modify ~/bin/gen_files to be as follow:

#! /bin/bash

DESTINATION=~/temp
FILE_PREFIX=file

mkdir -p $DESTINATION
cd $DESTINATION
touch ${FILE_PREFIX}{1..10}.txt
echo done
What Changed?

You can use quotes too, optionally.
You do not have to make them uppercase though I suggest you do as that's what's normal for bash scripts.NAME=value

User Input

So what if we want users to be able to define the file prefix? Easy! There's a program called that will get user input and define a variable based on it. Try it by running

#! /bin/bash

DESTINATION=~/temp
read -p "enter a file prefix: " FILE_PREFIX

mkdir -p $DESTINATION
cd $DESTINATION
touch ${FILE_PREFIX}{1..10}.txt
echo done

The flag allows us to prompt the user with a string, letting them know what we're expecting -p

Arguments

What if we want the user to be able to pass in the path to where we want to create the directory?

We can do that via arguments (sometimes called parameters too.) We want the user to be able say and use that input as $DESTINATION. Easy! gen_files ~/different_directory

#! /bin/bash

DESTINATION=$1
read -p "enter a file prefix: " FILE_PREFIX

mkdir -p $DESTINATION
cd $DESTINATION
touch ${FILE_PREFIX}{1..10}.txt
echo done