sr320 / course-fish546-2018

7 stars 2 forks source link

$ sign in loop in Bash #44

Closed melodysyue closed 5 years ago

melodysyue commented 5 years ago

On p. 436 on the textbook, it gives an example of the loop script in bash:

for fastq_file in ${sample_files[@]} 
do
   results_file="$(basename $fastq_file .fastq)-stats.txt"
   fastq_stat $fastq_file > stats/$results_file
done

There is $ all over the script. Does anyone know the function of $? Thanks:)

kubu4 commented 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):

FYI, you may see these two forms of referring to bash variables:

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.