Is there a way to set the positional parameters of a bash script from within a function?
In the global scope one can use set -- <arguments>
to change the positional arguments, but it doesn't work inside a function because it changes the function's positional parameters.
A quick illustration:
# file name: script.sh
# called as: ./script.sh -opt1 -opt2 arg1 arg2
function change_args() {
set -- "a" "c" # this doesn't change the global args
}
echo "original args: $@" # original args: -opt1 -opt2 arg1 arg2
change_args
echo "changed args: $@" # changed args: -opt1 -opt2 arg1 arg2
# desired outcome: changed args: a c
The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
There are two types of variables in Bash scripting: global and local. Global variables can be used by all Bash scripts on your system, while local variables can only be used within the script (or shell) in which they're defined.
As stated before, the answer is no, but if someone need this there's the option of setting an external array (_ARRAY
), modifying it from within the function and then using set -- ${_ARRAY[@]}
after the fact. For example:
#!/bin/bash
_ARGS=()
shift_globally () {
shift
_ARGS=$@
}
echo "before: " "$@"
shift_globally "$@"
set -- "${_ARGS[@]}"
echo "after: " "$@"
If you test it:
./test.sh a b c d
> before: a b c d
> after: b c d
It's not technically what you're asking for but it's a workaround that might help someone who needs a similar behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With