Linux – How do I change the value of a function parameter in a linux script?

How do I change the value of a function parameter in a linux script?… here is a solution to the problem.

How do I change the value of a function parameter in a linux script?

I have a script called with different parameters. Based on the values of these parameters, I check and build the “parameter” SVN version of the project.

./deploy 3281 

This command will create a 3281 directory and check the 3281

SVN version of the project, and will build it in the 3281 directory.

I need to create a keyword “HEAD” so that the script will check the latest SVN revision number and create a folder for it (example: 3282), then check the head version of the project and build it there.

I found out how to use svn ( svn info -r ‘HEAD’ –username jse http://[email protected]/repos/Teleena/ | grep Revision | egrep -o “[0-9]+”) to get the latest revision number, I’m trying to simply implement an if is something like this:

 #check to see if latest/head revision is called
        if [ "$1" == "head" ]; then
                #get latest revision number
                HEADREV=$(svn info -r 'HEAD' --username jse http://[email protected]/repos/Teleena/ | grep Revision | egrep -o "[0-9]+")
                echo "=========================================="
                echo "= Revision number: $HEADREV will be used ="
                echo "=========================================="
                #change swap the second parameter
                $1=$HEADREV  #<-- IS THIS CORRECT?
        fi
... [rest of program here]

I want to replace the first argument with the latest revision number and leave the rest of the script unchanged. So the question is: how do I change the parameter values of a function from inside a function?

Solution

You can use set built-in to change positional parameters.

The following code snippet changes the first positional argument, which is $1, to something:

set -- "something" "${@:2}"

For example, quote the following:

echo "Original parameters: $@"
set -- "something" "${@:2}"
echo "Modified parameters: $@"

Suppose it’s placed in a script called script and invoked via bash script foo bar baz, it will output:

Original parameters: foo bar baz
Modified parameters: something bar baz

Quoted from help set:

set: set [-abefhkmnptuvxBCHP] [-o option-name] [--] [arg ...]

 Set or unset values of shell options and positional parameters.

Related Problems and Solutions