简体   繁体   English

Bash命令可在cmd行上运行,但不能在脚本中运行

[英]Bash commands work on cmd line but not in script

I have a set of piped commands that work on the command line, but do not produce output when run within a script. 我有一组在命令行上工作的管道命令,但是在脚本中运行时不会产生输出。

The command is: 该命令是:

STRNG=$( ip mroute show | tr -d "()," | awk ' {print "/usr/sbin/smcroute -a eth3", $1, $2, "vtun0 vtun1"}' ); echo "$STRNG"`

And the output is: 输出为:

/usr/sbin/smcroute -a eth3 192.0.1.19 224.1.1.1 vtun0 vtun1
/usr/sbin/smcroute -a eth3 192.0.1.18 224.1.1.1 vtun0 vtun1

However, if I put the very same command line into a script, I get no output from the echo "$STRNG" command. 但是,如果将相同的命令行放入脚本中,则echo "$STRNG"命令不会得到任何输出。

What I'm trying to do is execute every line in $STRNG as a command, but for whatever reason it appears $STRNG doesn't contain any text in the script, whereas $STRNG does contain text when run from the command line. 我想做的是将$STRNG中的每一行作为命令执行,但是无论出于什么原因, $STRNG似乎都没有在脚本中包含任何文本,而$STRNG运行时$STRNG确实包含了文本。 I'm sure this is due to limited bash understanding. 我敢肯定这是由于对bash的了解有限。

Could someone help me with this? 有人可以帮我吗?

Is one of the commands in your pipeline an alias? 管道中的命令之一是别名吗? If so, you'll need to do 如果是这样,您需要做

shopt -s expand_aliases

in order for bash to expand it in your script....generally this is only enabled by default in interactive shells. 为了让bash在脚本中扩展它。...通常,默认情况下,仅在交互式shell中启用此功能。

As Scharron said, run it with sh -x. 正如Scharron所说,用sh -x运行它。 Other than that: 除此之外:

  • Is ip in the script's $PATH? ip是否在脚本的$ PATH中?
  • Do you use a different locale ($LANG or $LC_???) in your script, so the output of commands gets translated to another language? 您是否在脚本中使用了不同的语言环境($ LANG或$ LC _ ???),因此命令的输出被翻译成另一种语言?

I would break it into smaller pieces to debug it. 我将它分成较小的部分进行调试。

Ie, first have a script that does this: 即,首先具有执行此操作的脚本:

ip mroute show

Run the script. 运行脚本。 If that produces output then tack on more. 如果那产生了产出,那么就增加更多。

ip mroute show | tr -d "(),"

ip mroute show | tr -d "()," | awk ' {print $0 } '

ip mroute show | tr -d "()," | awk ' {print "/usr/sbin/smcroute -a eth3", $1, $2, "vtun0 vtun1"}'

I want to thank everyone for their help - these will be good things to look for in the future. 我要感谢大家的帮助-这些将是将来需要的好东西。

The first line of my script was different from the command line: 我的脚本的第一行与命令行不同:

/usr/sbin/smcroute -k; /usr/sbin/smcroute -d

It turns out that I was getting different results from ip mroute show each time, possibly because multicast packets had not yet arrived on the interface. 事实证明,每次从ip mroute show获得的结果都是不同的,可能是因为多播数据包尚未到达接口。 Adding a sleep 1 after the first line and before the ip mroute show chain fixed it. 在第一行之后和ip mroute show链之前添加一个sleep 1修复它。

I wouldn't have found it if not for Fosco's help, and I also didn't know how to debug or expand aliases before. 如果没有Fosco的帮助,我将找不到它,而且我之前也不知道如何调试或扩展别名。

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

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