sh 使用Borg的简短备份脚本

使用Borg的简短备份脚本

mkBackup.sh
#!/bin/bash
# Inspired by https://borgbackup.readthedocs.org/en/stable/quickstart.html
#             https://gist.github.com/ericmieth/c045edebb0709dfd88e1
# Created by mushu 2016-02-04
# Mounting the volume:
cryptsetup --key-file <keyfile> luksOpen UUID=<deviceUUID> cryptBackup
mount /dev/mapper/cryptBackup /mnt
# Performing the backup:
name=$(date -I)
sources='/etc /home /root'
target='/mnt/backups'
# Create a new backup:
borg create --exclude-caches $target::$name $sources
# Remove old backups:
borg prune -v $target --keep-daily=7 --keep-weekly=4 --keep-monthly=6
# Display current backups:
borg list $target
# Umounting the volume:
sync && umount /mnt
cryptsetup luksClose /dev/mapper/cryptBackup
checkBackup.sh
#!/bin/bash
# Inspired by https://borgbackup.readthedocs.org/en/stable/quickstart.html
#             https://gist.github.com/ericmieth/c045edebb0709dfd88e1
# Created by mushu 2016-02-22
# Mounting the volume:
cryptsetup --key-file <keyFile> luksOpen UUID=<deviceUUID> cryptBackup
mount /dev/mapper/cryptBackup /mnt
# Verifying current backups:
borg check /mnt/backups
# Umounting the volume:
sync && umount /mnt
cryptsetup luksClose /dev/mapper/cryptBackup
# Scrub local btrfs:
btrfs scrub start / -B
# Going to sleep:
systemctl suspend

sh 模板SysVinit脚本<br/> $ service mongodb_exporter start | stop <br/> $ /etc/init.d/mongodb_exporter start | stop <br/> $ update-rc.d mongodb_exporter def

模板SysVinit脚本<br/> $ service mongodb_exporter start | stop <br/> $ /etc/init.d/mongodb_exporter start | stop <br/> $ update-rc.d mongodb_exporter defaults

etc-init_d-mongodb_exporter.sh
#!/bin/bash

export USER='ubuntu'

export DAEMON_PATH=/usr/bin
export DAEMON=node_exporter
export DAEMONOPTS=""

export NAME=node_exporter
export PIDFILE=/var/run/$NAME.pid
export LOG_NAME=prometheus
export LOG_PATH=/var/log/$LOG_NAME

case "$1" in
start)
  if [ ! -d t ]; then mkdir $LOG_PATH && chown $USER:$USER $LOG_PATH; fi
	printf "%-50s" "Starting $NAME..."
	PID=`su $USER -c '$DAEMON_PATH/$DAEMON $DAEMONOPTS >> $LOG_PATH/$NAME.log 2>&1 & echo $!'`
        if [ -z $PID ]; then
            printf "%s\n" "Fail"
        else
            echo $PID > $PIDFILE
            printf "%s\n" "Ok"
        fi
;;
status)
        printf "%-50s" "Checking $NAME..."
        if [ -f $PIDFILE ]; then
            PID=`cat $PIDFILE`
            if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then
                printf "%s\n" "Process dead but pidfile exists"
            else
                echo "Running"
            fi
        else
            printf "%s\n" "Service not running"
        fi
;;
stop)
        printf "%-50s" "Stopping $NAME"
        if [ -f $PIDFILE ]; then
            PID=`cat $PIDFILE`
            su $USER -c 'echo "Stopping service..." >> $LOG_PATH/$NAME.log'
            kill -HUP $PID
            printf "%s\n" "Ok"
            rm -f $PIDFILE
        else
            printf "%s\n" "pidfile not found"
        fi
;;

restart)
  	$0 stop
  	$0 start
;;

*)
        echo "Usage: $0 {status|start|stop|restart}"
        exit 1
esac

sh 源自https://gist.github.com/ninjapanzer/aa81db16bae54431c41010e622d577b6

源自https://gist.github.com/ninjapanzer/aa81db16bae54431c41010e622d577b6

phalcon.sh
#!/bin/bash

ARRAY=(
    "phalcon:cphalcon"
    "phalcon:zephir"
    "phalcon:phalcon-devtools"
    "phalcon:incubator"
    "phalcon:docs-app"
)

touch combined.txt

for item in "${ARRAY[@]}" ; do
  ORG=${item%%:*}
  REPO=${item#*:}
  URL="https://github.com/$ORG/$REPO"
  git clone $URL
  cd $REPO && git fetch --all && git rebase && cd ..
  gource --output-custom-log ./output.txt ./$REPO
  sed -i -r "s#\(.*\)\|#\1|/$ORG/$REPO#" ./output.txt
  cat combined.txt output.txt > temp.txt && cat temp.txt > combined.txt
  rm -f temp.txt output.txt
done

cat combined.txt | sort -n > output.txt
rm -f combined.txt

gource -1920x1080 --stop-at-end --multi-sampling --highlight-users --highlight-dirs --auto-skip-seconds 1 --file-filter \.png --dir-colour 8b91a2 --highlight-colour ffffff --key --bloom-multiplier 0.2 --bloom-intensity 0.5 --hide mouse,filenames --seconds-per-day .01 --dir-name-depth 1 -r 25 -o - output.txt | avconv -y -r 25 -f image2pipe -vcodec ppm -i - -b 65536K phalcon-output-with-dirs.mp4

sh [Pseduo manual-HA script]用作将资源池从一台机器移动到另一台机器的临时解决方法的工具#ha #racktop #brickstor

[Pseduo manual-HA script]用作将资源池从一台机器移动到另一台机器的临时解决方法#ha #racktop #brickstor #bash #shell #failover #cluster #clustering

emergency-takeover.sh
#!/bin/sh
#
# Copyright 2017 RackTop Systems Inc. and/or its affiliates.
# http://www.racktopsystems.com
#
# The contents of this file are subject to the terms of the RackTop Commercial
# License ("RTCL"). You may not use, redistribute, or modify this file in source
# or binary forms except in compliance with the RTCL. You can obtain a copy at
# http://racktopsystems.com/legal/rtcl.txt.
#

DEBUG=0 # Enable debugging by setting > 0

# Assumptions:
# The other node is dead or otherwise disabled
# There are no active IPs or pools on the other node
# Manual cleanup of the other node may be necessary
# The pool being imported here is *NOT* already imported on the other node
# The pool may not have been correctly exported, requiring `-f` flag
# Aggregated interface aggr0 exists and is what vnics are created over


# Cleanup on remote end, if necessary:
# export pool if not exported with `zpool export <poolname>`
# Identify interfaces over which IP(s) is/are assigned with
# `ipadm show-addr`, where the last part will be /v4, and should be ignored
# and name will always begin with `havnic`
# destroy each IP interface with `ipadm delete-if <havnicX>`, where X is
# a number of the IP interface
# Destroy actual vic instance with `dladm delete-vnic <havnicX>`
# As soon as IP interfaces and vnics are gone, you are ready to run this script

[ ${DEBUG} -gt 0 ] && set -o xtrace

DLCMD=/usr/sbin/dladm
IPCMD=/usr/sbin/ipadm
PUBLIC_LINK=aggr0
ENOPUBLINK="Aggregate link ${PUBLIC_LINK} does not exist; cannot continue."
ENOARGS="Not enough arguments; expecting 3: <poolname> <mac addr> <CIDR>."
HAVNIC_NAME=
HAVNIC_MAC=
POOL_NAME=
SVC_IPADDR=
CMDLINE_ARGS=($@)


function print_err {
  printf "[ERROR]: %s\n" "$@" >&2
}

function split_input_into_fields {
  [ ${DEBUG} -gt 0 ] && set -o xtrace
  input=
  # We are assuming here that input arguments are in the following order:
  # 1) pool name
  # 2) mac address
  # 3) Service IP address
  if [[ ${#CMDLINE_ARGS} -lt 3 ]]; then
    print_err "${ENOARGS}"
    return 1
  fi
  
  # Set global variables to values extracted from command line arguments
  # passed to the script and then ask user to confirm that input is as
  # they intended it.
  POOL_NAME=${CMDLINE_ARGS[0]}
  HAVNIC_MAC=${CMDLINE_ARGS[1]}
  SVC_IPADDR=${CMDLINE_ARGS[2]}

  while true; do
    clear
    echo "*********************************************************************"
    echo "*** Please confirm the following is correct by typing 'Y' or 'N'. ***"
    echo "*** Type 'q' to quit. ***********************************************"
    echo "*********************************************************************"
    echo
    printf \
      "Pool: ${POOL_NAME} || MAC ADDR: ${HAVNIC_MAC} || IP ADDR: ${SVC_IPADDR}\n"
    
    # Consume input and keep repeating question until a 
    # suitable answer is provided.
    echo
    printf "Does this look right? "
    read -r input
    
    case ${input} in
    "y"|"Y") return 0
      ;;
    "n"|"N")
      printf "Please re-issue command with corrected arguments.\n"
      return 1
      ;;
    "q"|"Q")
      printf "You chose to quit!\n" ; exit 0
      ;;
    *) 
      continue
      ;;
    esac
  done
}

function create_vnic_over_aggr0 {
  [ ${DEBUG} -gt 0 ] && set -o xtrace
  typeset -A vnics
  vnic_index=0
  vnic_macaddr=$1
  if ! ${DLCMD} show-aggr ${PUBLIC_LINK} >/dev/null 2>&1 ; then 
    print_err "${ENOPUBLINK}"
    return 1
  fi

  # Obtain list of all vnics already configured on the system, then
  # `for loop over` the list and add each to an associative array setting
  # value of the map to 1. The goal is to then check this array against
  # havnic${vnic_index}, and as long as match is found, increment `vnic_index`
  # by 1. Eventually we will reach a point where no match is found and that
  # will be the name of the vnic with which we proceed.
  known_vnics=(`${DLCMD} show-vnic -p -olink | /usr/bin/awk '/havnic/'`)
  for vn in ${known_vnics[@]}; do
    vnics[$vn]=1
  done

  # Loop over already existing vnics and use the next available one.
  # This could be more efficient, but hash table-like lookup is fine here.
  while [ vnics[havnic${vnic_index}] -eq 1 ] ; do
    ((vnic_index++))
  done

  ${DLCMD} create-vnic \
    -t \
    -l ${PUBLIC_LINK} \
    -m ${vnic_macaddr} \
    havnic${vnic_index}
  HAVNIC_NAME=havnic${vnic_index}
}

#
# setup_ipaddress: Generic function responsible for setting-up
# IP Interface and address.
#
function setup_ipaddress {
  [ ${DEBUG} -gt 0 ] && set -o xtrace
  link_name=$1
  # skip_createif=0
  #
  # If we enhance this function to deal with existing vnics, we may need this.
  #
  # if ${IPCMD} show-if ${link_name} >/dev/null 2>&1 ; then
  #   skip_createif=1
  # fi
  # 
  # if ${IPCMD} show-addr "${link_name}/v4" >/dev/null 2>&1 ; then
  #   print_err \
  #     "IP Interface ${link_name}/v4 already exists. Skipping Create."
  # fi
  ${IPCMD} create-if -t ${link_name} || {
    print_err "Failed to create interface." ; return 1
  }
  if ! ${IPCMD} create-addr \
    -t \
    -T static \
    -a local=${SVC_IPADDR} \
    "${link_name}/v4"; then return 1
  fi
}

function rollback_ip_interface {
  [ ${DEBUG} -gt 0 ] && set -o xtrace
  if ! ${IPCMD} delete-if ${HAVNIC_NAME} >/dev/null 2>&1; then
    print_err "Failed to delete IP interface. VNIC will not be dropped."
    return 1
  fi
}

function rollback_vnic {
  [ ${DEBUG} -gt 0 ] && set -o xtrace
  if ! ${DLCMD} delete-vnic ${HAVNIC_NAME} >/dev/null 2>&1; then
    print_err "Failed to delete VNIC. VNIC will not be dropped."
    return 1
  fi
}

function import_pool {
  while true; do
    clear
    echo "*********************************************************************"
    echo "*** Please confirm pool is safe to import by typing 'Y' or 'N'. *****"
    echo "*** Type 'q' to quit. ***********************************************"
    echo "*********************************************************************"
    echo
    echo
    printf "Ready to *FORCE* import pool ${POOL_NAME}? "
    read -r input
    
    case ${input} in
    "y"|"Y")
      if ! /usr/sbin/zpool import -ff ${POOL_NAME} ; then
        print_err \
          "Failed to import pool ${POOL_NAME}. Please contact RackTop Support!"
        return 1
      else
        return 0
      fi
      ;;
    "n"|"N")
      printf "Breaking out.\n"
      return 1
      ;;
    "q"|"Q")
      printf "You chose to quit!\n" ; exit 0
      ;;
    *) 
      continue
      ;;
    esac
  done
}

# Main Body
split_input_into_fields || exit 1
create_vnic_over_aggr0 ${HAVNIC_MAC} || exit 1
setup_ipaddress ${HAVNIC_NAME} || exit 1

if ! import_pool ; then 
  rollback_ip_interface && rollback_vnic
else
  printf "\n\nImported pool ${POOL_NAME} and configured network.\n"
fi
exit $?

sh 安装在服务器上

安装在服务器上

post-install.sh
# To create 4GB swap:
# Source: https://help.ubuntu.com/community/SwapFaq#How_do_I_add_a_swap_file.3F

sudo fallocate -l 4g /mnt/4GiB.swap
sudo chmod 600 /mnt/4GiB.swap
sudo mkswap /mnt/4GiB.swap
sudo swapon /mnt/4GiB.swap

free -m

# To make swap permanent across reboots:
echo '/mnt/4GiB.swap swap swap defaults 0 0' | sudo tee -a /etc/fstab

sudo apt-get update
sudo apt-get install python build-essential
sudo apt-get install wget ca-certificates curl

sh 新服务器的安装脚本

新服务器的安装脚本

first_install_as_root.sh
# add a new user
adduser deploy

# add new user to sudo group
usermod -aG sudo deploy

sh 适用于UNIX系统的Bash CheatSheet

适用于UNIX系统的Bash CheatSheet

bash-cheatsheet.sh
#!/bin/bash
#####################################################
# Name: Bash CheatSheet for Mac OSX
# 
# A little overlook of the Bash basics
#
# Usage:
#
# Author: J. Le Coupanec
# Date: 2014/11/04
#####################################################


# 0. Shortcuts.


CTRL+A  # move to beginning of line
CTRL+B  # moves backward one character
CTRL+C  # halts the current command
CTRL+D  # deletes one character backward or logs out of current session, similar to exit
CTRL+E  # moves to end of line
CTRL+F  # moves forward one character
CTRL+G  # aborts the current editing command and ring the terminal bell
CTRL+J  # same as RETURN
CTRL+K  # deletes (kill) forward to end of line
CTRL+L  # clears screen and redisplay the line
CTRL+M  # same as RETURN
CTRL+N  # next line in command history
CTRL+O  # same as RETURN, then displays next line in history file
CTRL+P  # previous line in command history
CTRL+R  # searches backward
CTRL+S  # searches forward
CTRL+T  # transposes two characters
CTRL+U  # kills backward from point to the beginning of line
CTRL+V  # makes the next character typed verbatim
CTRL+W  # kills the word behind the cursor
CTRL+X  # lists the possible filename completefions of the current word
CTRL+Y  # retrieves (yank) last item killed
CTRL+Z  # stops the current command, resume with fg in the foreground or bg in the background

DELETE  # deletes one character backward
!!      # repeats the last command
exit    # logs out of current session


# 1. Bash Basics.


export              # displays all environment variables

echo $SHELL         # displays the shell you're using
echo $BASH_VERSION  # displays bash version

bash                # if you want to use bash (type exit to go back to your normal shell)
whereis bash        # finds out where bash is on your system

clear               # clears content on window (hide displayed lines)


# 1.1. File Commands.


ls                            # lists your files
ls -l                         # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified
ls -a                         # lists all files, including hidden files
ln -s <filename> <link>       # creates symbolic link to file
touch <filename>              # creates or updates your file
cat > <filename>              # places standard input into file
more <filename>               # shows the first part of a file (move with space and type q to quit)
head <filename>               # outputs the first 10 lines of file
tail <filename>               # outputs the last 10 lines of file (useful with -f option)
emacs <filename>              # lets you create and edit a file
mv <filename1> <filename2>    # moves a file
cp <filename1> <filename2>    # copies a file
rm <filename>                 # removes a file
diff <filename1> <filename2>  # compares files, and shows where they differ
wc <filename>                 # tells you how many lines, words and characters there are in a file
chmod -options <filename>     # lets you change the read, write, and execute permissions on your files
gzip <filename>               # compresses files
gunzip <filename>             # uncompresses files compressed by gzip
gzcat <filename>              # lets you look at gzipped file without actually having to gunzip it
lpr <filename>                # print the file
lpq                           # check out the printer queue
lprm <jobnumber>              # remove something from the printer queue
genscript                     # converts plain text files into postscript for printing and gives you some options for formatting
dvips <filename>              # print .dvi files (i.e. files produced by LaTeX)
grep <pattern> <filenames>    # looks for the string in the files
grep -r <pattern> <dir>       # search recursively for pattern in directory


# 1.2. Directory Commands.


mkdir <dirname>  # makes a new directory
cd               # changes to home
cd <dirname>     # changes directory
pwd              # tells you where you currently are


# 1.3. SSH, System Info & Network Commands.


ssh user@host            # connects to host as user
ssh -p <port> user@host  # connects to host on specified port as user
ssh-copy-id user@host    # adds your ssh key to host for user to enable a keyed or passwordless login

whoami                   # returns your username
passwd                   # lets you change your password
quota -v                 # shows what your disk quota is
date                     # shows the current date and time
cal                      # shows the month's calendar
uptime                   # shows current uptime
w                        # displays whois online
finger <user>            # displays information about user
uname -a                 # shows kernel information
man <command>            # shows the manual for specified command
df                       # shows disk usage
du <filename>            # shows the disk usage of the files and directories in filename (du -s give only a total)
last <yourUsername>      # lists your last logins
ps -u yourusername       # lists your processes
kill <PID>               # kills (ends) the processes with the ID you gave
killall <processname>    # kill all processes with the name
top                      # displays your currently active processes
bg                       # lists stopped or background jobs ; resume a stopped job in the background
fg                       # brings the most recent job in the foreground
fg <job>                 # brings job to the foreground

ping <host>              # pings host and outputs results
whois <domain>           # gets whois information for domain
dig <domain>             # gets DNS information for domain
dig -x <host>            # reverses lookup host
wget <file>              # downloads file


# 2. Basic Shell Programming.


# 2.1. Variables.


varname=value                # defines a variable
varname=value command        # defines a variable to be in the environment of a particular subprocess
echo $varname                # checks a variable's value
echo $$                      # prints process ID of the current shell
echo $!                      # prints process ID of the most recently invoked background job
echo $?                      # displays the exit status of the last command
export VARNAME=value         # defines an environment variable (will be available in subprocesses)

array[0] = val               # several ways to define an array
array[1] = val
array[2] = val
array=([2]=val [0]=val [1]=val)
array(val val val)

${array[i]}                  # displays array's value for this index. If no index is supplied, array element 0 is assumed
${#array[i]}                 # to find out the length of any element in the array
${#array[@]}                 # to find out how many values there are in the array

declare -a                   # the variables are treaded as arrays
declare -f                   # uses funtion names only
declare -F                   # displays function names without definitions
declare -i                   # the variables are treaded as integers
declare -r                   # makes the variables read-only
declare -x                   # marks the variables for export via the environment

${varname:-word}             # if varname exists and isn't null, return its value; otherwise return word
${varname:=word}             # if varname exists and isn't null, return its value; otherwise set it word and then return its value
${varname:?message}          # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script
${varname:+word}             # if varname exists and isn't null, return word; otherwise return null
${varname:offset:length}     # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters

${variable#pattern}          # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
${variable##pattern}         # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
${variable%pattern}          # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
${variable%%pattern}         # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
${variable/pattern/string}   # the longest match to pattern in variable is replaced by string. Only the first match is replaced
${variable//pattern/string}  # the longest match to pattern in variable is replaced by string. All matches are replaced

${#varname}                  # returns the length of the value of the variable as a character string

*(patternlist)               # matches zero or more occurences of the given patterns
+(patternlist)               # matches one or more occurences of the given patterns
?(patternlist)               # matches zero or one occurence of the given patterns
@(patternlist)               # matches exactly one of the given patterns
!(patternlist)               # matches anything except one of the given patterns

$(UNIX command)              # command substitution: runs the command and returns standard output


# 2.2. Functions.
# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.
# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters.


functname() {
  shell commands
}

unset -f functname  # deletes a function definition
declare -f          # displays all defined functions in your login session


# 2.3. Flow Control.


statement1 && statement2  # and operator
statement1 || statement2  # or operator

-a                        # and operator inside a test conditional expression
-o                        # or operator inside a test conditional expression

str1=str2                 # str1 matches str2
str1!=str2                # str1 does not match str2
str1<str2                 # str1 is less than str2
str1>str2                 # str1 is greater than str2
-n str1                   # str1 is not null (has length greater than 0)
-z str1                   # str1 is null (has length 0)

-a file                   # file exists
-d file                   # file exists and is a directory
-e file                   # file exists; same -a
-f file                   # file exists and is a regular file (i.e., not a directory or other special type of file)
-r file                   # you have read permission
-r file                   # file exists and is not empty
-w file                   # your have write permission
-x file                   # you have execute permission on file, or directory search permission if it is a directory
-N file                   # file was modified since it was last read
-O file                   # you own file
-G file                   # file's group ID matches yours (or one of yours, if you are in multiple groups)
file1 -nt file2           # file1 is newer than file2
file1 -ot file2           # file1 is older than file2

-lt                       # less than
-le                       # less than or equal
-eq                       # equal
-ge                       # greater than or equal
-gt                       # greater than
-ne                       # not equal

if condition
then
  statements
[elif condition
  then statements...]
[else
  statements]
fi

for x := 1 to 10 do
begin
  statements
end

for name [in list]
do
  statements that can use $name
done

for (( initialisation ; ending condition ; update ))
do
  statements...
done

case expression in
  pattern1 )
    statements ;;
  pattern2 )
    statements ;;
  ...
esac

select name [in list]
do
  statements that can use $name
done

while condition; do
  statements
done

until condition; do
  statements
done


# 3. Command-Line Processing Cycle.


# The default order for command lookup is functions, followed by built-ins, with scripts and executables last.
# There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`.

command  # removes alias and function lookup. Only built-ins and commands found in the search path are executed
builtin  # looks up only built-in commands, ignoring functions and commands found in PATH
enable   # enables and disables shell built-ins

eval     # takes arguments and run them through the command-line processing steps all over again


# 4. Input/Output Redirectors.


cmd1|cmd2  # pipe; takes standard output of cmd1 as standard input to cmd2
> file     # directs standard output to file
< file     # takes standard input from file
>> file    # directs standard output to file; append to file if it already exists
>|file     # forces standard output to file even if noclobber is set
n>|file    # forces output to file from file descriptor n even if noclobber is set
<> file    # uses file as both standard input and standard output
n<>file    # uses file as both input and output for file descriptor n
<<label    # here-document
n>file     # directs file descriptor n to file
n<file     # takes file descriptor n from file
n>>file    # directs file description n to file; append to file if it already exists
n>&        # duplicates standard output to file descriptor n
n<&        # duplicates standard input from file descriptor n
n>&m       # file descriptor n is made to be a copy of the output file descriptor
n<&m       # file descriptor n is made to be a copy of the input file descriptor
&>file     # directs standard output and standard error to file
<&-        # closes the standard input
>&-        # closes the standard output
n>&-       # closes the ouput from file descriptor n
n<&-       # closes the input from file descripor n


# 5. Process Handling.


# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y.
# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal.
# Of course, to interupt a job, type CTRL+C.

myCommand &  # runs job in the background and prompts back the shell

jobs         # lists all jobs (use with -l to see associated PID)

fg           # brings a background job into the foreground
fg %+        # brings most recently invoked background job
fg %-        # brings second most recently invoked background job
fg %N        # brings job number N
fg %string   # brings job whose command begins with string
fg %?string  # brings job whose command contains string

kill -l      # returns a list of all signals on the system, by name and number
kill PID     # terminates process with specified PID

ps           # prints a line of information about the current running login shell and any processes running under it
ps -a        # selects all processes with a tty except session leaders

trap cmd sig1 sig2  # executes a command when a signal is received by the script
trap "" sig1 sig2   # ignores that signals
trap - sig1 sig2    # resets the action taken when the signal is received to the default

disown <PID|JID>    # removes the process from the list of jobs

wait                # waits until all background jobs have finished


# 6. Tips and Tricks.


# set an alias
cd; nano .bash_profile
> alias gentlenode='ssh admin@gentlenode.com -p 3404'  # add your alias in .bash_profile

# to quickly go to a specific directory
cd; nano .bashrc
> shopt -s cdable_vars
> export websites="/Users/mac/Documents/websites"

source .bashrc
cd websites


# 7. Debugging Shell Programs.


bash -n scriptname  # don't run commands; check for syntax errors only
set -o noexec       # alternative (set option in script)

bash -v scriptname  # echo commands before running them
set -o verbose      # alternative (set option in script)

bash -x scriptname  # echo commands after command-line processing
set -o xtrace       # alternative (set option in script)

trap 'echo $varname' EXIT  # useful when you want to print out the values of variables at the point that your script exits

function errtrap {
  es=$?
  echo "ERROR line $1: Command exited with status $es."
}

trap 'errtrap $LINENO' ERR  # is run whenever a command in the surrounding script or function exists with non-zero status 

function dbgtrap {
  echo "badvar is $badvar"
}

trap dbgtrap DEBUG  # causes the trap code to be executed before every statement in a function or script
# ...section of code in which the problem occurs...
trap - DEBUG  # turn off the DEBUG trap

function returntrap {
  echo "A return occured"
}

trap returntrap RETURN  # is executed each time a shell function or a script executed with the . or source commands finishes executing

sh Bash脚本安装Apache,MySQL和PHP以及PHPMyAdmin和一些调整。对于Debian和Ubuntu。要运行,请将脚本复制到se

Bash脚本安装Apache,MySQL和PHP以及PHPMyAdmin和一些调整。对于Debian和Ubuntu。要运行,请将脚本复制到服务器并运行``bash lamp.sh``

lamp.sh
#!/bin/sh

#######################################
# Bash script to install an AMP stack and PHPMyAdmin plus tweaks. For Debian based systems.
# Written by @AamnahAkram from http://aamnah.com

# In case of any errors (e.g. MySQL) just re-run the script. Nothing will be re-installed except for the packages with errors.
#######################################

#COLORS
# Reset
Color_Off='\033[0m'       # Text Reset

# Regular Colors
Red='\033[0;31m'          # Red
Green='\033[0;32m'        # Green
Yellow='\033[0;33m'       # Yellow
Purple='\033[0;35m'       # Purple
Cyan='\033[0;36m'         # Cyan

# Update packages and Upgrade system
echo -e "$Cyan \n Updating System.. $Color_Off"
sudo apt-get update -y && sudo apt-get upgrade -y

## Install AMP
echo -e "$Cyan \n Installing Apache2 $Color_Off"
sudo apt-get install apache2 apache2-doc apache2-mpm-prefork apache2-utils libexpat1 ssl-cert -y

echo -e "$Cyan \n Installing PHP & Requirements $Color_Off"
sudo apt-get install libapache2-mod-php5 php5 php5-common php5-curl php5-dev php5-gd php5-idn php-pear php5-imagick php5-mcrypt php5-mysql php5-ps php5-pspell php5-recode php5-xsl -y

echo -e "$Cyan \n Installing MySQL $Color_Off"
sudo apt-get install mysql-server mysql-client libmysqlclient15.dev -y

echo -e "$Cyan \n Installing phpMyAdmin $Color_Off"
sudo apt-get install phpmyadmin -y

echo -e "$Cyan \n Verifying installs$Color_Off"
sudo apt-get install apache2 libapache2-mod-php5 php5 mysql-server php-pear php5-mysql mysql-client mysql-server php5-mysql php5-gd -y

## TWEAKS and Settings
# Permissions
echo -e "$Cyan \n Permissions for /var/www $Color_Off"
sudo chown -R www-data:www-data /var/www
echo -e "$Green \n Permissions have been set $Color_Off"

# Enabling Mod Rewrite, required for WordPress permalinks and .htaccess files
echo -e "$Cyan \n Enabling Modules $Color_Off"
sudo a2enmod rewrite
sudo php5enmod mcrypt

# Restart Apache
echo -e "$Cyan \n Restarting Apache $Color_Off"
sudo service apache2 restart

sh VPS为Ubuntu 16.04安装bash脚本

VPS为Ubuntu 16.04安装bash脚本

readme.md
This script install and configure LEMP-environment for Ubuntu 16.04

1. Create VPS
2. Login as root
3. Download `install.sh`
4. `chmod 700 install.sh`
5. `bash ./install.sh`

####Software:

Nginx, PHP 7.0 with php7.0-fpm, Mysql 5.7, Redis, Memcached, Beanstalkd, Node.js 5, Supervisor, Composer, Fail2Ban

#####Settings:

Open ports only: 22, 80, 443

SSH password auth is disabled (only keys)


install.sh

# =================== YOUR DATA ========================

SERVER_NAME="some-server-name"
SERVER_IP="111.111.11.11"

USER="someuser"
SUDO_PASSWORD="secret-password-one"
MYSQL_ROOT_PASSWORD="secret-password-two"

# SSH access via password will be disabled. Use keys instead.
PUBLIC_SSH_KEYS="# Home
ssh-rsa AAAAB3NzaC1yc2EAAAA...... 
# Notebook
ssh-rsa AAAAB3NzaC1yc2EAAAA......
# Work
ssh-rsa AAAAB3NzaC1yc2EAAAA......"

# if vps not contains swap file - create it
SWAP_SIZE="1G"

TIMEZONE="Etc/GMT+0" # lits of avaiable timezones: ls -R --group-directories-first /usr/share/zoneinfo

# =================== LETS MAGIC BEGINS ================

# Prefer IPv4 over IPv6 - make apt-get faster

sudo sed -i "s/#precedence ::ffff:0:0\/96  100/precedence ::ffff:0:0\/96  100/" /etc/gai.conf

# Upgrade The Base Packages

apt-get update
apt-get upgrade -y

# Add A Few PPAs To Stay Current

apt-get install -y --force-yes software-properties-common

apt-add-repository ppa:nginx/development -y
apt-add-repository ppa:chris-lea/redis-server -y
apt-add-repository ppa:ondrej/apache2 -y
apt-add-repository ppa:ondrej/php -y

# Update Package Lists

apt-get update

# Base Packages

apt-get install -y --force-yes build-essential curl fail2ban gcc git libmcrypt4 libpcre3-dev \
make python2.7 python-pip supervisor ufw unattended-upgrades unzip whois zsh mc p7zip-full htop

# Install Python Httpie

pip install httpie

# Disable Password Authentication Over SSH

sed -i "/PasswordAuthentication yes/d" /etc/ssh/sshd_config
echo "" | sudo tee -a /etc/ssh/sshd_config
echo "" | sudo tee -a /etc/ssh/sshd_config
echo "PasswordAuthentication no" | sudo tee -a /etc/ssh/sshd_config

# Restart SSH

ssh-keygen -A
service ssh restart

# Set The Hostname If Necessary

echo "$SERVER_NAME" > /etc/hostname
sed -i "s/127\.0\.0\.1.*localhost/127.0.0.1	$SERVER_NAME localhost/" /etc/hosts
hostname $SERVER_NAME

# Set The Timezone

ln -sf /usr/share/zoneinfo/$TIMEZONE /etc/localtime

# Create The Root SSH Directory If Necessary

if [ ! -d /root/.ssh ]
then
    mkdir -p /root/.ssh
    touch /root/.ssh/authorized_keys
fi

# Setup User

useradd $USER
mkdir -p /home/$USER/.ssh
adduser $USER sudo

# Setup Bash For User

chsh -s /bin/bash $USER
cp /root/.profile /home/$USER/.profile
cp /root/.bashrc /home/$USER/.bashrc

# Set The Sudo Password For User

PASSWORD=$(mkpasswd $SUDO_PASSWORD)
usermod --password $PASSWORD $USER

# Build Formatted Keys & Copy Keys To User

cat > /root/.ssh/authorized_keys << EOF
$PUBLIC_SSH_KEYS
EOF

cp /root/.ssh/authorized_keys /home/$USER/.ssh/authorized_keys

# Create The Server SSH Key

ssh-keygen -f /home/$USER/.ssh/id_rsa -t rsa -N ''

# Copy Github And Bitbucket Public Keys Into Known Hosts File

ssh-keyscan -H github.com >> /home/$USER/.ssh/known_hosts
ssh-keyscan -H bitbucket.org >> /home/$USER/.ssh/known_hosts

# Setup Site Directory Permissions

chown -R $USER:$USER /home/$USER
chmod -R 755 /home/$USER
chmod 700 /home/$USER/.ssh/id_rsa

# Setup Unattended Security Upgrades

cat > /etc/apt/apt.conf.d/50unattended-upgrades << EOF
Unattended-Upgrade::Allowed-Origins {
    "Ubuntu xenial-security";
};
Unattended-Upgrade::Package-Blacklist {
    //
};
EOF

cat > /etc/apt/apt.conf.d/10periodic << EOF
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
EOF

# Setup UFW Firewall

ufw allow 22
ufw allow 80
ufw allow 443
ufw --force enable

# Allow FPM Restart

echo "$USER ALL=NOPASSWD: /usr/sbin/service php7.0-fpm reload" > /etc/sudoers.d/php-fpm

# Configure Supervisor Autostart

systemctl enable supervisor.service
service supervisor start

# Configure Swap Disk

if [ -f /swapfile ]; then
    echo "Swap exists."
else
    fallocate -l $SWAP_SIZE /swapfile
    chmod 600 /swapfile
    mkswap /swapfile
    swapon /swapfile
    echo "/swapfile none swap sw 0 0" >> /etc/fstab
    echo "vm.swappiness=30" >> /etc/sysctl.conf
    echo "vm.vfs_cache_pressure=50" >> /etc/sysctl.conf
fi

# Install Base PHP Packages

apt-get install -y --force-yes php7.0-cli php7.0-dev \
php-sqlite3 php-gd \
php-curl php7.0-dev \
php-imap php-mysql php-memcached php-mcrypt php-mbstring \
php-xml php-imagick php7.0-zip php7.0-bcmath php-soap \
php7.0-intl php7.0-readline

# Install Composer Package Manager

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

# Misc. PHP CLI Configuration

sudo sed -i "s/error_reporting = .*/error_reporting = E_ALL/" /etc/php/7.0/cli/php.ini
sudo sed -i "s/display_errors = .*/display_errors = On/" /etc/php/7.0/cli/php.ini
sudo sed -i "s/memory_limit = .*/memory_limit = 512M/" /etc/php/7.0/cli/php.ini
sudo sed -i "s/;date.timezone.*/date.timezone = UTC/" /etc/php/7.0/cli/php.ini

# Configure Sessions Directory Permissions

chmod 733 /var/lib/php/sessions
chmod +t /var/lib/php/sessions

# Install Nginx & PHP-FPM

apt-get install -y --force-yes nginx php7.0-fpm

# Generate dhparam File

openssl dhparam -out /etc/nginx/dhparams.pem 2048

# Disable The Default Nginx Site

rm /etc/nginx/sites-enabled/default
rm /etc/nginx/sites-available/default
service nginx restart

# Tweak Some PHP-FPM Settings

sed -i "s/error_reporting = .*/error_reporting = E_ALL/" /etc/php/7.0/fpm/php.ini
sed -i "s/display_errors = .*/display_errors = On/" /etc/php/7.0/fpm/php.ini
sed -i "s/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=0/" /etc/php/7.0/fpm/php.ini
sed -i "s/memory_limit = .*/memory_limit = 512M/" /etc/php/7.0/fpm/php.ini
sed -i "s/;date.timezone.*/date.timezone = UTC/" /etc/php/7.0/fpm/php.ini
sed -i "s/short_open_tag.*/short_open_tag = On/" /etc/php/7.0/fpm/php.ini

# Setup Session Save Path

sed -i "s/\;session.save_path = .*/session.save_path = \"\/var\/lib\/php5\/sessions\"/" /etc/php/7.0/fpm/php.ini
sed -i "s/php5\/sessions/php\/sessions/" /etc/php/7.0/fpm/php.ini

# Configure Nginx & PHP-FPM To Run As User

sed -i "s/user www-data;/user $USER;/" /etc/nginx/nginx.conf
sed -i "s/# server_names_hash_bucket_size.*/server_names_hash_bucket_size 64;/" /etc/nginx/nginx.conf
sed -i "s/^user = www-data/user = $USER/" /etc/php/7.0/fpm/pool.d/www.conf
sed -i "s/^group = www-data/group = $USER/" /etc/php/7.0/fpm/pool.d/www.conf
sed -i "s/;listen\.owner.*/listen.owner = $USER/" /etc/php/7.0/fpm/pool.d/www.conf
sed -i "s/;listen\.group.*/listen.group = $USER/" /etc/php/7.0/fpm/pool.d/www.conf
sed -i "s/;listen\.mode.*/listen.mode = 0666/" /etc/php/7.0/fpm/pool.d/www.conf

# Configure A Few More Server Things

sed -i "s/;request_terminate_timeout.*/request_terminate_timeout = 60/" /etc/php/7.0/fpm/pool.d/www.conf
sed -i "s/worker_processes.*/worker_processes auto;/" /etc/nginx/nginx.conf
sed -i "s/# multi_accept.*/multi_accept on;/" /etc/nginx/nginx.conf

# Install A Catch All Server

cat > /etc/nginx/sites-available/catch-all << EOF
server {
    return 404;
}
EOF

ln -s /etc/nginx/sites-available/catch-all /etc/nginx/sites-enabled/catch-all

cat > /etc/nginx/sites-available/example << EOF
server {
    listen 80;
    server_name somedomain.com;
    root /home/$USER/somedomain.com/public;

    index index.html index.htm index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    access_log off;
    error_log  /var/log/nginx/somedomain.com-error.log error;

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}
EOF

# Restart Nginx & PHP-FPM Services

if [ ! -z "\$(ps aux | grep php-fpm | grep -v grep)" ]
then
    service php7.0-fpm restart
fi

service nginx restart
service nginx reload

# Add User To www-data Group

usermod -a -G www-data $USER
id $USER
groups $USER

# Install Node.js

curl --silent --location https://deb.nodesource.com/setup_5.x | bash -

apt-get update

sudo apt-get install -y --force-yes nodejs

npm install -g pm2
npm install -g gulp

# Set The Automated Root Password

export DEBIAN_FRONTEND=noninteractive

debconf-set-selections <<< "mysql-community-server mysql-community-server/data-dir select ''"
debconf-set-selections <<< "mysql-community-server mysql-community-server/root-pass password $MYSQL_ROOT_PASSWORD"
debconf-set-selections <<< "mysql-community-server mysql-community-server/re-root-pass password $MYSQL_ROOT_PASSWORD"

# Install MySQL

apt-get install -y mysql-server

# Configure Password Expiration

echo "default_password_lifetime = 0" >> /etc/mysql/mysql.conf.d/mysqld.cnf

# Configure Access Permissions For Root & User

sed -i '/^bind-address/s/bind-address.*=.*/bind-address = */' /etc/mysql/mysql.conf.d/mysqld.cnf
mysql --user="root" --password="$MYSQL_ROOT_PASSWORD" -e "GRANT ALL ON *.* TO root@'$SERVER_IP' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';"
mysql --user="root" --password="$MYSQL_ROOT_PASSWORD" -e "GRANT ALL ON *.* TO root@'%' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';"
service mysql restart

mysql --user="root" --password="$MYSQL_ROOT_PASSWORD" -e "CREATE USER '$USER'@'$SERVER_IP' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD';"
mysql --user="root" --password="$MYSQL_ROOT_PASSWORD" -e "GRANT ALL ON *.* TO '$USER'@'$SERVER_IP' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD' WITH GRANT OPTION;"
mysql --user="root" --password="$MYSQL_ROOT_PASSWORD" -e "GRANT ALL ON *.* TO '$USER'@'%' IDENTIFIED BY '$MYSQL_ROOT_PASSWORD' WITH GRANT OPTION;"
mysql --user="root" --password="$MYSQL_ROOT_PASSWORD" -e "FLUSH PRIVILEGES;"

# Install & Configure Redis Server

apt-get install -y redis-server
sed -i 's/bind 127.0.0.1/bind 0.0.0.0/' /etc/redis/redis.conf
service redis-server restart

# Install & Configure Memcached

apt-get install -y memcached
sed -i 's/-l 127.0.0.1/-l 0.0.0.0/' /etc/memcached.conf
service memcached restart

# Install & Configure Beanstalk

apt-get install -y --force-yes beanstalkd
sed -i "s/BEANSTALKD_LISTEN_ADDR.*/BEANSTALKD_LISTEN_ADDR=0.0.0.0/" /etc/default/beanstalkd
sed -i "s/#START=yes/START=yes/" /etc/default/beanstalkd
/etc/init.d/beanstalkd start

sh 在我的Raspberry 2/3上设置ArchLinux ARM

在我的Raspberry 2/3上设置ArchLinux ARM

RPI2-ArchLinuxARM-Install.sh
#! /bin/sh
# Simple script to store all the necessary steps to setup my ArchLinux ARM on my raspberry 2

#-Get The image at https://archlinuxarm.org/platforms/armv7/broadcom/raspberry-pi-2
#-Burn It to the SD card
#-A good site that store all the tips is http://archpi.dabase.com

#-Making a general update of the system---
pacman -Syu

#-Installing necessary stuff 
pacman -S sudo htop git pkgfile base-devel

#-Adding alarm to the sudoers users (https://stackoverflow.com/questions/12736351/exit-save-edit-to-sudoers-file-putty-ssh)

#-Building yaourt (https://archlinux.fr/yaourt-en) AS standard user (not root)
git clone https://aur.archlinux.org/package-query.git
cd package-query
makepkg -si
cd ..
git clone https://aur.archlinux.org/yaourt.git
cd yaourt
makepkg -si
cd ..