gpt4 book ai didi

linux - 需要使用 shell 脚本验证在命令行上作为参数传递的每个文件是否存在

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:13:22 24 4
gpt4 key购买 nike

我想创建一个 shell 脚本来读取命令行参数,然后连接这些文件的内容并将其打印到标准输出。我需要验证传递给命令行的文件是否存在。

到目前为止,我已经编写了一些代码,但脚本仅在仅传递一个命令行参数时才有效。如果传递多个参数,我尝试过的错误检查将不起作用。

#!/bin/bash

if [ $# -eq 0 ]; then
echo -e "Usage: concat FILE ... \nDescription: Concatenates FILE(s)
to standard output separating them with divider -----."
exit 1
fi

for var in "$@"
do
if [[ ! -e $@ ]]; then
echo "One or more files does not exist"
exit 1
fi
done


for var in "$@"
do
if [ -f $var ]; then
cat $var
echo "-----"
exit 0
fi
done

我需要修复对此的错误检查,以便检查每个命令行参数是否为现有文件。如果文件不存在,则必须将错误打印到 stderr,并且不应将任何内容打印到 stdout。

最佳答案

第 11 行有一个错误:

if [[ ! -e $@ ]]; then

你确实需要像这样使用 $var 检查给定的文件:

if [[ ! -e "$var" ]]; then

并且您在第 23 行过早退出 - 您将始终只打印一个单个文件。并记住始终引用您的变量,因为否则您的脚本将无法在名称中包含空格的文件上正确运行,例如:

$ echo a line > 'a b'
$ cat 'a b'
a line
$ ./concat.sh 'a b'
cat: a: No such file or directory
cat: b: No such file or directory
-----.

你说:

if a file does not exist, the error must be printed to stderr and nothing should be printed to stdout.

如果你想,你现在没有向 stderr 打印任何东西你应该这样做:

echo ... >&2

你应该使用 printf 而不是 echo 因为它更便携即使您使用的是 Bash

总而言之,您的脚本可能如下所示:

#!/bin/bash

if [ $# -eq 0 ]; then
printf "Usage: concat FILE ... \nDescription: Concatenates FILE(s) to standard output separating them with divider -----.\n" >&2
exit 1
fi

for var in "$@"
do
if [[ ! -e "$var" ]]; then
printf "One or more files does not exist\n" >&2
exit 1
fi
done

for var in "$@"
do
if [ -f "$var" ]; then
cat "$var"
printf -- "-----\n"
fi
done

exit 0

关于linux - 需要使用 shell 脚本验证在命令行上作为参数传递的每个文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939179/

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