BASH¶

A Jupyter kernel for bash: github repo. Other available Jupyter kernels can be found here

pip3 install bash_kernel --break-system-packages
python3 -m bash_kernel.install
In [1]:
ls
discordo.md			README.md
euporie.jupyter-terminal.md	tmp-env
lue.ebook-reader.md

Function¶

Checking if a bash function argument is Empty¶

In Bash, you can check if a function argument is empty using several methods:

  • method 1: Using -z test operator
  • method 2: Direct string comparison
  • method 3: Using parameter expansion with default value test
  • method 4: Check if argument count is sufficient

The -z test operator (Method 1) is the most common and recommended approach as it specifically tests if the string length is zero.

In [1]:
# Method 1: Using -z test operator
my_function() {
  if [ -z "$1" ]; then
    echo "First argument is empty or not provided"
  else
    echo "First argument is: $1"
  fi
}

my_function
my_function "Hello"
First argument is empty or not provided
First argument is: Hello
In [2]:
# Method 2: Direct string comparison
my_function() {
  if [ "$1" = "" ]; then
    echo "First argument is empty"
  else
    echo "First argument is: $1"
  fi
}

my_function
my_function "Hello"
First argument is empty
First argument is: Hello
In [0]:
# Method 3: Using parameter expansion with default value test
my_function() {
  if [ "${1:-}" = "" ]; then
    echo "First argument is empty or not provided"
  else
    echo "First argument is: $1"
  fi
}
my_function
my_function "Hello"
First argument is empty or not provided
First argument is: Hello
In [4]:
# Method 4: Check if argument count is sufficient
my_function() {
  if [ $# -lt 1 ]; then
    echo "Not enough arguments provided"
  else
    echo "First argument is: $1"
  fi
}
my_function
my_function "Hello"
Not enough arguments provided
First argument is: Hello

The Magic of Stubbing sh¶

References:

  • The Magic of Stubbing sh
In [5]:
#!/bin/bash -e

function test_tmp_files() {
  local workspace=$(mktemp -d)
  touch "$workspace/not_temp.sh"
  local first=$(mktemp)
  local second=$(mktemp)

  echo "WOW" > $second

  echo '----'
  realpath $workspace
  ls -la $workspace
  realpath $first
  realpath $second
  cat $first
  cat $second
  echo '----'

  rm $first
  rm $second
}
test_tmp_files
----
/private/var/folders/d8/4yrcb4_92fn4qz0cfwpln2hw0000gn/T/tmp.vkiOMVJtYX
total 0
drwx------    3 igorribeirolima  staff     96 Oct 26 21:26 .
drwx------@ 458 igorribeirolima  staff  14656 Oct 26 21:26 ..
-rw-r--r--    1 igorribeirolima  staff      0 Oct 26 21:26 not_temp.sh
/private/var/folders/d8/4yrcb4_92fn4qz0cfwpln2hw0000gn/T/tmp.Dm2cYFpkGi
/private/var/folders/d8/4yrcb4_92fn4qz0cfwpln2hw0000gn/T/tmp.1F30heNUYl
WOW
----