Bash shell script copy the first file with a specific extension to the current directory

I have a directory filled with several .c source files and I'm trying to write a shell script in another directory that will copy the first .c file from the previous directory, compile it, run and delete, Now I understand how to compile, run and delete files , but I don’t understand how to get only one .c file without knowing its name when there are several files in the directory with the same extension?

+4
source share
4 answers

One way is to use a loop and then exit after the first iteration:

for f in dir/*.c; do cp "$f" . # compile # run # delete break done 
+4
source

You did not specify how you define "first", but you can use set to do this:

 set -- source_dir/*.c cp "$1" . # ... rm "$1" 
+1
source

Assuming you are "first" mean the first file in a sorted list.

A for the loop works fine, but you can also do:

 file=`ls -1 dir/*.c | head -1` # compile $file && run $file && delete $file 
+1
source

In bash you can use arrays:

 files=(*.c) echo "compiling ${files[0]}" compile ${files[0]} 
+1
source

All Articles