Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from 84adam/bash_c_example.sh
Created July 16, 2025 20:03
Show Gist options
  • Save RandyMcMillan/37360cecd8558bac19b6cce01a085f66 to your computer and use it in GitHub Desktop.
Save RandyMcMillan/37360cecd8558bac19b6cce01a085f66 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment