2

I'm trying to assign everything else after strings to $@ but orange is also picked. I thought the shift will take as rest of the args but the output is picking orange too.

$ cat try.sh
#!/usr/bin/bash

str1="$1"
str2="$2"; shift

echo "$str1"
echo "$str2"

for i in "$@"
do
echo "rest are $i"
done

./try.sh apple orange 3 4 5
apple
orange
rest are orange
rest are 3
rest are 4
rest are 5
1
  • Type help shift in a bash session. Commented Jun 13, 2013 at 23:32

1 Answer 1

3

You need to do shift twice to get rid of both apple and orange. a single shift will only shift off one parameter, no matter where in the code it is - it's NOT related to which parameter was last accessed/assigned from.

 str1="$1"
 str2="$2"; shift ; shift

or

 str1="$1"; shift
 str2="$1"; shift # Notice that due to prior shift, orange now is in $1, not $2
Sign up to request clarification or add additional context in comments.

1 Comment

Or use shift 2 -- specifying the number to shift is commonly used in script that employ getopts: after parsing options, you'd use shift $((OPTIND-1))

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.