Kitz Forum

Computer Software => Linux => Topic started by: Weaver on October 16, 2018, 09:06:47 PM

Title: Learning bash
Post by: Weaver on October 16, 2018, 09:06:47 PM
I would appreciate a critique of my very first attempts to learn *nix shell scripting. A pair of tools to enhance ping and trace route so that they work seamlessly with IPv6 or IPv4. Plenty of known bugs, and no options at all supported yet. What I am really after is not assistance debugging them, as that is in hand any way, but suggestions for using Bash more fluently, suggestions for better techniques and opportunities missed. I started out with a tutorial which I later realised was very out of date as I began to suspect that it had not mentioned various new Bash-specific better ways of doing things. The two are pretty similar, apologies for the repetition.

Code: [Select]
#!/bin/bash

case  "$1" in
''|'-?'|'--?'|'-h'|'--h'|'--help')
echo "Usage: `basename $0` [options] ip_addr_or_dns_name" 1>&2
ping6 1>&2
exit 2
;;
esac

last_arg="${!#}" # Get last cmd line arg. Bash-only.
dest="$last_arg"
[ -z "$dest" ] && exit

if  echo "$*" | grep -P -q '(^|\s)\d+(\.\d+){3}($|\s)' # is ipv4 literal
then
ping_cmd='ping'
else
ping_cmd='ping6'
fi

if  echo "$*" | grep -P -q '(^|\s)--?c($|\s)' # is ipv4 literal
then
c_switch='-w 3'
else
c_switch='-c 1 -w 1'
fi

$ping_cmd $c_switch  $*
status=$?

# now output some info about actual ip addresses available (unfortunately not specifically the ones we probed)

# test if it was a domain name that we used

grep_pattern_is_dns_name='[a-zA-Z][-.a-zA-Z0-9]*'
if echo "$dest" | grep -q -P -i "$grep_pattern_is_dns_name"  # if is domain name
then
echo '---'
host "$dest" | grep -P ' address |NXDOMAIN'
fi
exit  $status

Code: [Select]
#!/bin/bash

case  "$1" in
''|'-?'|'--?'|'-h'|'--h'|'--help')
echo "Usage: `basename $0` [options] ip_addr_or_dns_name" 1>&2
traceroute6 1>&2
exit 2
;;
esac

last_arg="${!#}" # Get last cmd line arg. Bash-only.
dest="$last_arg"
[ -z "$dest" ] && exit

if  echo "$dest" | grep -P -q '^\d+(\.\d+)+$' # is ipv4 literal
then
traceroute_cmd='traceroute'
else
traceroute_cmd='traceroute6'
fi
$traceroute_cmd  $*
status=$?

# now output some info about actual ip addresses available (unfortunately not specifically the ones we probed)

# test if it was a domain name that we used

grep_pattern_is_dns_name='[a-zA-Z][-.a-zA-Z0-9]*'
if echo "$dest" | grep -q -P -i "$grep_pattern_is_dns_name"  # if is domain name
then
echo '---'
host "$dest" | grep -P ' address |NXDOMAIN'
fi
exit  $status