In our class scripting assignment, we need to pass any number of directories as positional parameters, and our script (in the end) will calculate, display, and save to file certain informatio开发者_开发知识库n about the directories passed as parameters. We in turn need to do several tests upon the name of the file we wish to save our results to.
My question is no doubt a simple one, I am wondering how I take the info stored in $@
and pass it to a variable that I can then use for all of the testing I need to do.
You can use a for
loop to iterate through the $@
array as:
for arg in "$@"
do
# use $arg
done
$@ is a variable. So is $_ and $1, $2, ...
It sounds like what you want to do can be achieved through the use of "shift" and a loop ("for" or "while"). Alternatively, just use:
for i in $@; do ...; done
For your reference:
shift: shift [n]
The positional parameters from $N+1 ... are renamed to $1 ... If N is
not given, it is assumed to be 1.
for i in $@; do echo $i; done
where you replace echo $i with whatever you want to do with each argument.
You can also refer to arguments in $@
somewhat like an array. It is one, but you can't use array subscripts. You can, however, use array slicing:
echo ${@:3:1} # $@ is ONE-based
will echo
the third argument.
echo ${@:4:3}
will echo
the fourth, fifth and sixth arguments.
By the way, the "subscripts" of $@
are $1
, $2
... $#
. The last one, $#
, is the count of the number of arguments. $0
has a special role. It contains the name and path of the script.
You can also assign the whole thing (or even parts of it) to an array that you can use subscripting with.
some_array=("$@")
echo ${some_array[3]} # the fourth element (ZERO based)
echo ${some_array[3]:4:3} # 5th, 6th and 7th chars of the fourth element
echo ${some_array[@]:4:3} # 5th, 6th and 7th ELEMENTS
echo ${some_array[@]: -1} # the last element (notice the space)
精彩评论