Score:0

Pass command arguments as a variable

ar flag

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.

Score:1
hr flag

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.

Rever_2019 avatar
ar flag
Thanks. I do (sadly) not enough bash scripting. Didn't notice I turned it to an array, adding the (). Before, I had just "forget_policy="--keep-within-daily 7d --…". That's just a string and didn't work. Had googeled and found the "array version"
hr flag
@Rever_2019 in that case it was a happy accident - using an array is exactly the right way to handle this kind of argument list ;)
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.