1

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:

#!/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.

2
  • 2
    /bin/sh is not bash, that's where it starts. Commented Dec 28, 2021 at 21:28
  • 1
    Your script has several problems; I'd recommend running it through shellcheck.net. Also, OPTIND is normally set by getopts, but you don't appear to have used it here. Commented Dec 28, 2021 at 23:11

1 Answer 1

3

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"
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.