Hello I am trying run a script that checks for a list of directories. then output the status of each directory into new fields or an array.
Thanks in Advance!
#!/bin/sh
dir00="/tmp/Apple"
dir01="/tmp/Banana"
dir02="/tmp/Carrot"
dirList=("$dir00" "$dir01" "$dir02")
dirName00="Apple"
dirName01="Banana"
dirName02="Carrot"
dirNames=("$dirName00" "$dirName01" "$dirName02")
for i in "${dirList[#]}"; do
if [ -d "$i" ]; then
echo "Directory Not Missing:$i"
# write to a new arrary (dirStatus) either 0 or 1
else
echo "Directory Missing: $i"
# write to a new arrary (dirStatus) either 0 or 1
fi
done
# then I can do the following:
echo dirName[0] dirStatus[0]
# expected output:
echo Apple 1 # if Apple is missing
The test [ -d path ] sets the exit status $?. Instead of using that status implicitly in an if statement you can append it explicitly to an array.
An exit status of 0 means "yes" and everything else (usually 1) means "no".
Since you didn't specify how exactly you'd like to store the results, here are two alternatives that could be useful:
Two Regular Arrays
#! /bin/bash
path=(tmp/DIR_0{0..2})
isDir=()
for p in "${path[#]}"; do
[ -d "$p" ]
isDir+=($?)
done
declare -p path isDir
One Associative Array
#! /bin/bash
declare -A isDir
for p in tmp/DIR_0{0..2}; do
[ -d "$p" ]
isDir["$p"]=$?
done
declare -p isDir
Related
I have many functions which return an array.
function myfunction() {
local -i status=0
local -a statusmsg=()
... do ....
statusmsg=($(do something ...))
if [[ ${status} -eq 0 ]]; then
....
return 0
else
for (( statusmsgline=0; statusmsgline<${#statusmsg[#]}; statusmsgline++ ))
do
printf "%s\n" "${statusmsg[${statusmsgline}]}"
done
return 1
fi
}
in the script I use mapfile as suggested here How to return an array in bash without using globals?
mapfile -t returnmsg <<< "$(myfunction "${param1}" "${param2}" "${paramX}" ...)"
if [ $? -eq 1 ]] ; then
... do something
fi
Using mapfile the array is well returned as it was generated but return code is ever and ever 0 (mapfile exit code) and can't retrieve the status code returned by the function.
I tried to use shopt -s lastpipe and shopt -so pipefail but without any success.
Is there any way to retrieve the array from function and the exit code at the same time ?
Kind Regards
Read the whole array into one string variable, evaluate the status, then pass the string variable on to mapfile.
output=$(myfunction ...)
if [ $? -eq 1 ] ; then
# do something
fi
mapfile -t array <<< "$output"
Warning: if the output of myfunction is very long the script may become slow or may even run out of memory. In this case you should write to a file or file descriptor instead.
The $() removes trailing empty lines. If those are important to you, then you can write either the exit status or the output to a file. Here we write the exit status at it is always short. Writing a long output to the file system and reading it afterwards would have more overhead.
mapfile -t array <(myfunction ...; echo $? > /tmp/status)
if [ "$(< /tmp/status; rm -f /tmp/status)" -eq 1 ] ; then
# do something
fi
There's also a way to work without these temporary variables/files by leveraging bash's options:
shopt -s lastpipe
myfunction ... | mapfile -t array
if [ "${PIPESTATUS[0]}" -eq 1 ] ; then
# do something
fi
# you may want to do `shopt -u lastpipe` here
I have a file like this below:
-bash-4.2$ cat a1.txt
0 10.95.187.87 5444 up 0.333333 primary 0 false 0
1 10.95.187.88 5444 up 0.333333 standby 1 true 0
2 10.95.187.89 5444 up 0.333333 standby 0 false 0
I want to fetch the data from the above file into a 2D array.
Can you please help me with a suitable way to put into an array.
Also post putting we need put a condition to check whether the value in the 4th column is UP or DOWN. If it's UP then OK, if its down then below command needs to be executed.
-bash-4.2$ pcp_attach_node -w -U pcpuser -h localhost -p 9898 0
(The value at the end is getting fetched from the 1st column.
You could try something like that:
while read -r line; do
declare -a array=( $line ) # use IFS
echo "${array[0]}"
echo "${array[1]}" # and so on
if [[ "$array[3]" ]]; then
echo execute command...
fi
done < a1.txt
Or:
while read -r -a array; do
if [[ "$array[3]" ]]; then
echo execute command...
fi
done < a1.txt
This works only if field are space separated (any kind of space).
You could probably mix that with regexp if you need more precise control of the format.
Firstly, I don't think you can have 2D arrays in bash. But you can however store lines into a 1-D array.
Here is a script ,parse1a.sh, to demonstrate emulation of 2D arrays for the type of data you included:
#!/bin/bash
function get_element () {
line=${ARRAY[$1]}
echo $line | awk "{print \$$(($2+1))}" #+1 since awk is one-based
}
function set_element () {
line=${ARRAY[$1]}
declare -a SUBARRAY=($line)
SUBARRAY[$(($2))]=$3
ARRAY[$1]="${SUBARRAY[#]}"
}
ARRAY=()
while IFS='' read -r line || [[ -n "$line" ]]; do
#echo $line
ARRAY+=("$line")
done < "$1"
echo "Full array contents printout:"
printf "%s\n" "${ARRAY[#]}" # Full array contents printout.
for line in "${ARRAY[#]}"; do
#echo $line
if [ "$(echo $line | awk '{print $4}')" == "down" ]; then
echo "Replace this with what to do for down"
else
echo "...and any action for up - if required"
fi
done
echo "Element access of [2,3]:"
echo "get_element 2 3 : "
get_element 2 3
echo "set_element 2 3 left: "
set_element 2 3 left
echo "get_element 2 3 : "
get_element 2 3
echo "Full array contents printout:"
printf "%s\n" "${ARRAY[#]}" # Full array contents printout.
It can be executed by:
./parsea1 a1.txt
Hope this is close to what you are looking for. Note that this code will loose all indenting spaces during manipulation, but a formatted update of the lines could solve that.
I am currently writing a script which should make it more easy for me to build some RPMs using mock.
The plan is to make it possible to add values for the mock (and therefor rpmbuild) --define parameter.
The error I get if I add such a define value is
ERROR: Bad option for '--define' ("dist). Use --define 'macro expr'
When I execute the script with as simple as ./test.sh --define "dist .el7" the "debug" output is as follows:
/usr/bin/mock --init -r epel-7-x86_64 --define "dist .el7"
If I copy this and execute it in the shell directly it is actually working. Does anybody have an idea why this is the case?
My script can be cut down to the following:
#!/bin/sh
set -e
set -u
set -o pipefail
C_MOCK="/usr/bin/mock"
MOCK_DEFINES=()
_add_mock_define() {
#_check_parameters_count_strict 1 ${#}
local MOCK_DEFINE="${1}"
MOCK_DEFINES+=("${MOCK_DEFINE}")
}
_print_mock_defines_parameter() {
if [ ${#MOCK_DEFINES[#]} -eq 0 ]; then
return 0
fi
printf -- "--define \"%s\" " "${MOCK_DEFINES[#]}"
}
_mock_init() {
local MOCK_DEFINES_STRING="$(_print_mock_defines_parameter)"
local MOCK_PARAMS="--init"
MOCK_PARAMS="${MOCK_PARAMS} -r epel-7-x86_64"
[ ! "${#MOCK_DEFINES_STRING}" -eq 0 ] && MOCK_PARAMS="${MOCK_PARAMS} ${MOCK_DEFINES_STRING}"
echo "${C_MOCK} ${MOCK_PARAMS}"
${C_MOCK} ${MOCK_PARAMS}
local RC=${?}
if [ ${RC} -ne 0 ]; then
_exit_error "Error while mock initializing ..." ${RC}
fi
}
while (( ${#} )); do
case "${1}" in
-s|--define)
shift 1
_add_mock_define "${1}"
;;
esac
shift 1
done
_mock_init
exit 0
After asking this question a coworker I was pointed to this question on unix stackexchange: Unix Stackexchange question
The way this problem was solved can be broken down to following lines:
DEFINES=()
DEFINES+=(--define "dist .el7")
DEFINES+=(--define "foo bar")
/usr/bin/mock --init -r epel-7-x86_64 "${DEFINES[#]}"
Just in case somebody else stumbles upon this kind of issue.
This is my bash script
I have 4 set of arrays and in each set i am ssh-ing to each server to find if /data filesystem exists. If it matches it should skip the array and move to next arry. I am unable to do with break as it exits the entire script. Any ideas ?
declare -a siteA=("server01" "server02" "server03")
declare -a siteB=("server04" "server05" "server06")
declare -a siteB=("server07" "server08" "server09")
declare -a siteB=("server10" "server11" "server12")
cmd=$(df -h|grep /data)
for i in "${siteA[#]}" "${siteB[#]}" "${siteC[#]}" "${siteD[#]}"; do
ping -c 2 ${i} > /dev/null 2>&1
if [[ $? -eq 0 ]] ; then
X=$(ssh root#${i} -q $cmd1 2>&1)
if [[ $Z == "/data" ]]; then
echo "$i: has /data"
fi
fi
done
To continue to the next array when you find a match, simply wrap your loop contents in a parameter loop within a function and call that for each site:
has_running_host() {
for host
do
[code which `break`s on a match]
done
}
has_running_host "${siteA[#]}"
has_running_host "${siteB[#]}"
[…]
Well although not very nice, you could use two loops in combination with eval:
for j in siteA siteB siteC siteD; do
for i in $(eval echo \${${j}[#]}); do
echo $i
done
done
this would then allow you to use break in the inner loop and therefore jumping to the next array
That worked for me, also getting output from a remote ssh is a challenge
I am confused in bash by this expression:
$ var="" # empty var
$ test -f $var; echo $? # test if such file exists
0 # and this file exists, amazing!
$ test -f ""; echo $? # let's try doing it without var
1 # and all ok
I can't understand such bash behaviour, maybe anybody can explain?
It's because the empty expansion of $var is removed before test sees it. You are actually running test -f and thus there's only one arg to test, namely -f. According to POSIX, a single arg like -f is true because it is not empty.
From POSIX test(1) specification:
1 argument:
Exit true (0) if `$1` is not null; otherwise, exit false.
There's never a test for a file with an empty file name. Now with an explicit test -f "" there are two args and -f is recognized as the operator for "test existence of path argument".
When var is empty, $var will behave differently when if quoted or not.
test -f $var # <=> test -f ==> $? is 0
test -f "$var" # <=> test -f "" ==> $? is 1
So this example tells us: we should quote the $var.