Reputation: 1702
I need to get three arguments by test.ksh script as the following
./test.ksh 12 34 AN
is it possible to set the argument by counter for example ?
for get_arg 1 2 3
do
my_array[get_arg]=$$get_arg
print ${my_array[get_arg]}
done
in this example I want to get three arguments from the user by loop counter "$$get_arg" in place of $1 $2 $3
is it possible? and how ?
Upvotes: 0
Views: 672
Reputation: 6064
Even you don't need in $@
, this would work the same:
#!/bin/bash
i=0
for arg; do
my_array[i]="$arg"
echo "${my_array[i]}"
(( i++ ))
done
That is,
if
in words
is not present, thefor
command executes the commands once for each positional parameter that is set, as ifin $@
had been specified.
Upvotes: 0
Reputation: 754490
my_array=("$@")
for i in 0 1 2
do
echo "${my_array[$i]}"
done
This assigns all the arguments to array my_array
; the loop then selects the first three arguments for echoing.
If you're sure you want the first three arguments in the array, you could use:
my_array=("$1" "$2" "$3")
If you want the 3 arguments at positions 1, 2, 3 in the array (rather than 0, 1, 2), then use:
# One or the other but not both of the two assignments
my_array=("dummy" "$@")
my_array=("dummy" "$1" "$2" "$3")
for i in 1 2 3
do
echo "${my_array[$i]}"
done
Upvotes: 1
Reputation: 18232
Edit: My bad ksh:
for arg;do
print $arg
done
Original Post: Use shift to iterate through shell script parameters:
# cat test.sh
#!/bin/bash
while [ "$1" != "" ]; do
echo $1
shift
done
test run:
# ./test.sh arg1 monkey arg3
arg1
monkey
arg3
Upvotes: 0
Reputation: 1768
bash has a special variable
$@
which contains the arguments of the script it currently executes. I think this is what your'e looking for:
for arg in $@ ; do
# code
done
Upvotes: 0