Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot pass argument to bash script through golang exec.Commad()

I am trying to pass an argument to a bash script, via a golang progam, but I’m having issues with the bash script properly recieving the argument.

Golang function:

func testLink(link string) {
    stdout, err := exec.Command("/bin/sh", "-c", "./test.sh", link).Output()

    if err != nil {
        log.Fatalf("Error running test script: %s", err)
    }
    fmt.Println(string(stdout))
}

Which calls the following bash script:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#!/bin/sh

LINK=${@:$OPTIND:1}

if [[ -z "$LINK" ]]; then
    echo "The link is required"
    exit 1
fi

PARSED_LINK=$(echo $LINK | awk '{split($0,a,"/"); print a[5]}')

#do some other actions

I can run the script no problem, and I get the expected output. However, upon running the golang code:

$ go run main.go test https://github.com/test/test
2021/12/28 20:48:02 Error running test script: exit status 1
exit status 1

How do I pass the argument in: go run main.go function argument to the bash script?

Additionaly, I know it fails with the receiving argument, because if I change the exit code in the if segment, the output from the go executable changes.

>Solution :

For the arguments to be passed, you need to remove the -c otherwise they are treated as argument to the sh executable rather than your script.

cmd := exec.Command("/bin/sh", "./test.sh", link)

I guess additionally your problem is how you wrote your shell script. That variable assignment looks odd. shellcheck reports this at line 2 below.

Assigning an array to a string! Assign as array, or use * instead of @ to concatenate. shellcheck(SC2124)
In POSIX sh, string indexing is undefined. shellcheck(SC3057)

When I try to execute a script with the argument set like you did via shell, I get an error.

#!/bin/sh
LINK=${@:$OPTIND:1}
echo "$LINK"
$ ./test.sh foo
./test.sh: 2: Bad substitution

I suggest assigning the variable like this instead.

#!/bin/sh
LINK="$1"
...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading