1

I am trying to write a simple Bash script that shows the difference between two variables, with the assumption that both variables contain identical parameters with different values. Look at $sam and $pish variables. They are identical, except parameter driver_mode is 1 in $sam, and 2 in $pish. To do this comparison, I store each variable into a separate array, and then compare each element one by one.

#!/bin/bash sam="driver_mode=2 firmware_path=/home/release/firmware/ onebox_zone_enabled=0x10001 ta_aggr=4 skip_fw_load=0 fw_load_mode=1 sdio_clock=40000 enable_antenna_diversity=0 coex_mode=1 obm_ant_sel_val=2 wlan_rf_power_mode=0 bt_rf_power_mode=0 zigb_rf_power_mode=0 country_code=840 bt_rf_tx_power_mode=1 bt_rf_rx_power_mode=0" pish="driver_mode=1 firmware_path=/home/release/firmware/ onebox_zone_enabled=0x10001 ta_aggr=4 skip_fw_load=0 fw_load_mode=1 sdio_clock=40000 enable_antenna_diversity=0 coex_mode=1 obm_ant_sel_val=2 wlan_rf_power_mode=0 bt_rf_power_mode=0 zigb_rf_power_mode=0 country_code=840 bt_rf_tx_power_mode=1 bt_rf_rx_power_mode=0" read -r -a array_old <<< "$sam" read -r -a array_new <<< "$pish" for index in "${!array_old[@]}"; do if [[ ${array_old[index]} -ne ${array_new[index]} ]]; then echo ${array_old[index]} 'to' ${array_new[index]} fi done 

Running the above bash script gives me error:

./test: line 12: firmware_path=/home/release/firmware/: syntax error: operand expected (error token is "/home/release/firmware/")

1 Answer 1

5

The -ne operator is an integer comparison operator. To compare strings use !=:

for index in "${!array_old[@]}"; do if [[ ${array_old[index]} != "${array_new[index]}" ]]; then echo ${array_old[index]} 'to' ${array_new[index]} fi done 
Sign up to request clarification or add additional context in comments.

3 Comments

I'd like to +1 because of your first paragraph, but then your last one cancels it out by being wrong in the exact way that the first paragraph was right. (Namely: the reason you can write index rather than $index is that array indices are an arithmetic context, exactly like the arguments of -ne.)
@ruakh it's fixed now ;-)
@ruakh, indeed, as ${!array_old[@]} expands to numeric indices. I'm used to use indices in string context, and completely forgot about this feature. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.