Skip to content

Instantly share code, notes, and snippets.

@ajithbh
Last active August 29, 2015 13:57
Show Gist options
  • Save ajithbh/9362085 to your computer and use it in GitHub Desktop.
Save ajithbh/9362085 to your computer and use it in GitHub Desktop.
Bash - Utility functions
while getopts ae:f:h:qs: option
do
case "${option} in
a) AFLAG="TRUE" ;;
e) EOPTION=${OPTARG} ;;
f) FILE=${OPTARG} ;;
q) QUIET="TRUE" ;;
s) SERVER=${OPTARG} ;;
h|\?) usage && exit 1 ;;
esac
done
factorial()
{
count=$1
fact=1
while [ ${count} -gt 0 ]; do
fact=$(( ${fact} * ${count} ))
count=$(( ${count} - 1 ))
done
echo ${fact}
}
#!/bin/bash
FILE=$1
# Read $FILE using fd
exec 3 < &0
exec 0 < ${FILE}
while read line; do
# Use ${line} to process each line
echo ${line}
done
exec 0 < &3
#!/bin/bash -
set -o nounset
pad_to_size()
{
local file=${1}
local size=${2}
local cur_size=${3}
local pad_length=$( echo ${size} - ${cur_size} | bc )
dd if=/dev/zero count=${pad_length} bs=1 >> ${file}
}
# pad_to_size test.txt 512 0
# pad_to_size test.txt 1024 $(stat -c%s test.txt)
_count=0
add_to_file_and_count()
{
local file=${1}
local str=${2}
echo -en "${str}\0" >> ${file}
_count=$( echo ${_count} + ${#str} + 1 | bc ) # + 1 since i'm adding '\0'
}
# add_to_file_and_count test.txt "Hello"
# add_to_file_and_count test.txt "World"
declare -A SECT1
declare -A SECT2
parse_config_file()
{
local config_file="${1}"
eval `awk -F ' *= *' '{ \
if ($1 ~ /^\[/) \
{ section=$1; gsub(/\[|\]/, "", section); } \
else if ($1 !~ /^$/) \
print section"["$1"]" "=" "\"" $2 "\"" }' ${config_file}`
}
# config.txt
#
# [SECT1]
# val1 = "1"
# val2 = 100
#
# [SECT2]
# id = 0
# name = TEST
#
parse_config_file config.txt
echo ${SECT1[val1]}
echo ${SECT1[val2]}
echo ${SECT2[id]}
echo ${SECT2[name]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment