How to pass variable number of parameters to a shell command? -


i writing script backup this:

backup.sh:

dir="$1" mode="$2" delta="$3"  file in "$dir/backup."*".$mode.tar.gz";     [ "$file" -nt "$ref" ] && ref="$file" done  if [ "$delta" = "true" ];     delta_cmd=-n "'$ref'" fi  backup_file="$dir/backup.$(date +%y%m%d-%h%m%s).$mode.tar.gz"  case "$mode" in     config)         tar -cpzvf "$backup_file" $delta_cmd \             /etc \             /usr/local             ;;     # still other modes here... esac 

i want pass single variable $delta_cmd tar command tars files or delta files since last backup depending on value of $delta.

the above code creates error message , not tar delta files correctly if $delta set true. how fix it?

p.s: script better posix compatible.

as posix-compliant approach, consider:

set --                  # clear $@ if [ -f "$ref" ];   set -- "$@" -n "$ref" # add -n "$ref" $@ fi  tar ... "$@" ...        # expand $@ command line 

to put in context, , protect main argument list against overwrite, might like:

#!/bin/sh  main() {     # if current shell supports "local", prevent variables leaking     # ...some "posix" shells, such ash, fine this.     local dir mode delta target_file backup_file 2>&1 ||:      dir=$1     mode=$2     delta=$3      set -- # clear $@      file in "$dir/backup."*".$mode.tar.gz";         [ "$file" -nt "$ref" ] && ref="$file"     done      if [ "$delta" = "true" ];         set -- "$@" -n "$ref"     fi      target_file="$dir/backup.$(date +%y%m%d-%h%m%s).$mode.tar.gz"      case "$mode" in         config)             tar -cpzvf "$target_file" "$@" \                 /etc \                 /usr/local             ;;         # still other modes here...     esac }  main "$@" 

Comments