简体   繁体   English

无法在bash脚本中执行shell命令

[英]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 错误: ./securityanalysis.sh: line 7: find: command not found

find is located under /bin, which is included in my PATH. 查找位于/ bin下,该文件包含在我的PATH中。 I also put the directory this script was being executed in into the PATH but it didn't make a difference. 我还将将要执行此脚本的目录放在PATH中,但没有任何区别。

Replacing the echo.. line with eval $RSYSLOGCLIENTS also gave me the same error. eval $RSYSLOGCLIENTS替换echo..行也给了我同样的错误。

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. 注意:我认为这是非常糟糕的做法,但是此脚本位于root的主目录中。 Could this have something to do with it? 这可能与它有关吗?

find is located under /bin, which is included in my PATH 查找位于/ bin下,该文件包含在我的PATH中

No, it isn't. 不,不是。 Your PATH is redefined in line 3 of the script to be: 您的PATH在脚本的第3行中重新定义为:

PATH=/var/log

Observe that the find command works before but not after PATH is reassigned: 观察到find命令重新分配PATH 之前有效重新分配PATH 之后无效:

$ 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. 这里的一般教训是,在为脚本定义shell变量时, 切勿使用全部大写字母。 The shell uses all caps for its important variables, like PATH. 外壳程序将所有大写形式用作其重要变量,例如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 : 例如,为path变量分配了一个值,它不会影响shell查找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. 在shell中,变量名称区分大小写,因此PATHpath是独立的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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