for d in */ ; do
cd $d
NUM = $(echo ${PWD##*/} | grep -q "*abc*");
if [[ "$NUM" -ne "0" ]]; then
pwd
fi
cd ..
done
Here I'm trying to match a folder name to some substring 'abc' in the name of the folder and check if the output of the grep is not 0. But it gives me an error which reads that NUM: command not found
An error was addressed in comments. NUM = $(echo ${PWD##*/} | grep -q "*abc*");
should be NUM=$(echo ${PWD##*/} | grep -q "*abc*");
.
To clarify, the core problem would be to be able to match current directory name to a pattern.
You can probably simply the code to just
if grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
echo "$PWD"
# Your rest of the code goes here
fi
You can use the exit code of the grep
directly in a if-conditional without using a temporary variable here ( $NUM
here). The condition will pass if grep
was able to find a match. The here-string <<<
, will pass the input to grep
similar to echo
with a pipeline. The part 2>/dev/null
is to just suppress any errors ( stderr - file descriptor 2
) if grep
throws!
As an additional requirement asked by OP, to negate the conditional check just do
if ! grep -q "*abc*" <<< "${PWD##*/}" 2>/dev/null; then
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.