我有这个代码:
for file in "$@"*png; do
echo "$file"
done
Run Code Online (Sandbox Code Playgroud)
仅当您提供以 /like 结尾的路径时才有效/root/
。
在这种情况下,在不破坏脚本的情况下将 / 添加到路径输入的正确方法是什么?
如果你在最后给出一个没有 / 的路径输入,它只是这样做:
File: /root*png
Run Code Online (Sandbox Code Playgroud)
如果我将其修改为for file in "$@"/*png; do
并输入/root/test/
它可以工作但结果看起来很难看:
File: /root/test//sample2.png
Run Code Online (Sandbox Code Playgroud)
ilkkachu 指出了我回答中的一个主要缺陷并在他的回答中更正了,所以请给他应有的荣誉。不过,我想出了另一个解决方案:
#!/bin/bash
for dir in "$@"; do
find "$dir" -type f -name '*png' -exec readlink -f {} \;
done
Run Code Online (Sandbox Code Playgroud)
示例:
$ ll
total 6
-rwxr-xr-x 1 root root 104 Jan 7 14:03 script.sh*
drwxr-xr-x 2 root root 3 Jan 7 04:21 test1/
drwxr-xr-x 2 root root 3 Jan 7 04:21 test2/
drwxr-xr-x 2 root root 3 Jan 7 04:21 test3/
$ for n in {1..3}; do ll "test$n"; done
total 1
-rw-r--r-- 1 root root 0 Jan 7 04:21 testfile.png
total 1
-rw-r--r-- 1 root root 0 Jan 7 04:21 testfile.png
total 1
-rw-r--r-- 1 root root 0 Jan 7 04:21 testfile.png
$ ./script.sh test1 test2/ test3
/root/temp/test1/testfile.png
/root/temp/test2/testfile.png
/root/temp/test3/testfile.png
Run Code Online (Sandbox Code Playgroud)
原始解决方案:
for file in "${@%/}/"*png; do
echo "$file"
done
Run Code Online (Sandbox Code Playgroud)
${@%/} 将修剪参数末尾的任何 / ,然后 / 外部会将其添加回来 - 或将其添加到任何没有参数的参数中。