Ask coding questions

← Back to all posts
Bash functions
19ecal (230)

I'm trying to make a function to compile and run a C/C++ file I give it, then delete the executable
In .replit I have run="bash main.sh"
In main.sh:

gcc -o main main.c;
./main;
rm main;
runc () {
	gcc -o $1 $1.c; 
	./$1; 
	rm $1;
};
runcpp () {
	gcc -o $1 $1.cpp -lstdc++;
	./$1;
	rm $1;
};

That should compile main.c, run then delete the executable, then define the functions for C and C++ but then when I go to the console and do runc main, it just says bash: runc: command not found
The function itself does work, as runc () { gcc -o $1 $1.c; ./$1; rm $1; }; runc main just straight in the console works
Am I doing something wrong, or is it just replit

Answered by programmeruser (571) [earned 5 cycles]
View Answer
Comments
hotnewtop
programmeruser (571)

The shell tab that you opened and the script are two different bash instances.
EDIT: see my comment below

19ecal (230)

@programmeruser So every time I will have to copy and paste the function definitions to be able to just do runc main and it to do it?

programmeruser (571)

@19ecal I got it wrong in my first post. Try this:
. main.sh
This will load the variables and functions from the file which allows you to use the function.

19ecal (230)

@programmeruser When I put that in .replit it says sh: 1: .: main.sh: not found, adding the full file path fixed that but it still does not work, unless you meant do it in the console/shell which does work

programmeruser (571)

@19ecal I meant to do it in the shell