Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

My header on top of every script

            #!/usr/bin/env bash
            set -eEuo pipefail
            # shellcheck disable=SC2034
            DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
            #######################################################


If you're using `set -e` you almost always want a trap on ERR to print where you suddenly exited from your program. Otherwise there's no way to tell.

Also worth mentioning, but not including permanently, is `set -x` which will print every command to stderr with a `+ ` prefix before running it.

For `DIR` I usually pick a name less likely to conflict with one randomly selected in my script, like `SCRIPT_DIR`.

You also need to think about symlinks and how you want to handle them. Your current `DIR` resolution gives you the directory name without any symlinks resolved. If you're possibly a script that got symlinked to by someone, this may not be the directory of your actual script anymore, but the directory containing the symlink. As long as you want that it's fine, but a lot of the time you want the script to see it's resolved folder so it can call scripts in the real folder with it instead


Wait... Most of my shell scripts have zero unused variables: I prefer to comment them if I may need them later on.

Why do you disable SC2034?

I don't think not having unused variables prevent me from doing things in my scripts!?

I understand if it's a preference but SC2034 is basically one of my biggest timesavers: in my case unused variables are typically a bug. Except, maybe, ANSI coloring variables at the top of the script.


It depends too on whether you use shellcheck as a primary tool or not. I prefer to have no shellcheck errors/warnings by default so when they do appear it's very obvious. But having a consistent opening block on a bunch of scripts is often more important, so setting a shellcheck disable on that one variable that may or may not be used is a better solution.


I disable it only for the DIR variable which I might not use.


I'd suggest `pwd -P` to resolve symlinks too. (if you use DIR to call/source neighbouring scripts).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: