0

At work, I run a command daily to return a specific token for access to our local repos. It's not a big deal, but I was trying to figure out a faster way of generating this token. Usually, I paste it into VSCode and run a Send Request via the REST Client Extension.

I'm trying to create a function in my .zsh profile that can then be run in my command line instead. Here's what I currently have:

generateToken() {
    response=curl -H "Content-Type: application/json" -H "service-token: xxxx" -X POST -d '{"user": "me.myself@xxxxxxx.com"}' <the-url.com>
    echo "$(response)"
}

Then I save, quit, and run eval ${generateToken}, but nothing happens. Any suggestions on the best way to get this going?

Cyrus
  • 84,225
  • 14
  • 89
  • 153
J. Jackson
  • 3,326
  • 8
  • 34
  • 74
  • Once you've fixed the assignment and output as per the duplicate, you can invoke your function with `generateToken` – that other guy Dec 15 '22 at 22:04
  • @thatotherguy i've wrapped the curl in parentheses, and fixed the echo statement, however it's just returning the cURL statement rather than the actual response – J. Jackson Dec 15 '22 at 22:07
  • I reopened the question. Please update with your code as it is now – that other guy Dec 15 '22 at 22:08
  • Ah I got it! One of the other popular answers (but below the accepted answer) mentioned the need to wrap in backticks rather than parentheses. This fixed the issue and it's not returning the token correctly. Thank you! – J. Jackson Dec 15 '22 at 22:09
  • I think you you cut some corners and used `(..)` instead of `$(..)`. Backticks are a deprecated form that does not use a `$`. Check out [shellcheck](https://www.shellcheck.net) which autodetects many such issues. – that other guy Dec 15 '22 at 22:11
  • You're right, I tried it with `$(..)` and that also works. – J. Jackson Dec 15 '22 at 22:12
  • @thatotherguy Shellcheck does not support Zsh – shadowtalker Dec 15 '22 at 22:33
  • @shadowtalker True, but the question was originally tagged `bash` – that other guy Dec 15 '22 at 22:36

2 Answers2

0

Thanks to @thatotherguy in the comments, I was able to create the following:

function generateToken() {
        echo "Generating token..."
        response=$(curl -H "Content-Type: application/json" -H "service-token: xxxxxxx" -X POST -d '{"user": "me.myself@mycompany.com"}' https://api.my.company/token)
        echo "${response}"
}
J. Jackson
  • 3,326
  • 8
  • 34
  • 74
0

If you're not doing anything to the output, you don't need to capture it and echo it. You can just run the command. It will write its output to the same place that echo would if you captured and re-echoed the output.

generateToken() {
  echo "Generating token..."
  curl -H "Content-Type: application/json" -H "service-token: xxxxxxx" \
    -X POST -d '{"user": "me.myself@mycompany.com"}' \
    https://api.my.company/token
}
tjm3772
  • 2,346
  • 2
  • 10