gpt4 book ai didi

bash - 将命令作为参数传递给 bash 脚本

转载 作者:行者123 更新时间:2023-11-29 09:15:21 25 4
gpt4 key购买 nike

如何将命令作为参数传递给 bash 脚本?在以下脚本中,我尝试这样做,但没有成功!

#! /bin/sh

if [ $# -ne 2 ]
then
echo "Usage: $0 <dir> <command to execute>"
exit 1;
fi;

while read line
do
$($2) $line
done < $(ls $1);

echo "All Done"

此脚本的示例用法是

./myscript thisDir echo

执行上面的调用应该回显 thisDir 目录中所有文件的名称。

最佳答案

第一个大问题:$($2) $line执行 $2本身作为一个命令,然后尝试将其输出(如果有的话)作为另一个命令运行 $line作为它的论据。你只想要 $2 $line .

第二大问题:while read ... done < $(ls $1)不从文件名列表中读取,它尝试读取由 ls 的输出指定的文件的内容——这将以多种方式失败,具体取决于具体情况。进程替换 ( while read ... done < <(ls $1) ) 或多或少会做你想要的,但它是 bash 专用的功能(即你必须#!/bin/bash 启动脚本,而不是 #!/bin/sh )。无论如何,parse ls 是个坏主意,您应该几乎总是只使用 shell glob ( * )。

该脚本还有一些其他潜在的问题,例如文件名中的空格(使用 $line,周围没有双引号等),以及奇怪的文体怪异(您不需要 ; 在一行的末尾壳)。这是我重写的尝试:

#! /bin/sh

if [ $# -ne 2 ]; then
echo "Usage: $0 <dir> <command to execute>"
exit 1
fi

for file in "$1"/*; do
$2 "$file"
done

echo "All done"

请注意,我没有在 $2 周围加上双引号.这允许您指定多字命令(例如 ./myscript thisDir "cat -v" 将被解释为运行带有 cat 选项的 -v 命令,而不是尝试运行名为 "cat -v" 的命令)。将第一个参数之后的所有参数作为命令及其参数实际上会更灵活一些,允许您执行例如./myscript thisDir cat -v , ./myscript thisDir grep -m1 "pattern with spaces"等:

#! /bin/sh

if [ $# -lt 2 ]; then
echo "Usage: $0 <dir> <command to execute> [command options]"
exit 1
fi

dir="$1"
shift

for file in "$dir"/*; do
"$@" "$file"
done

echo "All done"

关于bash - 将命令作为参数传递给 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15749618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com