0

I have a curl script where one of the variables in the URL is actually the name of .sh file.

So, if file name is test.sh then in the script I would want curl www.example.com/test where it would grab the 'test' from the file name.

I'm able to obtain the actual name by using a combination of answers I see here: How do I know the script file name in a Bash script?.

However, being new to this I'm not exactly sure how it should be formatted and specifically how to output the variable.

Would appreciate any help

Community
  • 1
  • 1
user2029890
  • 2,493
  • 6
  • 34
  • 65

2 Answers2

0

For your example:

# The name of the executable (with the .sh removed if it's there)
SCRIPT_NAME=`basename $0 .sh`

# Put the entire argument in quotes in case SCRIPT_NAME has a space in it.
# The curly braces aren't strictly necessary, but ensure that if you need to
# put anything immediately after, like "_test", it's not treated as part of the
# variable name.
curl "www.example.com/${SCRIPT_NAME}"

See example 5.1 here for an example of how to use variables, or section 3.2.2 here for a more in-depth description.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • That looks like it should work, however the variable displays correctly if I echo it, but in the curl script it just displays the actual variable name. I should point out that the variable is in middle of the url as in "www.example.com/${SCRIPT_NAME}/page1" – user2029890 Aug 22 '13 at 01:06
  • What do you mean "in the curl script"? Please paste as much of the script as possible into the question, as it looks like your actual error is in the way you're invoking your script or with other code inside it. – Jeff Bowman Aug 22 '13 at 01:12
  • You are probably correct, as even this simple script is failing:SCRIPT_NAME=/2013/08/21/politics/nsa-fisa-court/index.html?hpt=hp_t1 echo $SCRIPT_NAME curl 'www.cnn.com/${SCRIPT_NAME}' – user2029890 Aug 22 '13 at 01:19
  • Found your error. Unlike languages like Python, bash requires **double quotes** if you want your variables substituted within them. If you use **single quotes**, your variables will be treated literally and curl will request unsubstituted paths. – Jeff Bowman Aug 22 '13 at 01:26
  • Thanks for your help, but even double quotes doesn't work. It just says curl: (52) Empty reply from server. Where exactly should these double quotes be? – user2029890 Aug 22 '13 at 01:32
  • The double quotes are important around the URL with the variable in it. Compare `echo '$HOME'` with `echo "$HOME"`. Generally, URLs don't have spaces in them, so you might be fine just omitting the quotes around the URL entirely. – Jeff Bowman Aug 22 '13 at 21:16
0

If I understand you correctly

for test.sh

#!/bin/bash
name=${s/"$(basename $0)"/".sh"}  #ie name of scipt, no path, .sh removed
echo "DEBUG: $name"
curl "http://www.example.com/$name"
tolanj
  • 3,651
  • 16
  • 30