M. Abra
M. Abra

Reputation: 101

Looping through arguments in Shell Scripting skipping the first argument

#!/bin/sh
BACKUPDIR=$1
for argnum in {2..$#};do
    echo ${"$argnum"}
done

I have tried this but it gives me this error: ./backup.sh: 10: ./backup.sh: Bad substitution

Upvotes: 0

Views: 38

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295530

Use the shift command to remove $1 from the argument list after you're done reading it (thus renumbering your old $2 to $1, your old $3 to $2, etc):

#!/bin/sh
backupdir=$1; shift
for arg; do
  echo "$arg"
done

To provide a literal (but not-particularly-good-practice) equivalent to the code in the question, indirect expansion (absent such security-impacting practices as eval) looks like the following:

#!/bin/bash
#      ^^^^-- This IS NOT GUARANTEED TO WORK in /bin/sh

# not idiomatic, not portable to baseline POSIX shells; this is best avoided
backupdir=$1
for ((argnum=2; argnum<=$#; ++argnum)); do
  echo "${!argnum}"
done

Upvotes: 2

Related Questions