yzhao30
2/1/2018 - 3:26 AM

bash snippet

#!/bin/bash

# http://mywiki.wooledge.org/BashFAQ/001

# IFS='' (or IFS=) prevents leading/trailing whitespace from being trimmed.
#     If you don't set the IFS properly, you will lose any indentation.
# -r prevents backslash escapes from being interpreted.
# || [[ -n $line ]] prevents the last line from being ignored if it doesn't end with a \n (since read returns a non-zero exit code when it encounters EOF).

read1()
{
	while IFS='' read -r line || [[ -n $line ]]; do
		echo "$line"
	done < "$1"
}

read2()
{
	while read -r line || [[ -n $line ]]; do
		if [[ ! -z $line ]]; then
			echo "$line"
		fi
	done < "$1"
}

read2 $1
#!/bin/bash

start()
{
	echo "start"
}

stop()
{
	echo "stop"
}

# check arg number
# $1, $2, ...
if [[ $# -ne 1 ]]; then
	echo "illegal number of args"
	exit 1
else
	echo "number of args: $#"
fi

# check arg is empty
if [[ -z $1 ]]; then
	echo "arg is empty"
	exit 1
fi

# check arg
case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	*)
		echo "Usage: $0 {start|stop}" >&2
		exit 1
		;;
esac