简体   繁体   中英

Cannot execute shell commands in bash script

 #!/bin/bash
#general security monitoring
PATH=/var/log
echo "The IP addresses of users with more than 2 failed login attempts are:"
IPFAILEDLOGINS=$(grep "Failed password" /var/log/secure | cut -d: -f4 | awk '{print $6}' | uniq -c | awk '{if ($1>=2) print $2}')
echo "$IPFAILEDLOGINS"

RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
echo "The current rsyslog clients are: $RSYSLOGCLIENTS"

error: ./securityanalysis.sh: line 7: find: command not found

find is located under /bin, which is included in my PATH. I also put the directory this script was being executed in into the PATH but it didn't make a difference.

Replacing the echo.. line with eval $RSYSLOGCLIENTS also gave me the same error.

Can someone please explain what is happening?

Note: I assume this is extremely bad practice, but this script is located in the home directory of root. Could this have something to do with it?

find is located under /bin, which is included in my PATH

No, it isn't. Your PATH is redefined in line 3 of the script to be:

PATH=/var/log

Observe that the find command works before but not after PATH is reassigned:

$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
$ PATH=/var/log
$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
bash: find: command not found

The general lesson here is, when defining shell variables for your script, never use all capitals. The shell uses all caps for its important variables, like PATH. You don't want to overwrite them. Use lower or, at least, mixed case for your internal script variables.

For example, the path variable is assigned a value and it does not affect the ability of the shell to find find :

$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
$ path=/var/log
$ RSYSLOGCLIENTS=$(find /var/log -type d -regextype posix-egrep -regex ".*/([0-9]+\.){3}[0-9]+")
$

In shell, variable names are case-sensitive and, therefore, PATH and path are separate and independent variables.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM