1

Please could somebody explain how lines 3 and 8 work in this portion from a BASH script that I'm a bit confused with? It's to work out which USB drive to use for a backup. Many thanks.

1 WEEK_NO=`date +%U | sed -e 's/^0\+//g'`
2
3 (( USB_NN_IDX = $WEEK_NO % 2 ))
4
5 USB_DRIVES[0]="usb03"
6 USB_DRIVES[1]="usb04"
7
8 USB_NN=${USB_DRIVES[$USB_NN_IDX]}
1
  • Many thanks all. You've made me understand it now.
    – sixnumber
    Jun 28, 2012 at 11:54

4 Answers 4

3

On line 3 double parentheses are used in order to make sure that the expression between them is evaluated as arithmetic expression. $WEEK_NO % 2 returns the remainder of the division of $WEEK_NO by 2, so the result is always 0 or 1, depending on the $WEEK_NO (if it's even, result is 0; if it's odd, result is 1).

USB_DRIVES is an indexed array, and depending on the result of the evaluation on line 3, on line 8 one of its values is retrieved.

You can look at man 1 bash for more information. The relevant information is in the ARITHMETIC EVALUATION and Arrays sections.

0
1
(( USB_NN_IDX = $WEEK_NO % 2 ))

This one is used for calculation. It will let USB_NN_IDX equal to the remainder of an integer division operation variable WEEK_NO to 2.

USB_NN=${USB_DRIVES[$USB_NN_IDX]}

this one will let USB_NN variable equal to one of USB_DRIVES[0] or USB_DRIVES[1] depending on USB_NN_INX value. You can use any implementation in bash to equal one variable to another from following:

A=$B
A=${B}

both are allowed and last one is used here. Also in array you can use index as variable two.

1

The (( )) notation is a shorthand for let, read more here. So:

(( USB_NN_IDX = $WEEK_NO % 2 ))

Sets USB_NN_IDX to modulo 2 of week number, i.e. 0 or 1. This number is used as an index into the USB_NN array.

1

Line 3 ((...)) - is just an integer math embedded into shell. "%" - is a MODULO/REMINDER operator, complementary to the "/" that return integer part of division. In your case line 3 return 0 or 1 depends on week-number. Then that number substituted into device name USBx - USB_0 or USB_1.

Seems like backups written on a different flash-drives depends on even/odd week-number.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .