Last Updated: February 25, 2016
·
6.502K
· stucki

Prefix all elements of a bash variable with a string

For my work, I often need to dump databases using mysqldump. What annoys me a lot about this tool is that ignored tables need to be specified using

--ignore-table=<database>.<tablename>

This can easily grow to a huge list of the same parameter.

Luckily, I discovered that bash provides a feature to prefix every element of a variable with a string:

MYLIST=(var1 var2 var3)
echo ${MYLIST[@]/#/my_}
# Output: my_var1 my_var2 my_var3

Put together, you can use this script to dump a database with mysqldump:

DATABASE="database1"
IGNORE_TABLES=(table1 table2 table3)
echo mysqldump ${IGNORE_TABLES[@]/#/--ignore-table=${DATABASE}.} ${DATABASE}
# Output: mysqldump --ignore-table=database1.table1 --ignore-table=database1.table2 --ignore-table=database1.table3 database1

PS: It's also possible to set a suffix by using "%" instead of "#".