Bash

Bash

Bash / sh

#!/bin/sh

#!/bin/bash

Cheatsheet

If

if [ "$INTERFACE" != "pppoe-wan" ]
then
        exit
fi
  • Operator: =, !=
  • Logic operator : -a (and), -o (or)

Switch

# This script does a very simple test for checking disk space.

space=`df -h | awk '{print $5}' | grep % | grep -v Use | sort -n | tail -1 | cut -d "%" -f1 -`

case $space in
[1-6]*)
  Message="All is quiet."
  ;;
[7-8]*)
  Message="Start thinking about cleaning out some stuff.  There's a partition that is $space % full."
  ;;
9[1-8])
  Message="Better hurry with that new disk...  One partition is $space % full."
  ;;
99)
  Message="I'm drowning here!  There's a partition at $space %!"
  ;;
*)
  Message="I seem to be running with an nonexistent amount of disk space..."
  ;;
esac

Variables

FOO="${VARIABLE:-default}"  # If variable not set or null, use default.
FOO="${VARIABLE:=default}"  # If variable not set or null, set it to default.

Tips

Output binary data

# Only work in bash. DO NOT work in sh!
echo -n -e '\x01\x02' > file

fg error "bash:no job control in this shell"

You may need to enable job control:

#! /bin/bash   
set -m

cd "pwd" of script self file

参考这里

cd "${0%/*}"

or

SCRIPT_PATH=${0%/*}
if [ "$0" != "$SCRIPT_PATH" ] && [ "$SCRIPT_PATH" != "" ]; then 
    cd $SCRIPT_PATH
fi

Last update: 2022-03-17 07:41:45 UTC