繁体   English   中英

在bash shell脚本中使用反引号执行命令

[英]Execute command with backquote in bash shell script

我用bash编写了一个小shell脚本,使我可以在子目录中执行命令。 这是脚本

bat.sh:

#!/bin/sh

for d in */; do
  echo "Executing \"$@\" in $d"
  cd $d
  `$@`
  cd ..
done

随着我下面的目录结构

/home/user
--a/
----x.txt
----y.txt
--b/
----u.txt
----v.txt

我希望以下命令在主目录bat.sh ls中执行时列出目录a和b的内容

结果是

Executing "ls" in a/
/home/user/bin/bat.sh: line 6: x.txt: command not found
Executing "ls" in b/
/home/user/bin/bat.sh: line 6: u.txt: command not found

对这里出什么问题有任何想法吗?

您不希望使用反引号; 您想要双引号。

#!/bin/sh

for d in */
do
    echo "Executing \"$*\" in $d"
    (cd "$d" && "$@")
done

您正在尝试执行传递的命令的输出,而您只想执行命令。

使用显式子shell( ( … )表示法)可以避免跳转到其他目录的符号链接的某些问题。 在我看来(也许是过时的),这是为了执行命令而切换目录的一种更安全的方法。

暂无
暂无

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

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