Skip to content

Instantly share code, notes, and snippets.

@rytoj
Last active December 19, 2016 22:04
Show Gist options
  • Save rytoj/9e4e32d123404ea5b7680d11a9f5f43e to your computer and use it in GitHub Desktop.
Save rytoj/9e4e32d123404ea5b7680d11a9f5f43e to your computer and use it in GitHub Desktop.
bash if examples
#!/bin/bash
Reading
####################################
read -e -p "Enter value: " value # saves read input to var, $value
read -n 1 -p "Type a character > " #reads one character saves to default read var $REPLY
Cheking
####################################
#String cheking
#Checks if empty
[[ -n "$filesystem" ]] #return 1 if empty
#Check if no argument entered
if [ $# -eq 0 ]
then
echo "Usage: randomExample word"
exit 1
fi
#find only ip adresses
grep -Eoa '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /var/log/auth.log
ip a | grep inet | awk '{ print $2 }'
Letter comparison
####################################
read character
if [[ $character == 'Y' || $character == 'y' ]]
then
echo "YES"
else
echo "NO"
fi
------------------------------------
read x
if [ "$x" == "Y" ] || [ "$x" == "y" ]; then
echo "YES"
elif [ "$x" == "N" ] || [ "$x" == "n" ]; then
echo "NO"
fi
#function for input
function ask() {
echo "[y/n]"
read x
if [ "$x" == "Y" ] || [ "$x" == "y" ]; then
echo "Executing..."
elif [ "$x" == "N" ] || [ "$x" == "n" ]; then
echo "Skipping..."
(exit 1)
fi
}
#better version with case
function ask() {
echo "[y/n]"
read x
case "$x" in
y|Y)
echo "Komanda vykdoma..."
echo
;;
*)
echo "Komanda atsaukta."
exit 1
esac
}
ask && ls #exaple
------------------------------------
if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then echo "Not sh"; fi
loops
####################################
------------------------------------
for str in $(ls); do echo $str; done
------------------------------------
ls | while read; do echo $REPLY; done
------------------------------------
for NUMBER in 1 2 3 4 5; do echo $NUMBER; done
for i in {1..10}; do printf '%d\n' "$i"; done
for FILE in $(ls); do echo $FILE; done
i=1; while [ $i -lt 10 ]; do echo -n $i; let i=$i+1; done
i=1; until [ $i -gt 10 ]; do printf '%d\n' "$i"; i=$((i+1)); done
------------------------------------
arrays
####################################
programs=(httpd mysql-server php php-mysql wget unzip)
#array itteration example
for i in "${programs[@]}"
do
rpm -q $i > /dev/null 2>&1
if [ $? -eq 1 ]; then
echo "Error: $i not found. Install? [y/n]"
read x
if [ "$x" == "Y" ] || [ "$x" == "y" ]; then
echo "installing $1"
yum install $i -y
elif [ "$x" == "N" ] || [ "$x" == "n" ]; then
echo "Skipping $i install"
fi
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment