Skip to content

Instantly share code, notes, and snippets.

@trwatson
Last active September 29, 2017 20:16
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 trwatson/8ff43670318c1a616ea4ffb2803517ff to your computer and use it in GitHub Desktop.
Save trwatson/8ff43670318c1a616ea4ffb2803517ff to your computer and use it in GitHub Desktop.
Some bash conventions as an example
#!/bin/bash
##################################################################################
## A NOTE ABOUT YOUR SCRIPT ##
##################################################################################
VARIABLE="MyString123"
FILE_NAME="${VARIABLE}.txt"
EMPTY_ARRAY=()
COMMAND_OUTPUT=$(echo $VARIABLE) #MyString123
BACK_TRIMMED_VARIABLE=${VARIABLE::(-1)}; #MyString12
FRONT_TRIMMED_VARIABLE=${VARIABLE:(1)}; #yString123
TO_UPPER=$(echo $VARIABLE | tr [a-z] [A-Z]) #MYSTRING123
TO_LOWER=$(echo $VARIABLE | tr [A-Z] [a-z]) #mystring123
#Multiple string array
LIST_ARRAY=(
'My'
'String'
'123'
'4'
)
#A simple function to print areguemnts. called with print_arguments someString someOtherString
function print_arguements()
{
local FIRST_ARG=$1
local SECOND_ARG=$2
printf "My first argument is $FIRST_ARG. My second arguemet is $SECOND_ARG"
}
print_arguments foo bar #"My first argument is foo. My second arguemet is bar"
#For loop for all items in an array
for item in ${LIST_ARRAY[@]}
do
printf "$item\n"
done
#Split values by comma
ITEMS="foo,bar"
IFS="," PARTS=( $ITEMS )
FOO="${PARTS[0]}" #foo
BAR="${PARTS[1]}" #bar
#Add something to your EMPTY_ARRAY
EMPTY_ARRAY=()
EMPTY_ARRAY=(${EMPTY_ARRAY[@]} stuff)
EMPTY_ARRAY=(${EMPTY_ARRAY[@]} things)
printf "Your Array isn't so empty. We put %s and %s in it." ${EMPTY_ARRAY[@]}
#Check Internal Field Separator
echo $IFS | cat -A
#Write out a multiline file with variables in it
cat >> ~/$FILE_NAME << EOL
line 1
line 2
/variable/in/a/path/${VARIABLE}.txt
$COMMAND_OUTPUT
EOL
#If a file exists - it should because we made it in the step above
if [ -f ~/$FILE_NAME ]
then
#cat file
cat ~/$FILE_NAME
else
#Say the file doesn't exist
printf "$FILE_NAME doesn't exist!\n"
fi
#A case statement
case $VARIABLE in
MyString123)
Message="Variable is MyString123"
;;
*23*)
Message="Variable contains 23"
;;
*)
Message="Variable wasn't MyString123 or *23*"
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment