Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change global positional parameters inside a Bash function

Tags:

bash

shell

sh

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
like image 301
Calin Avatar asked Mar 25 '15 14:03

Calin


People also ask

How do I change global variables in bash?

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.

What does [- Z $1 mean in bash?

$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.

Can bash function access global variable?

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.


1 Answers

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.

like image 129
Ciro Costa Avatar answered Oct 11 '22 20:10

Ciro Costa