A function is internal to the shell that defines it. If you run another program, that other program won't see the function, even if it also happens to be a shell.
(Functions are accessible in subshells, i.e. when a copy of the running shell is made to run something in parentheses (…)
or for a command substitution $(…)
etc. But they are not accessible in separate programs, e.g. when you run sh -c …
.)
Define the function in the script that uses it:
#!/bin/sh
awk -F: '$4 == 0' /etc/passwd | cut -d: f1 | xargs -n1 -i bash -c '
compare() {
if [ $1 != root ]; then
echo "Fail" >> CAT1.txt
fi
}
compare "$@"' _
(I assume this is a toy example, this could all be done in a single, simple awk script.)
Alternatively, you can use a bash feature which allows functions to be exported through the environment to a child instance of bash. This is a bash-specific feature, so the parent script would have to run bash, not sh.
#!/bin/bash
compare() {
if [ $1 != root ]; then
echo "Fail" >> CAT1.txt
fi
}
export -f compare
awk -F: '$4 == 0' /etc/passwd | cut -d: f1 | xargs -n1 -i bash -c 'compare "$@"' _
export -f compare
after the function. Also prefer#!/bin/bash
when using bash-isms, as/bin/sh
may not be the same as bash. – meuh Jul 7 '15 at 8:27#!/bin/bash
as the start line. – meuh Jul 7 '15 at 9:13