Please enable JavaScript eh!

 ⌘ Web Mechanic ⌘ 

Bash Scripting


Coding

I think we can start with some actual bash coding now.

This is a preview for scripting, to get you used to thinking as a programmer.

Since programming is about solving problems, let's solve a problem eh!

For this we need to know how to get input from the user. This is done with the read command. Imagine that!

This is not quite scripting yet, but are 1-liners - all the commands are entered on the command line, separated by a semi-colon ';'.

In Terminal, enter the following text EXACTLY as it appears, all on one line, then hit Enter / return:

echo "What's your name:";read name;echo "Hey $name, good to see you."

NO CHEATING! DON'T COPY & PASTE

Answer the question and again hit Enter / return.

There are 3 commands in that line:

In the first one, we had to use quotes to allow the single quote in "What's".

Next we use the read command to get something from the user.

Finally we echo their response to the screen.

What's your name:
Fubar The Forth
Hey Fubar the Forth, good to see you.

This might be considered a milestone. You've successfully gotten some input from a user, and correctly read it into a variable, then printed the contents of that variable to the screen.

We can read several variables this way if needed:

Try this:

echo Enter some stuff:;read one two three four; echo Thanks. You entered $one $two $three $four

This is looking for 4 inputs and will echo them back.

Make sure your Terminal window is wide enough to see that whole string - it ends with '$four'.

Now see what happens ...

echo Enter some stuff:;read one two three four; echo Thanks. You entered $one $two $three $four
Enter some stuff:
once twice thrice forth
Thanks. You entered once twice thrice forth

Excellent, each word we entered was put into a separate variable - good to know.

But there's a twist with the read command. Using the history navigation trick, click the Up Arrow once to get the previous text, then hit Enter / return. Enter the following when asked:

a b c d e f g h i j k l m n o p q r s t u v w x y z
... and you should get back ...
Thanks. You entered a b c d e f g h i j k l m n o p q r s t u v w x y z

Whooaaa! What happened there? I entered the whole alphabet, but it still printed them all. Not just 4.

This is a feature of the read command:
If there are more words than variables, any excess words are assigned to the last variable.
If the variables are left out completely, the whole line is assigned to the REPLY variable.

The followng command is missing any variables for the read, but still works:

echo Enter some stuff:; read; echo Thanks. You entered $REPLY
Enter some stuff:
once twice thrice
Thanks. You entered once twice thrice

Well, that was instructive. It gives the programmer some options depending on what they are expecting.

Speaking of options, read has a few you can use depending on your situation:

Arrays