BASH指令碼基礎 使用set

2021-09-29 16:27:33 字數 2904 閱讀 1175

這篇文章介紹一下在bash中使用set的方法。set可以用於設定指令碼的執行方式,指令碼啟動時也可以通過設定選項來進行設定。

在指令碼啟動的設定中,常見的一些選項都可以通過set來進行設定,比如

設定選項

設定選項

快捷設定選項

設定說明

語法檢查--n

用來進行bash語法的檢查

原始碼顯示

–verbose

-v用於在執行時顯示指令碼**

除錯-o xtrace

-x用於顯示執行時的狀態和結果

變數檢查

-o nounset

-u用於進行強制變數檢查

錯誤控制

-o errexit

-e用於設定遇到錯誤直接退出

管道錯誤控制

-o pipefail

-用於設定管道符連線的命令串的返回值,只要有乙個執行出錯,結果就會返回錯誤

具體使用示例可參看如下內容:

通過如下示例**的使用方式就會了解在什麼場景下使用set了

liumiaocn:scripts liumiao$ cat test_condition.sh |

awk''

1 #!/bin/bash

2 3 if

[ _""

!= _"$"];

then

4 set

$5 fi

6 7 build_dir=

"build_dir"

8 mkdir -p "$build_dir"

9 cd

$builddir

10 echo

"shell: $shell"

11 echo

"liumiao, current dir is : $"

12

13 echo

"begin build ..."

14

15 no such commands |

uname

16 echo

"[return value] = $?"

17 echo

"pipe operation completed ..."

18

19 no such commands

20 echo

"build completed ..."

21

liumiaocn:scripts liumiao$

不用更改指令碼,只需要在外部設定環境變數,即可將指令碼改變為遇到錯誤立即退出的執行方式。

liumiaocn:scripts liumiao$ export shell_set_options=-e

liumiaocn:scripts liumiao$ sh test_condition.sh

shell: /bin/bash

liumiao, current dir is :

begin build ...

test_condition.sh: line 15: no: command not found

darwin

[return value]

= 0pipe operation completed ...

test_condition.sh: line 19: no: command not found

liumiaocn:scripts liumiao$

不用更改指令碼,只需要在外部設定環境變數,即可將指令碼改編為除錯模式。

liumiaocn:scripts liumiao$ export shell_set_options=-x

liumiaocn:scripts liumiao$ sh test_condition.sh

+ build_dir=build_dir

+ mkdir -p build_dir

+ cd

+ echo

'shell: /bin/bash'

shell: /bin/bash

+ echo

'liumiao, current dir is : '

liumiao, current dir is :

+ echo

'begin build ...'

begin build ...

+ no such commands

test_condition.sh: line 15: no: command not found

+ uname

darwin

+ echo

'[return value] = 0'

[return value]

= 0+ echo

'pipe operation completed ...'

pipe operation completed ...

+ no such commands

test_condition.sh: line 19: no: command not found

+ echo

'build completed ...'

build completed ...

liumiaocn:scripts liumiao$

而事實上所有的引數都可以通過這種方式進行使用。

如果你也希望在指令碼中新增乙個除錯模式,通過外部環境變數的修改來控制**執行的結果,本文使用set給出的示例可能就可乙個給你乙個啟發,從而也能夠更好的理解為何可以通過指令碼的執行選項的方式可以設定的功能,bash還提供set用以設定了。

bash指令碼基礎

shell 指令碼 一 如何建立新shell指令碼?1.建立包含bash命令的文字檔案。檔案第一行應為 bin bash 2.使檔案可執行 使用chmod x scripts 3.將檔案放置在使用者的 path的目錄中 bin 用於使用者的私有程式 usr local bin 本地開發 系統上的其他...

bash指令碼基礎

新建bash指令碼 vim hello.sh bin bash echo hello world bin bash 在 bash 中 第一行的 及後面的 bin bash 就表明該檔案是乙個 bash 程式,需要由 bin 目錄下的 bash 程式來解釋執行。bash 這個程式一般是存放在 bin ...

Bash指令碼中的set命令

伺服器的開發和管理離不開 bash 指令碼,掌握它需要學習大量的細節。set命令是 bash 指令碼的重要環節,卻常常被忽視,導致指令碼的安全性和可維護性出問題。本文介紹它的基本用法,讓你可以更安心地使用 bash 指令碼。我們知道,bash 執行指令碼的時候,會建立乙個新的 shell。bash ...