I want to get the error output from compiling a C++ file using shellscript. When I pass argument to shellscript , for ex: argument is the name of the .cpp file : data.cpp,
and that argument seems only be able to deal with "echo" but not with g++ as:

g++ $1.cpp 2> err.txt

doesn't work
So I decided to call only the shellscript(without argument) and in that :

g++ *.cpp 2> err.txt

then it works
Is there any way to deal with this kind of argument for other commands , not with "echo" command purely (to write stream)

Recommended Answers

All 2 Replies

The script you've written will work, you just need to pass the filename without the .cpp extension.

Where you've used '$1.cpp' in your script:
If you pass 'data.cpp' as a parameter when you run the script, '$1.cpp' will expand to 'data.cpp.cpp'. Which is why it's not working for you, the shell will be unable to find a file called data.cpp.cpp.

So to solve it you could do one of two things:

1. You could call your script and just pass the filename without the extension e.g.:

./buildit.sh ./data

BTW: For the sake of argument, we'll assume your script is called 'buildit.sh'.

Now $1.cpp will expand to data.cpp and g++ will attempt to build your file and the output will be saved to err.txt.


2. Remove the .cpp file extension from your script:

g++ $1 2> err.txt

Now you can call the script from the command line and get it to build data.cpp like this:

./buildit.sh ./data.cpp

And gcc will attempt to build the file and pipe any output into a file called 'err.txt'

Obviously, the above examples assume that the script and the .cpp file are in the same directory, if they were in different directories then you'd need to use the full paths to each.
So if you had the shellscript in a directory called 'scripts' in your home directory and the .cpp file was in a directory in home called 'cpp', then you'd drop to a command line and do something like this:

~/scripts/buildit.sh ~/cpp/data.cpp

NOTE: In case you didn't know the tilde '~' is an alias for the current users home directory (i.e. /home/username/ )

Anyway, hope this is of some use!
Cheers for now,

thank you. I follow and it works with command line input directly. But I forgot to inform that last time I used Java to call the command (also what I wanna ask last time):

String cmd = "./controller.sh data" ;
//workDir is the directory string
Process pr = Runtime.getRuntime().exec(cmd , null, workDir);

and Java did nothing. may be Java can't interprete that, can it ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.