Using associative array from bash4+.
#!/usr/bin/env bash
declare -A paths ##: declare associative array
for f; do ##: Loop through all the give arguments
[[ -z "$f" ]] && continue ##: If the given argument is two single '' quotes it breaks the array.
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"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//\'/}";;"$i";;
*)
printf ' { "is_available": %s, "path": "%s" },\n' "${paths[$i]}" "${i//\'/}";;"$i";;
esac
((counter++))
done
printf ']\n'
- See
help testfor checking permissions. Like what the other posted answer suggested. Instead oftouchandrmIt could be something like:
for f; do
[[ -z "$f" ]] && continue
if [[ -d "$f" && -w "$f" && -x "$f" ]]; then
avail_path1=1
else
avail_path1=0
fi
paths["'$f'"]="$avail_path1"paths["$f"]="$avail_path1"
done
- Checkout jq from this forum also for processing/working with
jsondata structure using the shell.