[英]bash shell script copy first file with certain extension to current directory
I have a directory filled with multiple .c source files and I am trying to write a shell script in another directory that will copy the first .c file from the previous directory, compile it, run it, and delete it. 我有一个目录充满了多个.c源文件,我试图在另一个目录中编写一个shell脚本,该目录将从前一个目录复制第一个.c文件,编译它,运行它并删除它。 Now I understand how to compile, run, and delete the files but I am stumped as to how get only one .c file without knowing its name when there are multiple files with the same extension in the directory?
现在我了解了如何编译,运行和删除文件,但是如果在目录中有多个具有相同扩展名的文件时,如何在不知道其名称的情况下只获取一个.c文件我感到困惑?
One way is to use a loop, then break out after the first iteration: 一种方法是使用循环,然后在第一次迭代后中断:
for f in dir/*.c; do
cp "$f" .
# compile
# run
# delete
break
done
You haven't specified how you define "the first", but you can use set
for this: 您尚未指定如何定义“第一个”,但您可以使用
set
来实现此目的:
set -- source_dir/*.c
cp "$1" .
# ...
rm "$1"
Assuming that you by "first" mean the first file in a sorted list. 假设您通过“first”表示排序列表中的第一个文件。
A for loop works fine, but you could also do: for循环工作正常,但你也可以这样做:
file=`ls -1 dir/*.c | head -1`
# compile $file && run $file && delete $file
In bash you can use arrays: 在bash中你可以使用数组:
files=(*.c)
echo "compiling ${files[0]}"
compile ${files[0]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.