Skip to content

Scripts

programming/shell has more stuff

Temporal files

Using mktemp.

#!/usr/bin/env sh

## Define the name and location for a temporal file
temp=$(mktemp "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")

## Add some text to the temp file
echo "1" >> "$temp"

## Recover the text
cat "$temp"

## Remove the file
rm "$temp"

Passwords in scripts

sha512sum.

#!/usr/bin/env sh
password="b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86"

if [ -z "$1" ]; then
  read -sp 'Password: ' input
else
  input="$1"
fi

hash="$( printf "$input" | sha512sum | cut -f 1 -d ' ' )"

if [ "$hash" = "$password" ]; then
  echo "Yes"
else
  echo "No"
  exit 1
fi

Parse arguments

Source https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash

#!/bin/bash

POSITIONAL=()
while [[ $# -gt 0 ]]
do
    key="$1"

    case $key in
        -e|--extension)
        EXTENSION="$2"
        shift # past argument
        shift # past value
        ;;
        -s|--searchpath)
        SEARCHPATH="$2"
        shift # past argument
        shift # past value
        ;;
        -l|--lib)
        LIBPATH="$2"
        shift # past argument
        shift # past value
        ;;
        --default)
        DEFAULT=YES
        shift # past argument
        ;;
        *)    # unknown option
        POSITIONAL+=("$1") # save it in an array for later
        shift # past argument
        ;;
    esac
done

set -- "${POSITIONAL[@]}" # restore positional parameters

echo "FILE EXTENSION  = ${EXTENSION}"
echo "SEARCH PATH     = ${SEARCHPATH}"
echo "LIBRARY PATH    = ${LIBPATH}"
echo "DEFAULT         = ${DEFAULT}"
echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l)
if [[ -n $1 ]]; then
    echo "Last line of file specified as non-opt/last argument:"
    tail -1 "$1"
fi