简体   繁体   中英

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. 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?

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 -- source_dir/*.c
cp "$1" .
# ...
rm "$1"

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

A for loop works fine, but you could also do:

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

In bash you can use arrays:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM