shell脚本入门
1.创建一个shell脚本
在创建shell脚本时,必须在文件的第一行指定要使用的shell。格式是:
#!/bin/bash
在shell脚本中除了第一行是指定执行脚本的shell其他的#开头的行都是注释行,是不会执行的。
2.执行shell脚本
第一种方式:给shell脚本执行权限
#!/bin/bash echo -n The time and date are: date echo "Let's see who's logged into the system" who
chmod u+x first.sh
./first.sh
输出结果
The time and date are:2019年 01月 03日 星期四 05:29:31 EST Let's see who's logged into the system root tty1 2019-01-02 08:26 root pts/0 2019-01-03 03:40 (192.168.13.22) root pts/1 2019-01-03 04:46 (192.168.13.22) root pts/2 2019-01-03 04:46 (192.168.13.22)
第二种:使用sh 脚本名称
sh first.sh
3.显示消息
使用echo向控制台输出消息
#!/bin/bash echo -n The time and date are: date echo "Let's see who's logged into the system" # 如果输出的消息中需要打印处'的可以使用""包裹输出的消息 who
输出:
The time and date are:2019年 01月 03日 星期四 05:33:44 EST Let's see who's logged into the system root tty1 2019-01-02 08:26 root pts/0 2019-01-03 03:40 (192.168.13.22) root pts/1 2019-01-03 04:46 (192.168.13.22) root pts/2 2019-01-03 04:46 (192.168.13.22)
echo -n 将文本字符串和命令输出的字符串在同一行显示
4.使用变量
环境变量:
shell维护这一组环境变量,用于记录特定的系统信息。比如系统名称,登录到系统上的用户名等:
可以使用set命令查看当前完整的环境变量。
BASH=/bin/bash BASHOPTS=checkwinsize:cmdhist:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:login_shell:progcomp:promptvars:sourcepath BASH_ALIASES=() BASH_ARGC=() BASH_ARGV=() BASH_CMDS=() BASH_LINENO=() BASH_SOURCE=() BASH_VERSINFO=([0]="4" [1]="2" [2]="46" [3]="1" [4]="release" [5]="x86_64-redhat-linux-gnu") BASH_VERSION='4.2.46(1)-release' COLUMNS=129 DIRSTACK=() EUID=0 GROUPS=() HISTCONTROL=ignoredups HISTFILE=/root/.bash_history HISTFILESIZE=1000 HISTSIZE=1000 HOME=/root HOSTNAME=localhost.localdomain HOSTTYPE=x86_64 IFS=$' \t\n' LANG=zh_CN.UTF-8 LESSOPEN='||/usr/bin/lesspipe.sh %s' LINES=25 LOGNAME=root LS_COLORS='rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:' MACHTYPE=x86_64-redhat-linux-gnu MAIL=/var/spool/mail/root MAILCHECK=60 OLDPWD=/root OPTERR=1 OPTIND=1 OSTYPE=linux-gnu PATH=/opt/python36/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/opt/nginx1-12/sbin/:/root/bin PIPESTATUS=([0]="0") PPID=56458 PROMPT_COMMAND='printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"' PS1='[\u@\h \W]\$ ' PS2='> ' PS4='+ ' PWD=/usr/local/src RC=0 SELINUX_LEVEL_REQUESTED= SELINUX_ROLE_REQUESTED= SELINUX_USE_CURRENT_RANGE= SHELL=/bin/bash SHELLOPTS=braceexpand:emacs:hashall:histexpand:history:interactive-comments:monitor SHLVL=1 SSH_CLIENT='192.168.13.22 52571 22' SSH_CONNECTION='192.168.13.22 52571 192.168.13.61 22' SSH_TTY=/dev/pts/1 TERM=xterm UID=0 USER=root VIRTUALENVWRAPPER_ENV_BIN_DIR=bin VIRTUALENVWRAPPER_HOOK_DIR=/root/Envs VIRTUALENVWRAPPER_PROJECT_FILENAME=.project VIRTUALENVWRAPPER_PYTHON=/opt/python36/bin/python3 VIRTUALENVWRAPPER_SCRIPT=/opt/python36/bin/virtualenvwrapper.sh VIRTUALENVWRAPPER_VIRTUALENV=virtualenv VIRTUALENVWRAPPER_VIRTUALENV_ARGS=--no-site-packages VIRTUALENVWRAPPER_VIRTUALENV_CLONE=virtualenv-clone VIRTUALENVWRAPPER_WORKON_CD=1 WORKON_HOME=/root/Envs XDG_RUNTIME_DIR=/run/user/0 XDG_SESSION_ID=24 _=set colors=/root/.dircolors _cdsitepackages_complete () { local cur="$2"; COMPREPLY=($(cdsitepackages && compgen -d -- "${cur}" )) } _cdvirtualenv_complete () { local cur="$2"; COMPREPLY=($(cdvirtualenv && compgen -d -- "${cur}" )) } _lsvirtualenv_usage () { echo "lsvirtualenv [-blh]"; echo " -b -- brief mode"; echo " -l -- long mode"; echo " -h -- this help message" } _virtualenvs () { local cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "`virtualenvwrapper_show_workon_options`" -- ${cur})) } add2virtualenv () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_active_environment || return 1; site_packages="`virtualenvwrapper_get_site_packages_dir`"; if [ ! -d "${site_packages}" ]; then echo "ERROR: currently-active virtualenv does not appear to have a site-packages directory" 1>&2; return 1; fi; path_file="$site_packages/_virtualenv_path_extensions.pth"; if [ "$*" = "" ]; then echo "Usage: add2virtualenv dir [dir ...]"; if [ -f "$path_file" ]; then echo; echo "Existing paths:"; cat "$path_file" | grep --color=auto -v "^import"; fi; return 1; fi; remove=0; if [ "$1" = "-d" ]; then remove=1; shift; fi; if [ ! -f "$path_file" ]; then echo "import sys; sys.__plen = len(sys.path)" > "$path_file" || return 1; echo "import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)" >> "$path_file" || return 1; fi; for pydir in "$@"; do absolute_path="$(virtualenvwrapper_absolutepath "$pydir")"; if [ "$absolute_path" != "$pydir" ]; then echo "Warning: Converting \"$pydir\" to \"$absolute_path\"" 1>&2; fi; if [ $remove -eq 1 ]; then sed -i.tmp "\:^$absolute_path$: d" "$path_file"; else sed -i.tmp '1 a\ '"$absolute_path"' ' "$path_file"; fi; rm -i -f "${path_file}.tmp"; done; return 0 } allvirtualenv () { virtualenvwrapper_verify_workon_home || return 1; typeset d; IFS='%'; virtualenvwrapper_show_workon_options | while read d; do [ ! -d "$WORKON_HOME/$d" ] && continue; echo "$d"; echo "$d" | sed 's/./=/g'; ( source "$WORKON_HOME/$d/$VIRTUALENVWRAPPER_ENV_BIN_DIR/activate"; virtualenvwrapper_cd "$VIRTUAL_ENV"; "$@" ); echo; done; unset IFS } cdproject () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_active_environment || return 1; if [ -f "$VIRTUAL_ENV/$VIRTUALENVWRAPPER_PROJECT_FILENAME" ]; then typeset project_dir="$(cat "$VIRTUAL_ENV/$VIRTUALENVWRAPPER_PROJECT_FILENAME")"; if [ ! -z "$project_dir" ]; then virtualenvwrapper_cd "$project_dir"; else echo "Project directory $project_dir does not exist" 1>&2; return 1; fi; else echo "No project set in $VIRTUAL_ENV/$VIRTUALENVWRAPPER_PROJECT_FILENAME" 1>&2; return 1; fi; return 0 } cdsitepackages () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_active_environment || return 1; typeset site_packages="`virtualenvwrapper_get_site_packages_dir`"; virtualenvwrapper_cd "$site_packages/$1" } cdvirtualenv () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_active_environment || return 1; virtualenvwrapper_cd "$VIRTUAL_ENV/$1" } cpvirtualenv () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_virtualenv_clone || return 1; typeset src_name="$1"; typeset trg_name="$2"; typeset src; typeset trg; if [ "$src_name" = "" ]; then echo "Please provide a valid virtualenv to copy."; return 1; else if [ ! -e "$WORKON_HOME/$src_name" ]; then src="$(virtualenvwrapper_expandpath "$src_name")"; if [ ! -e "$src" ]; then echo "Please provide a valid virtualenv to copy."; return 1; fi; src_name="$(basename "$src")"; else src="$WORKON_HOME/$src_name"; fi; fi; if [ "$trg_name" = "" ]; then trg="$WORKON_HOME/$src_name"; trg_name="$src_name"; else trg="$WORKON_HOME/$trg_name"; fi; trg="$(virtualenvwrapper_expandpath "$trg")"; if [ -e "$trg" ]; then echo "$trg_name virtualenv already exists."; return 1; fi; echo "Copying $src_name as $trg_name..."; ( [ -n "$ZSH_VERSION" ] && setopt SH_WORD_SPLIT; virtualenvwrapper_cd "$WORKON_HOME" && "$VIRTUALENVWRAPPER_VIRTUALENV_CLONE" "$src" "$trg"; [ -d "$trg" ] && virtualenvwrapper_run_hook "pre_cpvirtualenv" "$src" "$trg_name" && virtualenvwrapper_run_hook "pre_mkvirtualenv" "$trg_name" ); typeset RC=$?; [ $RC -ne 0 ] && return $RC; [ ! -d "$WORKON_HOME/$trg_name" ] && return 1; workon "$trg_name"; virtualenvwrapper_run_hook "post_mkvirtualenv"; virtualenvwrapper_run_hook "post_cpvirtualenv" } lssitepackages () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_active_environment || return 1; typeset site_packages="`virtualenvwrapper_get_site_packages_dir`"; ls --color=auto $@ "$site_packages"; path_file="$site_packages/_virtualenv_path_extensions.pth"; if [ -f "$path_file" ]; then echo; echo "_virtualenv_path_extensions.pth:"; cat "$path_file"; fi } lsvirtualenv () { typeset long_mode=true; if command -v "getopts" > /dev/null 2>&1; then OPTIND=1; while getopts ":blh" opt "$@"; do case "$opt" in l) long_mode=true ;; b) long_mode=false ;; h) _lsvirtualenv_usage; return 1 ;; ?) echo "Invalid option: -$OPTARG" 1>&2; _lsvirtualenv_usage; return 1 ;; esac; done; else typeset -a args; args=($(getopt blh "$@")); if [ $? != 0 ]; then _lsvirtualenv_usage; return 1; fi; for opt in $args; do case "$opt" in -l) long_mode=true ;; -b) long_mode=false ;; -h) _lsvirtualenv_usage; return 1 ;; esac; done; fi; if $long_mode; then allvirtualenv showvirtualenv "$env_name"; else virtualenvwrapper_show_workon_options; fi } mkproject () { typeset -a in_args; typeset -a out_args; typeset -i i; typeset tst; typeset a; typeset t; typeset force; typeset templates; in_args=("$@"); force=0; if [ -n "$ZSH_VERSION" ]; then i=1; tst="-le"; else i=0; tst="-lt"; fi; while [ $i $tst $# ]; do a="${in_args[$i]}"; case "$a" in -h | --help) virtualenvwrapper_mkproject_help; return ;; -f | --force) force=1 ;; -t) i=$(( $i + 1 )); templates="$templates ${in_args[$i]}" ;; *) if [ ${#out_args} -gt 0 ]; then out_args=("${out_args[@]-}" "$a"); else out_args=("$a"); fi ;; esac; i=$(( $i + 1 )); done; set -- "${out_args[@]}"; eval "typeset envname=\$$#"; virtualenvwrapper_verify_project_home || return 1; if [ -d "$PROJECT_HOME/$envname" -a $force -eq 0 ]; then echo "Project $envname already exists." 1>&2; return 1; fi; mkvirtualenv "$@" || return 1; virtualenvwrapper_cd "$PROJECT_HOME"; virtualenvwrapper_run_hook "project.pre_mkproject" $envname; echo "Creating $PROJECT_HOME/$envname"; mkdir -p "$PROJECT_HOME/$envname"; setvirtualenvproject "$VIRTUAL_ENV" "$PROJECT_HOME/$envname"; virtualenvwrapper_cd "$PROJECT_HOME/$envname"; for t in $templates; do echo; echo "Applying template $t"; virtualenvwrapper_run_hook --name $(echo $t | sed 's/^ //') "project.template" "$envname" "$PROJECT_HOME/$envname"; done; virtualenvwrapper_run_hook "project.post_mkproject" } mktmpenv () { typeset tmpenvname; typeset RC; typeset -a in_args; typeset -a out_args; in_args=("$@"); if [ -n "$ZSH_VERSION" ]; then i=1; tst="-le"; else i=0; tst="-lt"; fi; typeset cd_after_activate=$VIRTUALENVWRAPPER_WORKON_CD; while [ $i $tst $# ]; do a="${in_args[$i]}"; case "$a" in -n | --no-cd) cd_after_activate=0 ;; -c | --cd) cd_after_activate=1 ;; *) if [ ${#out_args} -gt 0 ]; then out_args=("${out_args[@]-}" "$a"); else out_args=("$a"); fi ;; esac; i=$(( $i + 1 )); done; set -- "${out_args[@]}"; tmpenvname=$("$VIRTUALENVWRAPPER_PYTHON" -c 'import uuid,sys; sys.stdout.write(uuid.uuid4()+"\n")' 2>/dev/null); if [ -z "$tmpenvname" ]; then tmpenvname=$("$VIRTUALENVWRAPPER_PYTHON" -c 'import random,sys; sys.stdout.write(hex(random.getrandbits(64))[2:-1]+"\n")' 2>/dev/null); fi; tmpenvname="tmp-$tmpenvname"; mkvirtualenv "$@" "$tmpenvname"; RC=$?; if [ $RC -ne 0 ]; then return $RC; fi; [ "$cd_after_activate" = "1" ] && cdvirtualenv; echo "This is a temporary environment. It will be deleted when you run 'deactivate'." | tee "$VIRTUAL_ENV/README.tmpenv"; cat - >> "$VIRTUAL_ENV/$VIRTUALENVWRAPPER_ENV_BIN_DIR/postdeactivate" <<EOF if [ -f "$VIRTUAL_ENV/README.tmpenv" ] then echo "Removing temporary environment:" $(basename "$VIRTUAL_ENV") rmvirtualenv $(basename "$VIRTUAL_ENV") fi EOF } mkvirtualenv () { typeset -a in_args; typeset -a out_args; typeset -i i; typeset tst; typeset a; typeset envname; typeset requirements; typeset packages; typeset interpreter; typeset project; in_args=("$@"); if [ -n "$ZSH_VERSION" ]; then i=1; tst="-le"; else i=0; tst="-lt"; fi; while [ $i $tst $# ]; do a="${in_args[$i]}"; case "$a" in -a) i=$(( $i + 1 )); project="${in_args[$i]}"; if [ ! -d "$project" ]; then echo "Cannot associate project with $project, it is not a directory" 1>&2; return 1; fi; project="$(virtualenvwrapper_absolutepath ${project})" ;; -h | --help) virtualenvwrapper_mkvirtualenv_help $a; return ;; -i) i=$(( $i + 1 )); packages="$packages ${in_args[$i]}" ;; -p | --python*) if echo "$a" | grep --color=auto -q "="; then interpreter="$(echo "$a" | cut -f2 -d=)"; else i=$(( $i + 1 )); interpreter="${in_args[$i]}"; fi ;; -r) i=$(( $i + 1 )); requirements="${in_args[$i]}"; requirements="$(virtualenvwrapper_expandpath "$requirements")" ;; *) if [ ${#out_args} -gt 0 ]; then out_args=("${out_args[@]-}" "$a"); else out_args=("$a"); fi ;; esac; i=$(( $i + 1 )); done; if [ ! -z $interpreter ]; then out_args=("--python=$interpreter" ${out_args[@]}); fi; set -- "${out_args[@]}"; eval "envname=\$$#"; virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_virtualenv || return 1; ( [ -n "$ZSH_VERSION" ] && setopt SH_WORD_SPLIT; virtualenvwrapper_cd "$WORKON_HOME" && "$VIRTUALENVWRAPPER_VIRTUALENV" $VIRTUALENVWRAPPER_VIRTUALENV_ARGS "$@" && [ -d "$WORKON_HOME/$envname" ] && virtualenvwrapper_run_hook "pre_mkvirtualenv" "$envname" ); typeset RC=$?; [ $RC -ne 0 ] && return $RC; [ ! -d "$WORKON_HOME/$envname" ] && return 0; if [ ! -z "$project" ]; then setvirtualenvproject "$WORKON_HOME/$envname" "$project"; RC=$?; [ $RC -ne 0 ] && return $RC; fi; workon "$envname"; if [ ! -z "$requirements" ]; then pip install -r "$requirements"; fi; for a in $packages; do pip install $a; done; virtualenvwrapper_run_hook "post_mkvirtualenv" } rmvirtualenv () { virtualenvwrapper_verify_workon_home || return 1; if [ ${#@} = 0 ]; then echo "Please specify an environment." 1>&2; return 1; fi; typeset env_name; for env_name in "$@"; do echo "Removing $env_name..."; typeset env_dir="$WORKON_HOME/$env_name"; if [ "$VIRTUAL_ENV" = "$env_dir" ]; then echo "ERROR: You cannot remove the active environment ('$env_name')." 1>&2; echo "Either switch to another environment, or run 'deactivate'." 1>&2; return 1; fi; if [ ! -d "$env_dir" ]; then echo "Did not find environment $env_dir to remove." 1>&2; fi; typeset prior_dir="$(pwd)"; virtualenvwrapper_cd "$WORKON_HOME"; virtualenvwrapper_run_hook "pre_rmvirtualenv" "$env_name"; command \rm -rf "$env_dir"; virtualenvwrapper_run_hook "post_rmvirtualenv" "$env_name"; if [ -d "$prior_dir" ]; then virtualenvwrapper_cd "$prior_dir"; fi; done } setvirtualenvproject () { typeset venv="$1"; typeset prj="$2"; if [ -z "$venv" ]; then venv="$VIRTUAL_ENV"; fi; if [ -z "$prj" ]; then prj="$(pwd)"; else prj=$(virtualenvwrapper_absolutepath "${prj}"); fi; if [ ! -d "$venv" ]; then venv="$WORKON_HOME/$venv"; fi; if [ ! -d "$venv" ]; then echo "No virtualenv $(basename $venv)" 1>&2; return 1; fi; if [ ! -d "$prj" ]; then echo "Cannot associate virtualenv with \"$prj\", it is not a directory" 1>&2; return 1; fi; echo "Setting project for $(basename $venv) to $prj"; echo "$prj" > "$venv/$VIRTUALENVWRAPPER_PROJECT_FILENAME" } showvirtualenv () { typeset env_name="$1"; if [ -z "$env_name" ]; then if [ -z "$VIRTUAL_ENV" ]; then echo "showvirtualenv [env]"; return 1; fi; env_name=$(basename "$VIRTUAL_ENV"); fi; virtualenvwrapper_run_hook "get_env_details" "$env_name"; echo } toggleglobalsitepackages () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_active_environment || return 1; typeset no_global_site_packages_file="`virtualenvwrapper_get_site_packages_dir`/../no-global-site-packages.txt"; if [ -f $no_global_site_packages_file ]; then rm -i $no_global_site_packages_file; [ "$1" = "-q" ] || echo "Enabled global site-packages"; else touch $no_global_site_packages_file; [ "$1" = "-q" ] || echo "Disabled global site-packages"; fi } virtualenvwrapper () { cat <<EOF virtualenvwrapper is a set of extensions to Ian Bicking's virtualenv tool. The extensions include wrappers for creating and deleting virtual environments and otherwise managing your development workflow, making it easier to work on more than one project at a time without introducing conflicts in their dependencies. For more information please refer to the documentation: http://virtualenvwrapper.readthedocs.org/en/latest/command_ref.html Commands available: EOF typeset helpmarker="#:help:" cat "$VIRTUALENVWRAPPER_SCRIPT" | grep --color=auto "^$helpmarker" | sed -e "s/^$helpmarker/ /g" | sort | sed -e 's/$/\'' /g' } virtualenvwrapper_absolutepath () { if [ "$1" = "" ]; then return 1; else "$VIRTUALENVWRAPPER_PYTHON" -c "import os,sys; sys.stdout.write(os.path.abspath(\"$1\")+'\n')"; return 0; fi } virtualenvwrapper_cd () { if [ -n "${BASH:-}" ]; then builtin \cd "$@"; else if [ -n "${ZSH_VERSION:-}" ]; then builtin \cd -q "$@"; else command \cd "$@"; fi; fi } virtualenvwrapper_derive_workon_home () { typeset workon_home_dir="$WORKON_HOME"; if [ "$workon_home_dir" = "" ]; then workon_home_dir="$HOME/.virtualenvs"; fi; if echo "$workon_home_dir" | ( unset GREP_OPTIONS; command \grep '^[^/~]' > /dev/null ); then workon_home_dir="$HOME/$WORKON_HOME"; fi; if echo "$workon_home_dir" | ( unset GREP_OPTIONS; command \egrep '([\$~]|//)' > /dev/null ); then workon_home_dir="$(virtualenvwrapper_expandpath "$workon_home_dir")"; fi; echo "$workon_home_dir"; return 0 } virtualenvwrapper_expandpath () { if [ "$1" = "" ]; then return 1; else "$VIRTUALENVWRAPPER_PYTHON" -c "import os,sys; sys.stdout.write(os.path.normpath(os.path.expanduser(os.path.expandvars(\"$1\")))+'\n')"; return 0; fi } virtualenvwrapper_get_python_version () { "$VIRTUAL_ENV/$VIRTUALENVWRAPPER_ENV_BIN_DIR/python" -V 2>&1 | cut -f2 -d' ' | cut -f-2 -d. } virtualenvwrapper_get_site_packages_dir () { "$VIRTUAL_ENV/$VIRTUALENVWRAPPER_ENV_BIN_DIR/python" -c "import distutils.sysconfig; print(distutils.sysconfig.get_python_lib())" } virtualenvwrapper_initialize () { export WORKON_HOME="$(virtualenvwrapper_derive_workon_home)"; virtualenvwrapper_verify_workon_home -q || return 1; if [ "$VIRTUALENVWRAPPER_HOOK_DIR" = "" ]; then VIRTUALENVWRAPPER_HOOK_DIR="$WORKON_HOME"; fi; export VIRTUALENVWRAPPER_HOOK_DIR; mkdir -p "$VIRTUALENVWRAPPER_HOOK_DIR"; virtualenvwrapper_run_hook "initialize"; virtualenvwrapper_setup_tab_completion; return 0 } virtualenvwrapper_mkproject_help () { echo "Usage: mkproject [-f|--force] [-t template] [virtualenv options] project_name"; echo; echo "-f, --force Create the virtualenv even if the project directory"; echo " already exists"; echo; echo "Multiple templates may be selected. They are applied in the order"; echo "specified on the command line."; echo; echo "mkvirtualenv help:"; echo; mkvirtualenv -h; echo; echo "Available project templates:"; echo; "$VIRTUALENVWRAPPER_PYTHON" -c 'from virtualenvwrapper.hook_loader import main; main()' -l project.template } virtualenvwrapper_mktemp () { command \mktemp "$@" } virtualenvwrapper_mkvirtualenv_help () { echo "Usage: mkvirtualenv [-a project_path] [-i package] [-r requirements_file] [virtualenv options] env_name"; echo; echo " -a project_path"; echo; echo " Provide a full path to a project directory to associate with"; echo " the new environment."; echo; echo " -i package"; echo; echo " Install a package after the environment is created."; echo " This option may be repeated."; echo; echo " -r requirements_file"; echo; echo " Provide a pip requirements file to install a base set of packages"; echo " into the new environment."; echo; echo 'virtualenv help:'; echo; "$VIRTUALENVWRAPPER_VIRTUALENV" $@ } virtualenvwrapper_run_hook () { typeset hook_script; typeset result; hook_script="$(virtualenvwrapper_tempfile ${1}-hook)" || return 1; ( virtualenvwrapper_cd "$WORKON_HOME" && "$VIRTUALENVWRAPPER_PYTHON" -m 'virtualenvwrapper.hook_loader' ${HOOK_VERBOSE_OPTION:-} --script "$hook_script" "$@" ); result=$?; if [ $result -eq 0 ]; then if [ ! -f "$hook_script" ]; then echo "ERROR: virtualenvwrapper_run_hook could not find temporary file $hook_script" 1>&2; command \rm -f "$hook_script"; return 2; fi; source "$hook_script"; else if [ "${1}" = "initialize" ]; then cat - 1>&2 <<EOF virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=$VIRTUALENVWRAPPER_PYTHON and that PATH is set properly. EOF fi; fi command \rm -f "$hook_script"; return $result } virtualenvwrapper_setup_tab_completion () { if [ -n "${BASH:-}" ]; then function _virtualenvs () { local cur="${COMP_WORDS[COMP_CWORD]}"; COMPREPLY=($(compgen -W "`virtualenvwrapper_show_workon_options`" -- ${cur})) }; function _cdvirtualenv_complete () { local cur="$2"; COMPREPLY=($(cdvirtualenv && compgen -d -- "${cur}" )) }; function _cdsitepackages_complete () { local cur="$2"; COMPREPLY=($(cdsitepackages && compgen -d -- "${cur}" )) }; complete -o nospace -F _cdvirtualenv_complete -S/ cdvirtualenv; complete -o nospace -F _cdsitepackages_complete -S/ cdsitepackages; complete -o default -o nospace -F _virtualenvs workon; complete -o default -o nospace -F _virtualenvs rmvirtualenv; complete -o default -o nospace -F _virtualenvs cpvirtualenv; complete -o default -o nospace -F _virtualenvs showvirtualenv; else if [ -n "$ZSH_VERSION" ]; then function _virtualenvs () { reply=($(virtualenvwrapper_show_workon_options)) }; function _cdvirtualenv_complete () { reply=($(cdvirtualenv && ls -d ${1}*)) }; function _cdsitepackages_complete () { reply=($(cdsitepackages && ls -d ${1}*)) }; compctl -K _virtualenvs workon rmvirtualenv cpvirtualenv showvirtualenv; compctl -K _cdvirtualenv_complete cdvirtualenv; compctl -K _cdsitepackages_complete cdsitepackages; fi; fi } virtualenvwrapper_show_workon_options () { virtualenvwrapper_verify_workon_home || return 1; ( virtualenvwrapper_cd "$WORKON_HOME" && echo */$VIRTUALENVWRAPPER_ENV_BIN_DIR/activate ) 2> /dev/null | command \tr "\n" " " | command \sed "s|/$VIRTUALENVWRAPPER_ENV_BIN_DIR/activate |/|g" | command \tr "/" "\n" | command \sed "/^\s*$/d" | ( unset GREP_OPTIONS; command \egrep -v '^\*$' ) 2> /dev/null } virtualenvwrapper_tempfile () { typeset suffix=${1:-hook}; typeset file; file="$(virtualenvwrapper_mktemp -t virtualenvwrapper-$suffix-XXXXXXXXXX)"; touch "$file"; if [ $? -ne 0 ] || [ -z "$file" ] || [ ! -f "$file" ]; then echo "ERROR: virtualenvwrapper could not create a temporary file name." 1>&2; return 1; fi; echo $file; return 0 } virtualenvwrapper_verify_active_environment () { if [ ! -n "${VIRTUAL_ENV}" ] || [ ! -d "${VIRTUAL_ENV}" ]; then echo "ERROR: no virtualenv active, or active virtualenv is missing" 1>&2; return 1; fi; return 0 } virtualenvwrapper_verify_project_home () { if [ -z "$PROJECT_HOME" ]; then echo "ERROR: Set the PROJECT_HOME shell variable to the name of the directory where projects should be created." 1>&2; return 1; fi; if [ ! -d "$PROJECT_HOME" ]; then [ "$1" != "-q" ] && echo "ERROR: Project directory '$PROJECT_HOME' does not exist. Create it or set PROJECT_HOME to an existing directory." 1>&2; return 1; fi; return 0 } virtualenvwrapper_verify_resource () { typeset exe_path="$(command \which "$1" | (unset GREP_OPTIONS; command \grep -v "not found"))"; if [ "$exe_path" = "" ]; then echo "ERROR: virtualenvwrapper could not find $1 in your path" 1>&2; return 1; fi; if [ ! -e "$exe_path" ]; then echo "ERROR: Found $1 in path as \"$exe_path\" but that does not exist" 1>&2; return 1; fi; return 0 } virtualenvwrapper_verify_virtualenv () { virtualenvwrapper_verify_resource $VIRTUALENVWRAPPER_VIRTUALENV } virtualenvwrapper_verify_virtualenv_clone () { virtualenvwrapper_verify_resource $VIRTUALENVWRAPPER_VIRTUALENV_CLONE } virtualenvwrapper_verify_workon_environment () { typeset env_name="$1"; if [ ! -d "$WORKON_HOME/$env_name" ]; then echo "ERROR: Environment '$env_name' does not exist. Create it with 'mkvirtualenv $env_name'." 1>&2; return 1; fi; return 0 } virtualenvwrapper_verify_workon_home () { RC=0; if [ ! -d "$WORKON_HOME/" ]; then if [ "$1" != "-q" ]; then echo "NOTE: Virtual environments directory $WORKON_HOME does not exist. Creating..." 1>&2; fi; mkdir -p "$WORKON_HOME"; RC=$?; fi; return $RC } virtualenvwrapper_workon_help () { echo "Usage: workon env_name"; echo ""; echo " Deactivate any currently activated virtualenv"; echo " and activate the named environment, triggering"; echo " any hooks in the process."; echo ""; echo " workon"; echo ""; echo " Print a list of available environments."; echo " (See also lsvirtualenv -b)"; echo ""; echo " workon (-h|--help)"; echo ""; echo " Show this help message."; echo ""; echo " workon (-c|--cd) envname"; echo ""; echo " After activating the environment, cd to the associated"; echo " project directory if it is set."; echo ""; echo " workon (-n|--no-cd) envname"; echo ""; echo " After activating the environment, do not cd to the"; echo " associated project directory."; echo "" } wipeenv () { virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_active_environment || return 1; typeset req_file="$(virtualenvwrapper_tempfile "requirements.txt")"; pip freeze | egrep --color=auto -v '(distribute|wsgiref|appdirs|packaging|pyparsing|six)' > "$req_file"; if [ -n "$(cat "$req_file")" ]; then echo "Uninstalling packages:"; cat "$req_file"; echo; pip uninstall -y $(cat "$req_file" | grep -v '^-f' | sed 's/>/=/g' | cut -f1 -d=); else echo "Nothing to remove."; fi; rm -i -f "$req_file" } workon () { typeset -a in_args; typeset -a out_args; in_args=("$@"); if [ -n "$ZSH_VERSION" ]; then i=1; tst="-le"; else i=0; tst="-lt"; fi; typeset cd_after_activate=$VIRTUALENVWRAPPER_WORKON_CD; while [ $i $tst $# ]; do a="${in_args[$i]}"; case "$a" in -h | --help) virtualenvwrapper_workon_help; return 0 ;; -n | --no-cd) cd_after_activate=0 ;; -c | --cd) cd_after_activate=1 ;; *) if [ ${#out_args} -gt 0 ]; then out_args=("${out_args[@]-}" "$a"); else out_args=("$a"); fi ;; esac; i=$(( $i + 1 )); done; set -- "${out_args[@]}"; typeset env_name="$1"; if [ "$env_name" = "" ]; then lsvirtualenv -b; return 1; else if [ "$env_name" = "." ]; then IFS='%'; env_name="$(basename $(pwd))"; unset IFS; fi; fi; virtualenvwrapper_verify_workon_home || return 1; virtualenvwrapper_verify_workon_environment "$env_name" || return 1; activate="$WORKON_HOME/$env_name/$VIRTUALENVWRAPPER_ENV_BIN_DIR/activate"; if [ ! -f "$activate" ]; then echo "ERROR: Environment '$WORKON_HOME/$env_name' does not contain an activate script." 1>&2; return 1; fi; type deactivate > /dev/null 2>&1; if [ $? -eq 0 ]; then type deactivate | grep --color=auto 'typeset env_postdeactivate_hook' > /dev/null 2>&1; if [ $? -eq 0 ]; then deactivate; unset -f deactivate > /dev/null 2>&1; fi; fi; virtualenvwrapper_run_hook "pre_activate" "$env_name"; source "$activate"; virtualenvwrapper_original_deactivate=`typeset -f deactivate | sed 's/deactivate/virtualenv_deactivate/g'`; eval "$virtualenvwrapper_original_deactivate"; unset -f deactivate > /dev/null 2>&1; eval 'deactivate () { typeset env_postdeactivate_hook typeset old_env # Call the local hook before the global so we can undo # any settings made by the local postactivate first. virtualenvwrapper_run_hook "pre_deactivate" env_postdeactivate_hook="$VIRTUAL_ENV/$VIRTUALENVWRAPPER_ENV_BIN_DIR/postdeactivate" old_env=$(basename "$VIRTUAL_ENV") # Call the original function. virtualenv_deactivate $1 virtualenvwrapper_run_hook "post_deactivate" "$old_env" if [ ! "$1" = "nondestructive" ] then # Remove this function unset -f virtualenv_deactivate >/dev/null 2>&1 unset -f deactivate >/dev/null 2>&1 fi }'; VIRTUALENVWRAPPER_PROJECT_CD=$cd_after_activate virtualenvwrapper_run_hook "post_activate"; return 0 }
在脚本中可以直接使用这些环境变量
#!/bin/bash # display user information from the system. echo "User info for userid $USER" echo UID:$UID echo HOME:$HOME
输出:
User info for userid root UID:0 HOME:/root
有时我们希望shell不要解析$,比如:
echo "The cost of the item is \$15"
使用\告诉shell不再转义$,这里打印的就是美元符号了。
输出:
The cost of the item is $15
5.用户变量
用户变量可以是任何由字母,数字,下划线组成的文件字符串,长度不超过20个字符。用户变量区分大小写
#!/bin/bash # testing variables days=10 guest="ZJ" echo "$guest checked in $days days ago" days=5 guest="ZS" echo "$guest checked in $days days ago"
输出:
ZJ checked in 10 days ago ZS checked in 5 days ago
6.命令替换
shell脚本中最有用的特性之一就是可以从命令输出中提取信息,并将其赋给变量。把输出赋给变量之后,就可以在脚本中随意使用了。
有两种方法可以将命令输出赋给变量:
反引号字符(`)
$()格式
#!/bin/bash testing1=`date` echo date is: $testing1 testing2=$(who) echo info: $testing2
执行输出:
date is: 2019年 01月 03日 星期四 06:02:43 EST info: root tty1 2019-01-02 08:26 root pts/0 2019-01-03 03:40 (192.168.13.22) root pts/1 2019-01-03 05:59 (192.168.13.22) root pts/2 2019-01-03 05:59 (192.168.13.22)
根据时间生成唯一的文件名:
#!/bin/bash today=$(date +%Y%m%d%H%M%S) ls /usr/bin -al > log.$today
执行3次后的结果
[root@localhost src]# ll | grep 'log.*' -rw-r--r--. 1 root root 49223 1月 3 06:14 log.20190103061450 -rw-r--r--. 1 root root 49223 1月 3 06:15 log.20190103061502 -rw-r--r--. 1 root root 49223 1月 3 06:16 log.20190103061629
7.重定向输入和输出
输出重定向
> 覆盖重定向
[root@localhost src]# date > test4 [root@localhost src]# cat test4 2019年 01月 03日 星期四 06:20:31 EST [root@localhost src]#
>> 追加重定向
[root@localhost src]# date > test4 [root@localhost src]# cat test4 2019年 01月 03日 星期四 06:24:26 EST [root@localhost src]# who >> test4 [root@localhost src]# cat test4 2019年 01月 03日 星期四 06:24:26 EST root tty1 2019-01-02 08:26 root pts/1 2019-01-03 05:59 (192.168.13.22) root pts/2 2019-01-03 05:59 (192.168.13.22) [root@localhost src]# date > test4 # 原来的内容被清理掉了 [root@localhost src]# cat test4 2019年 01月 03日 星期四 06:25:16 EST [root@localhost src]#
输入从定向
输入重定向的符号是小于号(<):
浙公网安备 33010602011771号