From 3dd5377492e80344d49a81684145b543f81c073f Mon Sep 17 00:00:00 2001 From: Russell Neches Date: Thu, 6 Jun 2019 01:14:33 -0700 Subject: [PATCH] describe ${foo} vs. $foo in for loops --- _episodes/04-redirection.md | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/_episodes/04-redirection.md b/_episodes/04-redirection.md index 9a43c61b..3c02ccb0 100644 --- a/_episodes/04-redirection.md +++ b/_episodes/04-redirection.md @@ -339,7 +339,33 @@ When the shell sees the keyword `for`, it knows to repeat a command (or group of Each time the loop runs (called an iteration), an item in the list is assigned in sequence to the **variable**, and the commands inside the loop are executed, before moving on to the next item in the list. Inside the loop, we call for the variable's value by putting `$` in front of it. The `$` tells the shell interpreter to treat the **variable** -as a variable name and substitute its value in its place, rather than treat it as text or an external command. +as a variable name and substitute its value in its place, rather than treat it as text or an external command. In shell programming, this is usually called "expanding" the variable. + +Sometimes, we want to expand a variable without any whitespace to its right. +Suppose we have a variable named `foo` that contains the text `abc`, and would +like to expand `foo` to create the text `abcEFG`. + +~~~ +$ foo=abc +$ echo foo is $foo +foo is abc +$ echo foo is $fooEFG # doesn't work +foo is +~~~ +{: .bash} + +The interpreter is trying to expand a variable named `fooEFG`, which (probably) +doesn't exist. We can avoid this problem by enclosing the variable name in +braces (`{` and `}`, sometimes called "squiggle braces"). + +~~~ +$ foo=abc +$ echo foo is $foo +foo is abc +$ echo foo is ${foo}EFG # now it works! +foo is abcEFG +~~~ +{: .bash} Let's write a for loop to show us the first two lines of the fastq files we downloaded earlier. You will notice shell prompt changes from `$` to `>` and back again as we were typing in our loop. The second prompt, `>`, is different to remind us that we haven’t finished typing a complete command yet. A semicolon, `;`, can be used to separate two commands written on a single line.