Skip to content

Instantly share code, notes, and snippets.

@grantjbutler
Last active October 10, 2015 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantjbutler/3725897 to your computer and use it in GitHub Desktop.
Save grantjbutler/3725897 to your computer and use it in GitHub Desktop.
Simple bash script for running little code snippets
#!/bin/bash
function template_from_language() {
__PHP_TEMPLATE="<?php\n\n?>\n"
__OBJC_TEMPLATE="#import <Foundation/Foundation.h>\n\nint main(int argc, char *argv[]) {\n\t@autoreleasepool {\n\t\t\n\t}\n\t\n\treturn 0;\n}\n"
__JAVA_TEMPLATE="public class program {\n\tpublic static void main(String args[]) {\n\t\t\n\t}\n}\n"
__BASH_TEMPLATE="#!/bin/bash\n\n"
__JS_TEMPLATE="var path = require('path');\n\n"
if [ -z "$1" ]
then
echo ""
fi
case "$1" in
php)
echo $__PHP_TEMPLATE
;;
objc)
echo $__OBJC_TEMPLATE
;;
java)
echo $__JAVA_TEMPLATE
;;
bash)
echo $__BASH_TEMPLATE
;;
js)
echo $__JS_TEMPLATE
;;
*)
echo ""
;;
esac
}
function extension_from_language() {
if [ -z "$1" ]
then
echo ""
fi
case "$1" in
php)
echo "php"
;;
objc)
echo "m"
;;
java)
echo "java"
;;
bash)
echo "sh"
;;
js)
echo "js"
;;
*)
echo ""
;;
esac
}
function run_program_for_language() {
if [ -z "$1" ]
then
return 0
fi
if [ -z "$2" ]
then
return 0
fi
file="$1"
language="$2"
case "$language" in
php)
php -f $file
;;
objc)
clang -fobjc-arc -framework Foundation $file -o /tmp/program
/tmp/program
;;
java)
javac $file
java -classpath /tmp program
;;
bash)
chmod +x $file
$file
;;
js)
node $file
;;
*)
return 0
;;
esac
}
function usage() {
program=`basename $0`
echo "USAGE: $program [options] [language]"
echo ""
echo "OPTIONS:"
echo " -e Edit the existing code file."
echo ""
echo "SUPPORTED LANGUAGES:"
echo " Bash (bash)"
echo " Java (java)"
echo " JavaScript (js)"
echo " Objective-C (objc)"
echo " PHP (php)"
exit 0
}
language="objc"
if [ -n "$1" ]
then
if [ "$1" == "-h" ]
then
usage
elif [ "$1" != "-e" ]
then
language="$1"
elif [ -n "$2" ]
then
language="$2"
fi
fi
extension=$(extension_from_language $language)
if [ -z "$extension" ]
then
echo "Invalid language specified."
exit 1
fi
file="/tmp/program.$extension"
template=$(template_from_language $language)
if [ -z "$1" ]
then
echo -e $template > $file
elif [ "$1" != "-e" ]
then
echo -e $template > $file
fi
file_editor="$EDITOR"
if [ -z "$file_editor" ]
then
file_editor=`which nano`
fi
$file_editor $file
run_program_for_language $file $language
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment