0

I want to pass the version tag argument like v1.3 to bash script file. I shown my file which contains tag argument. I want to pass v1.3 argument to ${tag} from terminal. This tag value often changed. Can any one tell me how to pass the argument for below bash script file.

#!/bin/bash
cd /path/to/file
git checkout -- .
git checkout tags/${tag}
4

You use what are known as "positional parameters", $1, $2 and so on.

eg

#!/bin/bash
cd /path/to/file
git checkout -- .
git checkout tags/"$1"

Now you can do myscript tag or myscript anothertag or myscript test and the value of $1 will be what you enter.

1

Your script could be made to work the way you inted by the addition of a single line:

#!/bin/bash
tag=$1
cd /path/to/file
git checkout -- .
git checkout tags/${tag}

This would take the first command line argument of the script an assign it to the variable tag.

To allow for spaces in the value of $tag, double quote the variable expansion:

#!/bin/bash
tag=$1
cd /path/to/file
git checkout -- .
git checkout tags/"$tag"

To only do the git operations if the cd succeeded, make each command depend on the successful completion of the previous command:

#!/bin/bash
tag=$1
cd /path/to/file &&
git checkout -- . &&
git checkout tags/"$tag"

alternatively, make the script automatically terminate when one of the commands fail,

#!/bin/bash -e
tag=$1
cd /path/to/file
git checkout -- .
git checkout tags/"$tag"

Since this script is not using anything that is bash-specific, it will easily run under /bin/sh instead:

#!/bin/sh -e

tag=$1

cd /path/to/file
git checkout -- .
git checkout tags/"$tag"
-1

you can pass parameters to your script with positional parameters

#!/bin/bash
cd /path/to/file
TAG=$1  # read the first paramater passed to your script like ./myscript v1.2
if [ "$TAG" != "" ]; then
    git checkout -- .
    git checkout tags/"$TAG"
else
    echo "Please enter a Tag "
    exit 1 ;
fi

you can also use interactive mode to allow user to enter value to your script like .

   #!/bin/bash
    read -p "Please enter tag: " TAG
     cd /path/to/file
    if [ -n "$TAG" ]; then
        git checkout -- .
        git checkout tags/"$TAG"
    else
        echo "Please run again and enter a Tag "
        exit 1 ;
    fi
  • // is not a comment in bash scripts, and a test for a non-empty value could be done with [ -n "$TAG" ]. – Kusalananda Dec 5 '18 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.