Linux:Scripts: Difference between revisions
From Cheatsheet
Jump to navigationJump to search
(→if) |
|||
| Line 54: | Line 54: | ||
fi | fi | ||
</syntaxhighlight> | </syntaxhighlight> | ||
== Scripts == | == Scripts == | ||
Revision as of 12:39, 30 January 2024
Template
#!/usr/bin/env bash
set -o errexit # Exit on error, do not continue running the script
set -o nounset # Trying to access a variable that has not been set generates an error
set -o pipefail # When a pipe fails generate an error
if [[ "${1-}" =~ ^-*h(elp)?$ ]] || [[ "${1}" == "" ]] ; then
echo ""
echo 'Usage: myscript.sh value1
This is the description of my script.
'
exit
echo ""
fi
Common syntax
for
# Execute a command for all objects within this folder and all subdirectories for i in *; do du -h "$i" ; done # Execute a command x amount of times based on $i for((i=1;i<=5;++i)) do echo $i done
if
Examples
FILE=~/todo.txt if [ -f "$FILE" ]; then cat "~/todo.txt" else echo "You don't have the file, so you should make it." fi
USER=$(whoami) FILE=~/todo.txt if [ "$USER" != "root" -a -f "$FILE" ]; then echo "You're a normal user, you do have the file and this is its output:" cat "$FILE" elif [ "$USER" != "root" -a ! -f "$FILE" ]; then echo "You're a normal user, you don't have the file, so you should make it." fi
Scripts
SSH
centos-create-user.sh
#!/bin/bash
# Execute as root
# Usage: ./centos-create-user.sh USER
USER="$1"
echo "Creating user ${USER}"
useradd -m ${USER} -G wheel
echo "Creating authorized keys file and settings rights for ${USER} user"
mkdir -p /home/${USER}/.ssh
cat << 'EOF' >> /home/${USER}/.ssh/authorized_keys
# PUT ANY KEYS IN HERE
# KEY-1
# KEY-2
# KEY-3
EOF
chown -R ${USER}:${USER} /home/${USER}/.ssh
chmod 700 /home/${USER}/.ssh
chmod 600 /home/${USER}/.ssh/authorized_keys
# EOF
ubuntu-create-user.sh
#!/bin/bash
# Execute as root
# Usage: ./ubuntu-create-user.sh USER
USER="$1"
echo "Creating user ${USER}"
adduser ${USER} --disabled-password
echo "Adding ${USER} to the sudo group"
usermod -aG sudo ${USER}
echo "Creating authorized keys file and settings rights for ${USER} user"
mkdir -p /home/${USER}/.ssh
cat << 'EOF' >> /home/${USER}/.ssh/authorized_keys
# PUT ANY KEYS IN HERE
# KEY-1
# KEY-2
# KEY-3
EOF
chown -R ${USER}:${USER} /home/${USER}/.ssh
chmod 700 /home/${USER}/.ssh
chmod 600 /home/${USER}/.ssh/authorized_keys
# EOF
Automatic sendmail
#!/bin/bash
#requires: date,sendmail
function fappend {
echo "$2">>$1;
}
YYYYMMDD=`date +%Y%m%d`
# CHANGE THESE
TOEMAIL="ADMINISTRATOR@MYDOMAIN.COM";
FREMAIL="FROMNOREPLY@MYDOMAIN.com";
SUBJECT="E-mail Subject";
MSGBODY=$(Command);
# DON'T CHANGE ANYTHING BELOW
TMP=`mktemp`
rm -rf $TMP;
fappend $TMP "From: $FREMAIL";
fappend $TMP "To: $TOEMAIL";
fappend $TMP "Reply-To: $FREMAIL";
fappend $TMP "Subject: $SUBJECT";
fappend $TMP "";
fappend $TMP "$MSGBODY";
fappend $TMP "";
fappend $TMP "";
cat $TMP|/usr/sbin/sendmail -t;
rm $TMP;