Scott Moser
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: til, shell, bash, blog --- # Today I learned: set -e sucks even more. [2023-04-23 - posted at https://smoser.github.io/2023/04/27/set-e-bad.html] **Summary: Just don't use set -e.** I've never been a fan "errexit" in shell. You've probably seen this as `set -e`, or `set -o errexit` or `sh -e`. People write lists of shell commands in a file and want the script to exit on the first one that fails rather than barreling on and causing damage. That seems sane. I've always strived to write "shell programs" rather than "shell scripts". The difference being that the program will clean up after itself and give sane error messages. It won't just exit when `mkdir` fails and leave the user to understand some message like: mkdir: cannot create directory ‘/tmp/work/bcd’: No such file or directory I've always felt that errexit makes "good error handling" in shell more difficult. The [bash(1)](http://manpages.ubuntu.com/manpages/bionic/en/man1/bash.1.html) man page has the following text: > > 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. Here's an example of how painful it can be, and I took way too long today tracking down what was wrong. 1. A Programmer starts off with a simple script `make-lvs` and uses `set -e`. ```bash= #!/bin/bash -ex lvm lvcreate --size=1G myvg -n mylv0 lvm lvcreate --size=1G myvg -n mylv1 ``` This looks fine for a "shell script". The `-x` argument even makes shell write to standard error the commands it is running. At this point everyone is happy. 2. Later the programmer looks at the script and realizes that he/she needs more flags to lvm lvcreate. So now the script looks like: ```bash= #!/bin/bash -ex lvm lvcreate --ignoremonitoring --yes --activate=y --setactivationskip=n --size=1G --name=mylv0 mylv0 lvm lvcreate --ignoremonitoring --yes --activate=y --setactivationskip=n --size=1G --name=mylv1 myvg ``` I'm happy that the programmer here used long format flags as they are much more self documenting so readers don't have to (as quickly) open up the [lvm man](http://manpages.ubuntu.com/manpages/bionic/en/man8/lvcreate.8.html) page. It is easier to make sense of that than it is to read '`lvm lvcreate --ignoremonitoring -y -ay -ky -L1G -n mylv`'. 3. After doing so, they realize that they can make this look a lot nicer, and reduce the copy/paste code with a simple function wrapper. ```bash= #!/bin/bash -e lvcreate() { echo "Creating lv $2 on vg $1 of size $3" lvm lvcreate "--size=$3" --ignoremonitoring --yes --activate=y \ --setactivationskip=n --name="$2" "$1" echo "Created $1/$2" } lvcreate myvg mylv0 1G lvcreate myvg mylv1 1G ``` The improvements are great. The complexity of the `lvm lvcreate` is abstracted away nicely. They've even dropped the vile `set -x` in favor of more human friendly messages. Output of a failing `lvm` command looks like this: $ make-lvs; echo "exited with $?" Creating lv mylv0 on vg myvg of size 1G out of space exited with 1 4. The next improvement is where sanity goes completely out the window. \[*I realize you were questioning my sanity long ago due to my pursuit of shell scripting perfection*\]. The programmer tries to add reasonable 'FATAL' messages that you might find in log messages of other other programming languages. ```bash= #!/bin/bash -e lvcreate() { echo "Creating lv $2 on vg $1 of size $3" lvm lvcreate "--size=$3" --ignoremonitoring --yes --activate=y \ --setactivationskip=n --name="$2" "$1" echo "Created $1/$2" } fail() { echo "FATAL:" "$@" 1>&2; exit 1; } lvcreate myvg mylv0 1G || fail "Failed to create mylv0" if ! lvcreate myvg mylv1 2G; then fail "Failed to create lylv1" fi echo "Success" ``` Can you guess what is going to happen here? If the `lvm` command fails (perhaps the vg is out of space) then the output of this script will look like: $ make-lvs; echo exited with $? Creating lv mylv1 on vg myvg of size 1G error: out of space Created myvg/mylv1 Creating lv mylv2 on vg myvg of size 1G error: out of space Created myvg/mylv2 Success exited with 0 The attempt to handle the failure of the `lvcreate` function with `||` on lines 10 and with `if !` on line 12 made it a "compound command". A compound command disables the error handling and shell exit that would have come from `-e` when the lvm command on line 4 failed. Above I've demonstrated with bash, but this is actually posix behavior, and you can just as well test the function with [`sh`](http://manpages.ubuntu.com/manpages/bionic/en/man1/sh.1.html) as well. madness. If you're interested in further reading, you can see this topic on the [BashFAQ](https://mywiki.wooledge.org/BashFAQ/105). I agree with GreyCat and geirha: "don't use set -e. Add your own error checking instead." If you're *still* here, the following is the version of the script that I'd like to see. Of course there are other improvements that can be made, but I'm happy with it. ```bash= #!/bin/bash info() { echo "$@" 1>&2; } stderror() { echo "$@" 1>&2; } fail() { stderror "FATAL:" "$@"; exit 1; } lvcreate() { local vg="$1" lv="$2" size="$3" info "Creating $vg/$lv size $size" lvm lvcreate \ --ignoremonitoring --yes --activate=y --setactivationskip=n \ --size="$size" --name="$lv" "$vg" || { stderror "failed to create $vg/$lv size $size" return 1 } info "Created $vg/$lv" } # this demonstrates both 'command ||' and 'if !command; then' styles. lvcreate myvg mylv0 1G || fail "Failed to create mylv0" if ! lvcreate myvg mylv1 1G; then fail "Failed to create mylv1" fi info "Success" ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully