如何在ldapsearch命令中同时使用变量与NOT过滤器?
You've hit a common shell quoting conflict—here are a couple of reliable ways to get both variable substitution (like $month_8 and $month_3) and the NOT filter !(nEApps=*) working in the same ldapsearch command:
Method 1: Quote Splicing (Most Reliable)
Split your filter into segments: wrap parts that need variable expansion in double quotes, and wrap parts containing the ! operator (or other shell-special characters) in single quotes. The shell automatically concatenates adjacent quoted strings into one unified filter:
ldapsearch -h 1.0.24.24 -p 389 -x -t -LLL -S cn -D cn=user,ou=resources,o=otherresource,c=xx -w server101 -b "ou=Non- Staff,ou=people,o=test,c=us" '(&(objectClass=inetOrgPerson)(createTimestamp<='"$month_8"')(!(nEApps=*))(nEDHHSNFAccNbr=\00)(nECreatedBy=cioSelfRegistered)(loginTime<='"$month_3"'))' dn
How this works:
"$month_8"and"$month_3"are wrapped in double quotes, so the shell replaces them with their actual values before passing the filter toldapsearch.- The rest of the filter (including
!(nEApps=*)) is in single quotes, which tells the shell to treat every character literally—no unwanted history expansion for!, no accidental variable substitution where you don't want it. - The shell merges all quoted segments into a single, properly formatted filter string automatically.
Method 2: Escape the Exclamation Mark in Double Quotes
If you prefer using a single double-quoted filter, escape the ! with a backslash (\!) to prevent the shell from interpreting it as a history command shortcut. Note this works best in bash; behavior may vary in other shells like zsh:
# Temporarily disable history expansion (bash-specific, optional but recommended) set +o histexpand ldapsearch -h 1.0.24.24 -p 389 -x -t -LLL -S cn -D cn=user,ou=resources,o=otherresource,c=xx -w server101 -b "ou=Non- Staff,ou=people,o=test,c=us" "(&(objectClass=inetOrgPerson)(createTimestamp<=$month_8)(\!(nEApps=*))(nEDHHSNFAccNbr=\00)(nECreatedBy=cioSelfRegistered)(loginTime<=$month_3))" dn # Re-enable history expansion if needed set -o histexpand
Critical Note:
Ensure your filter uses a literal & instead of &—& is HTML-encoded, and ldapsearch expects the actual ampersand character for valid LDAP filter syntax. If you copied this from a web page, replace & with & to avoid filter parsing errors.
内容的提问来源于stack exchange,提问作者paxtuik

