Skip to main content
8 of 9
Add an alternative to touch and rm.
Jetchisel
  • 1.6k
  • 9
  • 12

Using associative array from bash4+.

#!/usr/bin/env bash

declare -A paths ##: declare associative array

for f; do  ##: Loop through all the give arguments
  if create_file=$(touch "$f"/checkalivefile 2>&1); then ##: command substitution in a variable has a useful exit status
    avail_path1=1
    rm -rf "$create_file"
  else
    avail_path1=0
  fi
  paths["'$f'"]="$avail_path1"
done

counter=1
total="${#paths[@]}"

##: If no argument is given exit the script
((total)) || {
  printf >&2 'No directory given!\n'
  exit 1
}

printf '[\n'
for i in "${!paths[@]}"; do
  case $counter in
    "$total") ##: Do not add a trailing `,` if it is the last element.
       printf '  { "is_available": %s, "path": "%s" }\n' "${paths[$i]}" "${i//\'/}";;
    *)
     printf '  { "is_available": %s, "path": "%s" },\n' "${paths[$i]}" "${i//\'/}";;
  esac
((counter++))
done
printf ']\n'

  • See help test for checking permissions. Like what the other posted answer suggested. Instead of touch and rm It could be something like:
for f; do
  if [[ -d "$f" && -w "$f" && -x "$f" ]]; then
    avail_path1=1
  else
    avail_path1=0
  fi
  paths["'$f'"]="$avail_path1"
done
  • Checkout jq from this forum also for processing/working with json data structure using the shell.
Jetchisel
  • 1.6k
  • 9
  • 12