【问题标题】:Create a shell script to execute multiple commands [duplicate]创建一个shell脚本来执行多个命令[重复]
【发布时间】:2018-09-19 02:51:55
【问题描述】:

这就是我想要做的......我想编写一个脚本,它将文件夹中的所有文件作为command2的输入发送。

我知道管道用于将一个命令的输出发送到另一个命令,但就我而言,当我这样做时

ls | command

它的作用是将 ls 的输出(即文件夹中的所有文件)作为单个输入发送。相反,我希望将单个文件作为参数一个一个地发送给 command2。

谁能帮帮我,我确实搜索了很多,但没有找到太多。

【问题讨论】:

  • find 或目录中的文件循环可能会更好地完成您尝试做的任何事情。这是ls中的generally considered a bad idea to parse the output
  • 在这种特殊情况下,当然,简单的command * 更好,并避免parsing ls output
  • @Sonamor :我理解的问题是 OP 想要调用 command 多次,每个输入文件一次。
  • @ChintanMehta:echo *|xargs -n 1 your_command 怎么样?请注意,在这种情况下,your_command 不会通过标准输入获取(单个)文件名,而是作为命令行参数。

标签: bash shell terminal sh executable


【解决方案1】:

使用以下任何一种方法,但我推荐第一种,因为没有创建子shell

for files in *;do
   if [[ -f "$files" ]];then
       echo "$files"
   fi
done


while read line;do
   if [[ -f "$line" ]];then
       echo "$line"
   fi
done < <(ls)

【讨论】:

  • test -f 有助于避免目录
  • 我想用 gpg 命令加密这些文件。现在你的第一个脚本运行良好,但是当我用 gpg -e -r "Recipient" 替换第三行时,我得到以下输出 usage: gpg [options] --encrypt [filename ] 而不是运行该命令
  • 错误不是脚本,错误是你的gpg命令,“收件人”是什么?
  • recipient 是密钥所在的用户。顺便说一句,我在没有 shellscript 的情况下使用了相同的 gpg 命令,它完美地工作,所以我不认为它是 @0.sh
  • 兄弟将文件名传递给 gpg gpg -e -r "Recipient" "$files"
【解决方案2】:

您可以使用find,例如:

$ cat do.sh
#!/usr/bin/env sh

printf "arg: %s\n" "$1"
$ touch {1..10}
$ find . -type f -exec ./do.sh {} \;
arg: ./6
arg: ./10
arg: ./5
arg: ./3
arg: ./9
arg: ./2
arg: ./8
arg: ./do.sh
arg: ./1
arg: ./4
arg: ./7

【讨论】:

  • 我不明白你在这里做什么。是的,我尝试在我的文件夹中运行这个文件。它没有工作
  • 什么文件?什么不起作用?
  • 没关系,我用了另一种方法,它奏效了。请查看答案。
【解决方案3】:

您可以使用xargs

$ find . -maxdepth 1 -print0 | xargs -0 -l command

这将打印当前目录中的所有文件,用空字符分隔名称,然后xargs 一次获取一个 (-l) 并使用每个文件作为参数调用 command

【讨论】:

    猜你喜欢
    • 2012-07-02
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多