xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Linux shell script set -eux All In One

Linux shell script set -eux All In One

#!/usr/bin/env bash

# 设置 shell 选项的命令, exit, undefined, excute ❓退出,未定义,执行
set -eux

# 设置 env
# lang
# https://wttr.in/:translation
LANGUAGE="zh-CN"
CITY=Shanghai
# CITY=Moscow
UNIT=m
# UNIT=u
# m === °C (default)
# u === °F
# temperature
UA="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4343.0 Safari/537.36"

image

ChatGPT (GPT 3.5 free version)

prompt: 请扮演一个 Linux 系统专家来回答以下问题

Linux shell 脚本中 set -eux 是什么,有什么用处?

在Linux shell脚本中,set -eux 是一条常见的命令,用于设置脚本的执行行为。让我为您解释一下各个部分的含义和用途:

  1. set:这是用于设置 shell 选项的命令。

  2. -e:这是set命令的一个选项,它表示"Exit immediately if a command exits with a non-zero status",即如果任何命令的退出状态码(返回值)不为0,脚本将立即退出。这对于确保脚本在出现错误时立即停止执行非常有用,以防止错误的状态继续传播。

  3. -u:这是set命令的另一个选项,它表示"Treat unset variables as an error when substituting",即如果尝试使用未定义的变量,脚本将产生错误并退出。这有助于捕获脚本中可能导致问题的变量未正确设置的情况。

  4. -x:这也是set命令的选项,它表示"Print each command before executing it",即在执行每个命令之前,将该命令打印到标准错误输出。这对于调试脚本非常有用,因为它可以帮助您查看脚本的执行流程变量的值

综合起来,set -eux 是一种常用的shell脚本设置,它有助于使脚本更加健壮易于调试。它可以帮助您在脚本执行期间捕获错误,并在脚本中使用未定义的变量时产生错误,同时还提供了执行跟踪,以便更好地理解脚本的执行流程

image

https://chat.openai.com/c/d3e9ae9e-8eb7-4b00-8d6d-a16b79435a81

man set

The set command is a shell builtin command that is used to set and unset a value of the local variables in shell.
set 命令是 shell 内置命令,用于设置取消设置 shell 中局部变量

$ set [--abBCefhHkmnpPtuvx] [-o option] [arg …]

  1. -e

Exit immediately if a pipeline (which may consist of a single simple command), a list, or a compound command (see SHELL GRAMMAR above), exits with a non-zero status.
The shell does not exit if the command that fails is part of the command list immediately following a while or until keyword, part of the test following the if or elif reserved words, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command,s return value is being inverted with !.
If a compound command other than a subshell returns a non-zero status because a command failed while -e was being ignored, the shell does not exit.
A trap on ERR, if set, is executed before the shell exits.
This option applies to the shell environment and each subshell environment separately (see COMMAND EXECUTION ENVIRONMENT above), and may cause subshells to exit before executing all the commands in the subshell.

If a compound command or shell function executes in a context where -e is being ignored, none of the commands executed within the compound command or function body will be affected by the -e setting, even if -e is set and a command returns a failure status.
If a compound command or shell functionsets -e while executing in a context where -e is ignored, that setting will not have any effect until the compound command or the command containing the function call completes.

  1. -u

Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion.
If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status.

  1. -x

After expanding each simple command, for command, case command, select command, or arithmetic for command, display the expanded value of PS4, followed by the command and its expanded arguments or associated word list.

# ...
       set [--abefhkmnptuvxBCEHPT] [-o option-name] [arg ...]
       set [+abefhkmnptuvxBCEHPT] [+o option-name] [arg ...]
              Without  options,  the  name  and  value  of each shell variable are displayed in a
              format that can be reused as input  for  setting  or  resetting  the  currently-set
              variables.   Read-only  variables  cannot  be  reset.   In  posix  mode, only shell
              variables are listed.  The output is sorted according to the current locale.   When
              options are specified, they set or unset shell attributes.  Any arguments remaining
              after option processing are treated as values for the positional parameters and are
              assigned,  in order, to $1, $2, ...  $n.  Options, if specified, have the following
              meanings:
              -a      Each variable or function that is created or modified is given  the  export
                      attribute and marked for export to the environment of subsequent commands.
              -b      Report  the  status  of terminated background jobs immediately, rather than
                      before the next primary prompt.  This is effective only when job control is
                      enabled.
              -e      Exit  immediately  if  a  pipeline  (which  may  consist of a single simple
                      command), a list, or a compound command (see SHELL  GRAMMAR  above),  exits
                      with  a non-zero status.  The shell does not exit if the command that fails
                      is part of the command list immediately following a while or until keyword,
                      part  of  the  test  following  the  if or elif reserved words, part of any
                      command executed in a && or || list except the command following the  final
                      &&  or  ||,  any  command  in  a pipeline but the last, or if the command,s
                      return value is being inverted with !.  If a compound command other than  a
                      subshell  returns  a  non-zero status because a command failed while -e was
                      being ignored, the shell does not exit.  A trap on ERR, if set, is executed
                      before  the  shell exits.  This option applies to the shell environment and
                      each subshell environment separately  (see  COMMAND  EXECUTION  ENVIRONMENT
                      above),  and  may cause subshells to exit before executing all the commands
                      in the subshell.

                      If a compound command or shell function executes in a context where  -e  is
                      being ignored, none of the commands executed within the compound command or
                      function body will be affected by the -e setting, even if -e is set  and  a
                      command  returns a failure status.  If a compound command or shell function
                      sets -e while executing in a context where -e is ignored, that setting will
                      not  have  any  effect until the compound command or the command containing
                      the function call completes.
              -f      Disable pathname expansion.
              -h      Remember the location of commands as they  are  looked  up  for  execution.
                      This is enabled by default.
              -k      All  arguments  in  the  form  of  assignment  statements are placed in the
                      environment for a command, not just those that precede the command name.
              -m      Monitor mode.  Job control is enabled.  This option is on  by  default  for
                      interactive shells on systems that support it (see JOB CONTROL above).  All
                      processes  run  in  a  separate  process  group.   When  a  background  job
                      completes, the shell prints a line containing its exit status.
              -n      Read  commands  but do not execute them.  This may be used to check a shell
                      script for syntax errors.  This is ignored by interactive shells.
              -o option-name
                      The option-name can be one of the following:
                      allexport
                              Same as -a.
                      braceexpand
                              Same as -B.
                      emacs   Use an emacs-style command line editing interface.  This is enabled
                              by  default  when  the  shell  is  interactive, unless the shell is
                              started with the --noediting option.  This also affects the editing
                              interface used for read -e.
                      errexit Same as -e.
                      errtrace
                              Same as -E.
                      functrace
                              Same as -T.
                      hashall Same as -h.
                      histexpand
                              Same as -H.
                      history Enable  command  history,  as  described above under HISTORY.  This
                              option is on by default in interactive shells.
                      ignoreeof
                              The effect is as if the shell  command  ``IGNOREEOF=10''  had  been
                              executed (see Shell Variables above).
                      keyword Same as -k.
                      monitor Same as -m.
                      noclobber
                              Same as -C.
                      noexec  Same as -n.
                      noglob  Same as -f.
                      nolog   Currently ignored.
                      notify  Same as -b.
                      nounset Same as -u.
                      onecmd  Same as -t.
                      physical
                              Same as -P.
                      pipefail
                              If  set,  the  return  value of a pipeline is the value of the last
                              (rightmost) command to exit with a non-zero status, or zero if  all
                              commands  in  the  pipeline  exit  successfully.   This  option  is
                              disabled by default.
                      posix   Change the behavior of bash where  the  default  operation  differs
                              from  the  POSIX  standard to match the standard (posix mode).  See
                              SEE ALSO below for a reference to a document that details how posix
                              mode affects bash,s behavior.
                      privileged
                              Same as -p.
                      verbose Same as -v.
                      vi      Use  a  vi-style command line editing interface.  This also affects
                              the editing interface used for read -e.
                      xtrace  Same as -x.
                      If -o is supplied with no option-name, the values of  the  current  options
                      are  printed.   If  +o  is  supplied  with  no option-name, a series of set
                      commands to recreate the  current  option  settings  is  displayed  on  the
                      standard output.
              -p      Turn  on  privileged  mode.  In this mode, the $ENV and $BASH_ENV files are
                      not processed, shell functions are not inherited from the environment,  and
                      the  SHELLOPTS,  BASHOPTS, CDPATH, and GLOBIGNORE variables, if they appear
                      in the environment,  are  ignored.   If  the  shell  is  started  with  the
                      effective user (group) id not equal to the real user (group) id, and the -p
                      option is not supplied, these actions are taken and the effective  user  id
                      is  set  to the real user id.  If the -p option is supplied at startup, the
                      effective user id is  not  reset.   Turning  this  option  off  causes  the
                      effective user and group ids to be set to the real user and group ids.
              -t      Exit after reading and executing one command.
              -u      Treat  unset variables and parameters other than the special parameters "@"
                      and "*" as an error when performing parameter expansion.  If  expansion  is
                      attempted  on  an  unset  variable  or parameter, the shell prints an error
                      message, and, if not interactive, exits with a non-zero status.
              -v      Print shell input lines as they are read.
              -x      After expanding each simple command,  for  command,  case  command,  select
                      command,  or  arithmetic  for  command,  display the expanded value of PS4,
                      followed by the command and its expanded arguments or associated word list.
              -B      The shell performs brace expansion (see Brace Expansion above).  This is on
                      by default.
              -C      If  set,  bash  does  not overwrite an existing file with the >, >&, and <>
                      redirection operators.  This may be overridden when creating  output  files
                      by using the redirection operator >| instead of >.
              -E      If  set,  any  trap  on  ERR  is  inherited  by  shell  functions,  command
                      substitutions, and commands executed in a subshell  environment.   The  ERR
                      trap is normally not inherited in such cases.
              -H      Enable  !   style  history substitution.  This option is on by default when
                      the shell is interactive.
              -P      If set, the shell does not resolve symbolic links when  executing  commands
                      such as cd that change the current working directory.  It uses the physical
                      directory structure instead.  By default, bash follows the logical chain of
                      directories when performing commands which change the current directory.
              -T      If  set,  any  traps  on DEBUG and RETURN are inherited by shell functions,
                      command substitutions, and commands executed  in  a  subshell  environment.
                      The DEBUG and RETURN traps are normally not inherited in such cases.
              --      If  no  arguments  follow  this  option, then the positional parameters are
                      unset.  Otherwise, the positional parameters are set to the args,  even  if
                      some of them begin with a -.
              -       Signal  the  end of options, cause all remaining args to be assigned to the
                      positional parameters.  The -x and -v options are turned off.  If there are
                      no args, the positional parameters remain unchanged.

              The  options  are  off  by  default  unless otherwise noted.  Using + rather than -
              causes these options to be turned off.   The  options  can  also  be  specified  as
              arguments  to  an invocation of the shell.  The current set of options may be found
              in $-.  The return status is always true unless an invalid option is encountered.

# ...

https://manpages.ubuntu.com/manpages/jammy/en/man1/bash.1.html#shell builtin commands

https://manpages.ubuntu.com/manpages/jammy/en/man1/bash.1.html

# 查看
$ set
# 使用 pipe 直接把输出复制到系统剪切板 🚀
$ set | pbcopy
'!'=0
'#'=0
'$'=76309
'*'=(  )
0=-zsh
'?'=0
@=(  )
ARGC=0
BG
CDPATH=''
COLUMNS=95
CPUTYPE=x86_64
EGID=20
EUID=501
FG
FIGNORE=''
FPATH=/Users/xgqfrms-mm/.oh-my-zsh/plugins/git:/Users/xgqfrms-mm/.oh-my-zsh/functions:/Users/xgqfrms-mm/.oh-my-zsh/completions:/usr/local/share/zsh/site-functions:/usr/share/zsh/site-functions:/usr/share/zsh/5.9/functions
FUNCNEST=700
FX
GID=20
HISTCHARS='!^#'
HISTCMD=6620
HISTFILE=/Users/xgqfrms-mm/.zsh_history
HISTSIZE=50000
HOME=/Users/xgqfrms-mm
HOST=xgqfrms-mm.local
IFS=$' \t\n\C-@'
KEYBOARD_HACK=''
KEYTIMEOUT=40
LC_CTYPE=UTF-8
LESS=-R
LINENO=14
LINES=68
LISTMAX=100
LOGNAME=xgqfrms-mm
MACHTYPE=x86_64
MAILCHECK=60
MAILPATH=''
MANPATH=''
MATCH=m
MBEGIN=1
MEND=1
MODULE_PATH=/usr/lib/zsh/5.9
NULLCMD=cat
NVM_BIN=/Users/xgqfrms-mm/.nvm/versions/node/v18.12.0/bin
# 省略 ...

demos

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

#!/usr/bin/env bash vs #!/usr/bin/bash vs #!/bin/bash

https://www.cnblogs.com/xgqfrms/p/17369184.html

set & unset

       set [ {+|-}options | {+|-}o [ option_name ] ] ... [ {+|-}A [ name ] ]
           [ arg ... ]
              Set the options for the shell and/or set the positional
              parameters, or declare and set an array.  If the -s option is
              given, it causes the specified arguments to be sorted before
              assigning them to the positional parameters (or to the array
              name if -A is used).  With +s sort arguments in descending
              order.  For the meaning of the other flags, see zshoptions(1).
              Flags may be specified by name using the -o option. If no option
              name is supplied with -o, the current option states are printed:
              see the description of setopt below for more information on the
              format.  With +o they are printed in a form that can be used as
              input to the shell.

              If the -A flag is specified, name is set to an array containing
              the given args; if no name is specified, all arrays are printed
              together with their values.

              If +A is used and name is an array, the given arguments will
              replace the initial elements of that array; if no name is
              specified, all arrays are printed without their values.

              The behaviour of arguments after -A name or +A name depends on
              whether the option KSH_ARRAYS is set.  If it is not set, all
              arguments following name are treated as values for the array,
              regardless of their form.  If the option is set, normal option
              processing continues at that point; only regular arguments are
              treated as values for the array.  This means that

                     set -A array -x -- foo

              sets array to `-x -- foo' if KSH_ARRAYS is not set, but sets the
              array to foo and turns on the option `-x' if it is set.

              If the -A flag is not present, but there are arguments beyond
              the options, the positional parameters are set.  If the option
              list (if any) is terminated by `--', and there are no further
              arguments, the positional parameters will be unset.

              If no arguments and no `--' are given, then the names and values
              of all parameters are printed on the standard output.  If the
              only argument is `+', the names of all parameters are printed.

              For historical reasons, `set -' is treated as `set +xv' and `set
              - args' as `set +xv -- args' when in any other emulation mode
              than zsh's native mode.


$ man zshbuiltins
# $ man zshbuiltins | grep set

# Unknown locale, assuming C
$ locale
LANG=""
LC_COLLATE="C"
LC_CTYPE="UTF-8"
LC_MESSAGES="C"
LC_MONETARY="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_ALL=

# fix
$ export LANG="en_US.UTF-8"
$ locale
LANG="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL=

https://stackoverflow.com/questions/77058657/why-both-the-set-and-unset-commands-dont-work-as-expected-in-my-macos-terminal#comment135847407_77058657

https://pubs.opengroup.org/onlinepubs/007904875/utilities/set.html

       unset [ -fmv ] name ...
              Each named parameter is unset.  Local parameters remain local
              even if unset; they appear unset within scope, but the previous
              value will still reappear when the scope ends.

              Individual elements of associative array parameters may be unset
              by using subscript syntax on name, which should be quoted (or
              the entire command prefixed with noglob) to protect the
              subscript from filename generation.

              If the -m flag is specified the arguments are taken as patterns
              (should be quoted) and all parameters with matching names are
              unset.  Note that this cannot be used when unsetting associative
              array elements, as the subscript will be treated as part of the
              pattern.

              The -v flag specifies that name refers to parameters. This is
              the default behaviour.

              unset -f is equivalent to unfunction.

https://pubs.opengroup.org/onlinepubs/007904875/utilities/unset.html

refs

https://www.baeldung.com/linux/set-command

https://askubuntu.com/questions/1455037/what-does-set-eu-do-in-a-bash-script

https://stackoverflow.com/questions/19622198/what-does-set-e-mean-in-a-bash-script

https://unix.stackexchange.com/questions/544993/what-does-set-u-do-in-bash-script

https://www.freecodecamp.org/news/bash-scripting-tutorial-linux-shell-script-and-command-line-for-beginners/#:~:text=troubleshooting Bash scripts.-,Set the set -x option,-One of the



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2023-09-06 23:26  xgqfrms  阅读(97)  评论(1编辑  收藏  举报