I would like a bash shell script (for my Debian 12 system) which accepts multiple paths as arguments, and then checks if a file can be successfully created in each one. Then the result should be put into json format.
The command to run should be:
./checkavailable.sh /the/first/path /the/second/path
(where there could be any number of input paths given, but at least one)
and I would like the output to be in the following format:
[
{ "is_available": 0, "path": "/the/first/path/" },
{ "is_available": 1, "path": "/the/second/path/" }
]
Currently, I managed to achieve this with the following script:
#!/bin/bash
# Check if first path is available
if touch $1/checkalivefile ; then
avail_path1=1
rm $1/checkalivefile
else
avail_path1=0
fi
# Check if second path is available
if touch $2/checkalivefile ; then
avail_path2=1
$2/checkalivefile
else
avail_path2=0
fi
echo "["
printf " { "is_available": "$avail_path1", "path": "$1" } "
printf ",n"
printf " { "is_available": "$avail_path2", "path": "$2" } "
echo
echo "]"
but it’s obviously a bit primitive and is hardcoded to work with x2 arguments only, and doesn’t scale to additional arguments.
I could try to add a loop now. However, I came across this script, which seems to do something similar (to get disk usage in this case) but using awk instead of a loop:
#!/bin/bash
echo "["
du -s -B1 "$@" | awk '{if (NR!=1) {printf ",n"};printf " { "dir_size_bytes": "$1", "path": ""$2"" }";}'
echo
echo "]"
Can someone show how this approach using “awk” could be applied to my case? I am very new to bash scripts, so hope to learn something.