Skip to content

Instantly share code, notes, and snippets.

@84adam
Created May 9, 2024 17:12
Show Gist options
  • Save 84adam/d78100ff5f3188673ec3396992aa3071 to your computer and use it in GitHub Desktop.
Save 84adam/d78100ff5f3188673ec3396992aa3071 to your computer and use it in GitHub Desktop.
Bash-C Hello World: Compile and run a C program from a single Bash script
#!/bin/bash
# bash_c_example.sh
# Directory to store the C source file and the executable
EXAMPLES_DIR="$HOME/bash_c_examples"
# Ensure the directory exists, create it if not
mkdir -p "$EXAMPLES_DIR"
# Check if hello_world.c and hello_world executable already exist
if [[ -f "$EXAMPLES_DIR/hello_world.c" && -x "$EXAMPLES_DIR/hello_world" ]]; then
# Run the existing executable
echo "(Running existing hello_world executable)"
"$EXAMPLES_DIR/hello_world"
else
# Define the C code with "Hello, World!" inside a docstring
CODE=$(cat <<EOF
#include <stdio.h>
int main() {
printf("\\nHello, World!\\n\\n");
return 0;
}
EOF
)
# Create a C source file with the defined code in the specified directory
echo "$CODE" > "$EXAMPLES_DIR/hello_world.c"
# Change directory to the examples directory
cd "$EXAMPLES_DIR" || exit
# Compile the C source file using GCC
gcc -o hello_world hello_world.c
# Run the compiled executable
echo "(Running newly compiled hello_world executable)"
./hello_world
fi
@84adam
Copy link
Author

84adam commented May 9, 2024

make executable:

$ chmod +x bash_c_example.sh

run it the first time:

$ ./bash_c_example.sh

example output:

(Running newly compiled hello_world executable)

Hello, World!

run it a second time:

$ ./bash_c_example.sh

(Running existing hello_world executable)

Hello, World!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment