Reputation: 2317
I inherited a shell script 'myScript.sh', that I want parametrize. Inside the script there is a function, like this:
function hmac_sha256 {
key="$1"
data="$2"
printf "${data}" | openssl dgst -sha256 -mac HMAC -macopt "${key}" | \
sed 's/^.* //'
}
Now, when I want to call the overall script in my terminal I do
/.myScript arg1 arg2 etc
These args, to my limited knowledge, are by default represented by respective '$1', '$2', etc. I use these args elsewhere in the script, NOT as arguments for this specific function.
However, these very $1 and $2 are already in use in the function above.
The question is I think: how do I distinguish between 'external' and 'internal' arguments?
Upvotes: 0
Views: 338
Reputation: 1036
Most portable way across different shells would be to assign script arguments to global variables.
ARG1="$1"
ARG2="$2"
echo "My arguments $ARG1 $ARG2"
There is also shortcut for this in most modern shells (at least bash, zsh, ksh) which have support for arrays. Be aware that strict POSIX shells don't have arrays, so this will not work in them. You can assign $@
to array and access this array instead like this:
ARGV=("$@")
# arguments in ARGV array will be shifted - $1 on index 0, $2 on index 1, etc..
echo "My arguments ${ARGV[0]} ${ARGV[1]}"
At last, if you are ok with an unportable bash script, you can use BASH_ARGV array.
echo "My arguments ${BASH_ARGV[1]} ${BASH_ARGV[0]}"
Upvotes: 1