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

Time:12-29

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.

CodePudding user response:

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"
...
  • Related