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

时间:2015-06-08 02:54:12

标签: bash shell

我在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

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

结果是

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

关于这里出了什么问题的任何想法?

1 个答案:

答案 0 :(得分:4)

你不想要后面的引号;你想要双引号。

#!/bin/sh

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

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

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

相关问题