开发者

Using a shell script -> getting an error

开发者 https://www.devze.com 2023-04-11 13:50 出处:网络
I was writing a shell script so that it I would not have to give clang the same parameters every single time when I try to compile a c file... (using Sublime and trying to build and run...

I was writing a shell script so that it I would not have to give clang the same parameters every single time when I try to compile a c file... (using Sublime and trying to build and run...

#!/bin/bash
cd "$(dirname "$1")"
clang "-Wall $(basename "$1") -o $(basename "$1"开发者_运维问答 ".${1##*.}")"

Am I making a really dumb mistake? or is it possible?

And if I want it to run right away should i remove the -o?

Kelan


everything within double quotes is one parameter, so...:

clang -Wall "$(basename "$1")" -o "$(basename "$1" ".${1##*.}")"


Will explain with one example. This is something acceptable:

a=getAnum(randomize(10*(34)))

And this is what you did:

a=getAnum(randomize)10*(34)()

Your quotes act as the brackets in the second code line. That's why we usually use single quotes when we want to nest something between double quotes in most programming languages, like this: "I ate 'pizza' and 'tuna'" To get the string: I ate 'pizza' and 'tuna'

However in shell double quotes and single quotes are very different. Double quotes let you have variables between them while single ones will take everything between and use it literally so that special symbols are interpreted just like normal text.

In your case I would just take off quotes completely when not nessecary so that this for example:

cd "$(dirname "$1")"

Becomes this:

cd $(dirname "$1")

Or this:

cd $(dirname $1)

However this:

cd '$(dirname $1)'

Or this:

cd $(dirname '$1')

would not work. It would take everything between the single quotes and interpret it as text. So in the first case it would try to enter a directory named $(dirname $1) and in the second name it would run dirname $1.


Try it just like this:

#!/bin/bash
if [ "$1" ] ; then
    cd "$(dirname "$1")"
    clang -Wall "$(basename "$1")" -o "$(basename "${1%%.c}")"
fi

When you plan to compile more files, start using Makefiles.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号