0
#!/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

3
  • 1
    BTW, all-caps names are used for variables with meaning to the OS or shell; variables you define yourself should have at least one lower-case character in their names. See paragraph 4 of the relevant POSIX spec at pubs.opengroup.org/onlinepubs/9699919799/basedefs/… Commented Feb 24, 2018 at 17:19
  • 1
    (Also, you can't use variables in a brace expansion such as {2..$#} -- see BashPitfalls #33). Commented Feb 24, 2018 at 17:20
  • 1
    ...actually, brace expansion for numeric ranges isn't guaranteed to work with /bin/sh at all, even with constants. Commented Feb 24, 2018 at 17:25

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.