bash scripting

Bash recipes

bash scripting

Proper escaping - Everything is a string

Accessing values

a="some string"

# this works, but I don't like it:
echo $a

# This is how I do it. Curly braces for string values:
echo "${a}"

Executing a command
# Running a command with backticks, but I don't like that:
fileContent=`cat 1.txt`

# Running a command with $( xxx )
fileContent="$( cat 1.txt )"
fileContent="$( echo "Hi" > 1.txt ; cat "./1.txt" ; rm ./1.txt )"

Defining variables

Creating and accessing an array in bash
declare releaseNames=( "api-poi" "api-trip" "api-user" "api-user-java" )

echo "The array contains ${#releaseNames[@]} elements:"

for releaseName in "${releaseNames[@]}"; do
echo "  -  ${releaseName}"

Creating and accessing a hashmap / dict bash

declare -A helmValues
helmValues["a"]="val a"
helmValues["b"]="val b"

echo "a: '${helmValues["a"]}'"
echo "b: '${helmValues["b"]}'"

Determine the directory of the script
d="$( dirname "$( readlink -f "$0" )" )"
echo "Running in directory ${d}"

results in

$ pwd

$ ./
Running in directory /mnt/c/github/chgeuer/tips

Span a command across multiple lines

Use a baskslash (\) at the end of the line (no additional whitespace), and preferably indent the next line:
response="$( cat payload.xml | curl \
  --silent --include \
  --request POST \
  --url "${triggerURI}" \
  --header "Content-Type: application/xml" \
  --data @- )"

echo "${response}"

Lambda-style functions in bash

# Define some function
function httpStatus {
  local url="$1"

  echo "$( curl \
  --silent \
  --output /dev/null \
  --write-out '%{http_code}' \
   "${url}" )"

function httpStatus2 { echo "$( curl --silent --output /dev/null --write-out '%{http_code}' $1 )" ; }

echo "Azure:    $( httpStatus "" )"
echo "Homepage: $( httpStatus2 "" )"

results in

$ ./
Azure:    200
Homepage: 200


Creating a text file

The cat > x <<-EOF ... EOF syntax allows to create a file in the local directory. Please not that the lines 6 and 7 below (the content) are prefixed with a tabstop (), which does not show up in the actual text file.



cat > somefile.ini <<-EOF

base64-encode a text

The command base64 --wrap=0 converts input into a long base64-encoded string without line breaks.


FILE_CONTENT="$( cat ./foo.bin )"
ONE_LONG_BASE64_STR=$(echo "${FILE_CONTENT}" | base64 --wrap=0)

Bash history

Put the following lines in ~/.inputrc:

## arrow up
## arrow down

Last updated