bash 脚本虽然需要但不保存输出文件 [英] bash script do not save output file although required

查看:88
本文介绍了bash 脚本虽然需要但不保存输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写以下简单的 .sh 脚本,将 output.txt 保存到工作目录:

Wrote the following simple .sh script which should save output.txt to the working directory:

valuesfile="values.*"

for f in ./
do
 if [[ $f = $valuesfile ]]
 then
     yq d $f 'resources.' >./output.txt
 fi
done

当我执行脚本时,没有创建文件.所有文件夹都具有 rwx 权限,包括脚本本身.

When I execute the script, no file is created. all folders have rwx permissions including the script itself.

推荐答案

您的 glob 永远不会扩展:[[ ... ]] 中未加引号的参数扩展不会进行路径名扩展.您的循环也不正确:for f in ./ 只迭代一次,将 f 设置为字符串 ./,而不是对文件进行迭代在电流直接.最后,如果多个匹配的文件,你会反复覆盖output.txt的前面的内容;改用 >>.

Your glob is never expanded: unquoted parameter expansions inside [[ ... ]] do not undergo pathname expansions. Your loop is also incorrect: for f in ./ iterates exactly once, setting f to the string ./, rather than iteration over the files in the current directly. And finally, if there are more than one matching file, you'll repeatedly overwrite the previous contents of output.txt; use >> instead.

可以试试

valuesfile="values.*"

for f in ./$valuesfile
do
     yq d "$f" 'resources.' >> ./output.txt
done

尽管如果您的任何文件有空格,这会导致问题,因为 $valuesfile 的扩展会经历分词和路径名扩展.

though this will cause problems if any of your files have whitespace, as the expansion of $valuesfile undergoes word-splitting as well as pathname expansion.

改用数组:

valuesfile=( values.* )

for f in "${valuesfile[@]}"
do
  yq d "$f" 'resources.' >> output.txt
done

或者,只需省去额外的变量,直接将模式放入循环中:

Or, just dispense with the extra variable and put the pattern in the loop directly:

for f in values.*
do
  yq d "$f" 'resources.' >> output.txt
done

这篇关于bash 脚本虽然需要但不保存输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆