2013-03-01 77 views
3

我编写了这个.sh文件来编译任何c源文件,这样当我运行它时,它会请求文件名,然后gcc编译它,然后运行可执行文件.OUT。用于编译和生成C文件输出的Shell脚本文件

但是,当错误出现在.c文件中时,这不起作用。它也表明a.out不存在。我不希望此错误消息(a.out的是不存在的),但只想打印只为.c文件生成错误消息..

这里是脚本..

echo `clear` 
echo enter file name 
read FILE 
gcc $FILE 
./a.out 
echo -e '\n' 

回答

1

你可以链编译和执行命令:

echo `clear` 
echo enter file name 
read FILE 
gcc $FILE && ./a.out 
echo -e '\n' 

在这里,如果gcc失败,shell将删除./a.out命令。

+0

谢谢......那个工作很好... – Karthik 2013-03-01 13:37:23

2

如果启用中止,对错误的shell脚本,生活会轻松很多:

#!/bin/sh 
set -eu # makes your program exit on error or unbound variable 
# ...your code here... 
1

您也可以保护文件名用双引号:

#! /bin/bash 
clear 
echo -n "Enter file name: " 
read FILE 
gcc -Wall -W "$FILE" && ./a.out 
echo 
+0

谢谢哟你提醒我那些 - 墙壁 - 我...忘了使用他们一段时间... – Karthik 2013-03-01 13:38:08

2

利用内置规则替代您的脚本,您可能希望使用make作为手动脚本的替代方法。要编译file.c并运行生成的可执行文件,所有你需要做的是:

make file && ./file 

如果你不知道的话,我强烈建议你看一看的make实用,因为它会减轻你的工作很多。管理任何超过一个文件项目的东西,如果没有它,就会变得非常糟糕。

0

我还有希望这是你在找什么,只需要此命令:

./compile executableName myCProgram.c -lm

您可以将更多的C文件每个人的未来并在该行的末尾添加更多的库,并且executableName不需要.exe

#!/bin/bash 
args="[email protected]" 
quant=$# 

#Copies in case you need the -lm(math library) params 
biblio=${args#*-} 
#grabs all params except the first one which should be the name of the executable 
firstCommand=${*:2:${#args}} 
#Remove the "-lm -lc" from firstCommand 
firstCommand=${firstCommand%%-*} 

printf "\nEXECUTING: gcc -W -Wall -c $firstCommand\n" 

#Creates the object file ".o" 
gcc -W -Wall -c $firstCommand 

#Convert the files names from example.c to example.o 
args=${args//.c/.o} 
printf "\nEXECUTING: gcc -o $args\n\n" 

#Creates the executable 
gcc -o $args 

printf "\n**Now execute comand: ./$1 **\n\n"