Closed melodysyue closed 5 years ago
Basically, the $
tells bash to expand the next value (parameter expansion). In your example loop you have (I'm listing them in order of "simplicity" instead of the order they appear in the for loop):
$fastq_file
: This tells bash to expand the parameter (i.e. variable) fastq_file
to use the contents stored here. Since you're using this in a loop, the contents change each time the loop is run. It stores the value found at the current position in ${sample_files[@]}
(see below for an explanation of what this is).
$results_file
: This tells bash to expand the parameter (i.e. variable) results_file
to use the contents stored here. In this instance, results_file
will contain the output of "$(basename $fastq_file .fastq)-stats.txt"
. The value will change each time the loop runs.
${sample_files[@]}
: This tells bash to expand the array called sample_files[]
. Using the [@]
notation in the array tells bash to expand the entire array (i.e. return all of the values at each position in the array). If your array contains something like: fastq1.fastq fastq2.fastq fastq3.fastq fastq.4
, then the [@]
tells bash to "show" all of those file names. In essence your for loop could be re-written to look like this, without the array: for fastq_file in fastq1.fastq fastq2.fastq fastq3.fastq fastq.4
. This is the equivalent of expanding the entire array.
$(basename $fastq_file .fastq)
: This is an example of command substitution. It tells bash to run the basename
command and then return the output. This also has the added complexity of using a variable ($fastq_file
) as the input for the basename
command. The entire line is even more complex because it appends additional text (-stats.txt
) to the output of the command.
FYI, you may see these two forms of referring to bash variables:
$results_file
${results_file}
In essence, these are equivalent, but the latter is the "best practice" way to refer to variables, as it leads to scripts that are easier to read, helps avoid some pitfalls associated with typos, and allows greater flexiblity with appending to variables' outputs.
On p. 436 on the textbook, it gives an example of the loop script in bash:
There is
$
all over the script. Does anyone know the function of$
? Thanks:)