0

I have to compile some mysql c api code and tired of writing all this in command line:

gcc main.c -o main `mysql_config --cflags --libs`

I wrote a shell script in bash and pass positional parameter in bash:

gcc $1 -o ${"$1":0:2} 'mysql_config --cflags --libs' but this doesn't work. I get error message: ./compile: line 2: ${"$1":0:-2}: bad substitution. Can someone please tell me what I am doing wrong?

The only way I got this to work is by assigning a new variable:

filename=$1;
gcc $filename -o ${filename:0:-2} `mysql_config --cflags --libs`

Is this the only way to do it or is there a way to fix what I am doing wrong in the first case?

5
  • Time to start learning about make... Or any other build-management tool... Commented Mar 5, 2014 at 19:27
  • @twalberg I thought make would only be appropriate for larger programs. This is just a small test program. thanks. Commented Mar 5, 2014 at 19:33
  • While it's true that it provides the most benefit for large complicated builds, it works perfectly fine for tiny single-source builds too... Commented Mar 5, 2014 at 19:35
  • @twalberg would you might showing me how it works in this case? Commented Mar 5, 2014 at 23:48
  • Posted an answer below to maintain formatting. Note the spacing at the beginning of the gcc line must be a single tab character. Commented Mar 6, 2014 at 0:48

2 Answers 2

3

You almost had it:

${1:0:2}

You don't need another reference to $1 inside the brackets since everything in it will be interpreted as the name of the variable, as in the case of ${filename:0:-2}.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Some explanation for the curious: 1 is the name of the parameter. However, the positional parameters aren't variables (i.e., parameters with valid identifiers as names), so you can't assign to it using variable assignment; 1=somestring doesn't work. To set the value of a positional parameter, you need to use the set command.
1

In response to the comments under the question, here's an example makefile for this situation:

MSQL_FLAGS := $(shell mysql_config --cflags)
MSQL_LIBS  := $(shell mysql_config --libs)

main : main.c
        gcc $(MSQL_FLAGS) -o $@ $< $(MSQL_LIBS)

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.