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

I group different kind of settings under particular files. My .bashrc has `source ~/.rc.d/pyenvrc`, `source ~/.rc.d/gitrc` and so on which can help to organize yourself if you have too many custom settings.

I also have a very tiny set of useful functions that I might occasionally use from some scripts. For example:

  # Changes the current working directory to the running script.
  cd_running_script_dir() {
      cd "$(dirname "$(readlink -f "$0")")"
  }

  # Display an error message and abort the running script.
  #
  # Arguments:
  #   $1: A string with error to be displayed before aborting.
  abort() {
      ERROR=$1

      >&2 echo "${ERROR}"
      kill $$
  }

  # Return a program's full path if exists or display an error
  # message and abort script execution.
  #
  # Arguments:
  #   $1: A string with the program's name to be looked up.
  get_program() {
      PROGRAM_NAME=$1
      PROGRAM_PATH=$(which "${PROGRAM_NAME}")

      if [ -z "${PROGRAM_PATH}" ]; then
          abort "Error - ${PROGRAM_NAME} is not installed."
      fi

      echo "${PROGRAM_PATH}"

      unset PROGRAM_PATH
      unset PROGRAM_NAME
  }

Given the sort of subtle nature of sh that for example misplacing a whitespace or a character can render a whole script wrong, from time to time I add these snippets so I can entirely forget how to do some regular things by sourcing `~/.scripts/lib.sh`. It's also a great way to extend your sh knowledge and learn about customizing your environment.

Yes these are silly functions, but their main purpose is to make sh snippets more readable.

Because I don't like to always display the same wallpaper over and over again my .xinitrc contains:

  "${HOME}/.scripts/set-random-background" &

which is:

  #!/usr/bin/env sh

  # Randomly sets a wallpaper from a directory containing images.
  #
  # Usage:
  #   ./set-random-background

  # Adjust global settings accordingly.
  WALLPAPERS_PATH="${HOME}/.scripts/assets/wallpapers"

  set_random_background() {
      FEH=$(get_program "feh")

      if [ -d "${WALLPAPERS_PATH}" ]; then
          WALLPAPER=$(ls "${WALLPAPERS_PATH}"/* | sort --random-sort | head -n1)

          if [ -n "${WALLPAPER}" ]; then
              ${FEH} --no-fehbg --bg-center --bg-scale "${WALLPAPER}"
          fi
      fi
  }

  main() {
      if [ -n "${BASH_LIB}" ]; then
          . "${BASH_LIB}"

          set_random_background
      fi
  }

  main




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

Search: