文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書
1. set命令介紹
set
命令主要用來設(shè)置shell怎诫,在編寫shell腳本時(shí)瘾晃,使用set
命令能設(shè)置shell的執(zhí)行方式,根據(jù)需求不同幻妓,采用的參數(shù)設(shè)置也不同蹦误。set
命令也用來顯示系統(tǒng)中已存在的shell變量以及設(shè)置新的shell變量。
2. set命令的常用參數(shù)及作用
- set
不帶參數(shù)的set
命令用來顯示環(huán)境變量肉津。
root@3500f62fe5ae:/workspace# set
BASH=/bin/bash
BASHOPTS=checkwinsize:cmdhist:complete_fullquote:expand_aliases:extquote:force_fignore:histappend:hostcomplete:interactive_comments:progcomp:promptvars:sourcepath
BASH_ALIASES=()
BASH_ARGC=()
BASH_ARGV=()
BASH_CMDS=()
BASH_LINENO=()
BASH_SOURCE=()
BASH_VERSINFO=([0]="4" [1]="3" [2]="48" [3]="1" [4]="release" [5]="x86_64-pc-linux-gnu")
BASH_VERSION='4.3.48(1)-release'
COLUMNS=236
CUDA_HOME=/usr/local/cuda
CUDA_PKG_VERSION=10-0=10.0.130-1
CUDA_VERSION=10.0.130
CUDNN_VERSION=7.6.0.64
...
- set -e
-e
參數(shù)表示只要shell腳本中發(fā)生錯誤强胰,即命令返回值不等于0,則停止執(zhí)行并退出shell妹沙。set -e
在shell腳本中經(jīng)常使用偶洋。默認(rèn)情況下,shell腳本碰到錯誤會報(bào)錯距糖,但會繼續(xù)執(zhí)行后面的命令玄窝。
test.sh
腳本內(nèi)容如下:
#!/usr/bin/env bash
set -e
hello
echo "Hello set"
執(zhí)行結(jié)果如下:
root@3500f62fe5ae:/workspace# sh test.sh
test.sh: 4: test.sh: hello: not found
注:set +e
表示關(guān)閉-e選項(xiàng),set -e
表示重新打開-e選項(xiàng)悍引。
- set -u
-u
參數(shù)表示shell腳本執(zhí)行時(shí)如果遇到不存在的變量會報(bào)錯并停止執(zhí)行恩脂。默認(rèn)不加-u
參數(shù)的情況下,shell腳本遇到不存在的變量不會報(bào)錯吗铐,會繼續(xù)執(zhí)行东亦。
test.sh
腳本內(nèi)容如下:
#!/usr/bin/env bash
echo $test
set -u
echo $hello
執(zhí)行結(jié)果如下:
root@3500f62fe5ae:/workspace# sh test.sh
test.sh: 5: test.sh: hello: parameter not set