Skip to content

Instantly share code, notes, and snippets.

@shohi
Created March 16, 2020 03:54
Show Gist options
  • Save shohi/c77cc3a8518e5ca7a1756fab663ec4f2 to your computer and use it in GitHub Desktop.
Save shohi/c77cc3a8518e5ca7a1756fab663ec4f2 to your computer and use it in GitHub Desktop.
bash snippets

Bash Commands

String

local var=""

if [ -z "$var" ]; then
  echo "\$var is empty"
else
  echo "\$var is NOT empty"
fi
if [ -n "$1" ]; then
  echo "You supplied the first parameter!"
else
  echo "First parameter not supplied."
fi

可以使用非运算符-!, 如

if [[ ! -z "$var" ]]; then
  echo "\$var is NOT empty"
fi

File

  • 判断文件是否存在
if [[ -f "$file" ]]; then
  echo "File - $file exists"
else
  echo "File - $file does not exist"
fi
if [[ -L "$file" ]]; then
  echo "File - $file is symbolic link"
fi

读取符号链接所对应的真实文件名

local _uname="$(uname -s)"

if [[ "${_uname}" == "Darwin" ]]
then
    filepath="$(greadlink -f "$FILE")"
else
    filepath="$(readlink -f "$FILE")"
fi

Directory

FILE=/etc/docker
if [ -d "$FILE" ]; then
  echo "$FILE is a directory"
fi
  • 级联创建目录仅当其不存在的情况下
mkdir -p [/path/to/my/dir]

Array

TODO

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment