Home > OS >  Script that execute C by Bash
Script that execute C by Bash

Time:06-30

What should a script that compiles and executes a C program look like? By condition, the script must be run with the following flags: gcc -Wall -Werror -Wextra -o

In my understanding, when running the script, I have to enter the name of the program file

% gcc -Wall -Werror -Wextra "file_name".c -o "file_name"
% ./"file_name"

CodePudding user response:

The script can take the name of the program as an argument, which you access using $1. Then substitute that for the file name in the commands.

#!/bin/sh

prog="$1"

if gcc -Wall -Werror -Wextra "$prog".c -o "$prog"
then "./$prog"
else
    echo "$prog.c did not compile successfully"
fi

CodePudding user response:

#!/bin/sh

gcc -Wall -Werror -Wextra "$1".c -o "$1" && "./$1" || echo "Unable to compile and run $1"

Compile with gcc and run a program if it is successfully compiled, otherwise show the message to user.

Run the script like

script_name file_name
  • Related