gpt4 book ai didi

bash 脚本 : build a command then execute

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

我正在尝试创建一个函数,该函数基本上接受诸如 f hello there my friend 之类的参数,并使用 find 搜索目录以查找所有出现的任何这些字符串,所以它会是 find | grep '你好\|那里\|我的\| friend '。我是 shell 脚本的新手,但我的代码如下:

function f { 
cmd="find | grep '"
for var in "$@"
do
cmd="$cmd$var\\|"
done
cmd="${cmd%\\|}'"
echo "$cmd"
$cmd
}

当我执行命令时,我得到这个:

# f hello there my friend
find | grep 'hello\|there\|my\|friend'
find: `|': No such file or directory
find: `grep': No such file or directory
find: `\'hello\\|there\\|my\\|friend\'': No such file or directory

为什么它不起作用,我怎样才能让它起作用?我想这与未转换为命令的字符串有关,但我不太了解 shell 脚本的工作原理。

最佳答案

看起来你的命令语法是正确的。要从 bash 中的脚本运行命令并捕获结果,请使用以下语法:

cmd_string="ls"
result=$($cmd_string)
echo $result

关于bash 脚本 : build a command then execute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32787320/

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