Pass command arguments as a variable

I have made a bash script to back up my AWS Ligthsail server with restic. Everything works finally, but there is one thing I couldn't find an answer.

Just the part where the problem is:

//Settings
forget_policy=(--keep-within-daily 7d --keep-within-weekly 1m --keep-within-monthly 1y --keep-within-yearly 2y)
//(… other code)
forget_old () { # Forget and prune restic -r $RESTIC_REPOSITORY forget "${forget_policy}" --prune | log # Check if exit status is ok status=$? if [ $status -ne 0 ]; then log "Forget failed ${status}" exit 1 fi
}
//(… other code)
forget_old

Output

>> invalid argument "--prune" for "--keep-within-daily" flag: no number found

I can't pass the $forget_policy variable to the forget command. When I wrap the varibale in "" I get

>> unknown flag: --keep-within-daily 7d --keep-within-weekly 1m --keep-within-monthly 1y --keep-within-yearly 2y

When I copy the variable content directly to the command, it works. So I must be doing something wrong with passing the variable.

1 Answer

To expand each of the elements of your argument array as a separate word you need "${forget_policy[@]}"

"${forget_policy}" is equivalent to "${forget_policy[0]}" so only expands to the first argument - which is why you end up with --keep-within-daily --prune

See the Arrays subsection under PARAMETERS in the bash manual page.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like