Snippets

Jesse Almanrode Bash Snippets

Created by Jesse Almanrode last modified
1
2
3
4
5
6
#!/bin/bash
# Use echo to turn the string variable into a pseudo array
echo "${pseudoArray}” | while read line; do
    echo "${line};
    echo "----"; # To show I am processing each line in turn
done
#!/bin/bash
MY_UID=$(id | grep 'uid=0(root)'); # Running as root or using sudo
if [ -n ${MY_UID} ]; then
	echo “You must run this tool as your normal user and not using sudo”;
	exit 1;
else
	sudo -k; #Reset sudo timestamp. Doesn’t require a password
	sudo ls / > /dev/null; #have the user enter their sudo password
	if [ $? -gt 0 ]; then
		echo -e “You did not enter the correct sudo password…\nExiting!”;
		exit 1;
	fi
fi

echo “You now have been validated as a user with sudo privileges!” 
exit 0;
#!/bin/bash
someCommand 2> /dev/null; 
# Do the command but don’t show an error to the user if one occurs
if [ $? -ne 0 ]; then
	echo “An Error Occurred”;
	# Do something about it
fi
OR

someCommand; 
# Show the error to the user, if any, and then do something about it
if [ $? -ne 0 ]; then
	echo “An Error Occurred”;
	# Do something about it
fi
#!/bin/bash
function VERIFY_IPv4() {
ip=$1;
isIP=S(echo "$ip" | grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}');
if [ -z "$isIP" ]; then
        echo "Not in IP form: $ip";
        return 1;
fi
ipArray=$(echo $ip | tr '.' ' ');
firstOctet=$(echo $ip | cut -d '.' -f1);
lastOctet=$(echo $ip | cut -d '.' -f4);
newip="";
for octet in $ipArray; do
        octet=$(echo $(( ${octet#0} )));
        if [ $octet -gt 255 ]; then
                echo "Invalid IP: $ip";
                return 1;
        else
                newip="$newip$octet.";
        fi
done
ip=$(echo $newip | rev | cut -c 2- | rev); # Removes trailing period
if [ $firstOctet -eq 0 -o $lastOctet -eq 0 -o $firstOctet -eq 255 -o $lastOctet -eq 255 ]; then
        echo "Invalid IP: $ip";
        return 1;
fi
echo "$ip";
return 0;
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.